diff --git "a/data/dataset_Pharmacogenetics.csv" "b/data/dataset_Pharmacogenetics.csv" new file mode 100644--- /dev/null +++ "b/data/dataset_Pharmacogenetics.csv" @@ -0,0 +1,90704 @@ +"keyword","repo_name","file_path","file_extension","file_size","line_count","content","language" +"Pharmacogenetics","Illumina/Polaris","release-notes/v1.0/vc1_0.md",".md","6030","155","[TOC]: # + +# Table of Contents +- [Get the data](#get-the-data) +- [Input sources](#input-sources) +- [Populations used](#populations-used) +- [Software used](#software-used) +- [Dataset summary](#dataset-summary) + - [Allele frequency](#allele-frequency) +- [Validation results](#validation-results) + - [Validation methods](#validation-methods) + - [Pedigree consistency](#pedigree-consistency) + - [HWE](#hwe) +- [References](#references) + + +## Get the data + +The easiest way to get the VC1.0 VCF is to use wget to download the data from +the `illumina-polaris` AWS S3 bucket: + +```bash +$: wget https://s3.amazonaws.com/illumina-polaris/vc1_0.vcf.gz +$: wget https://s3.amazonaws.com/illumina-polaris/vc1_0.vcf.gz.tbi +``` + +## Input sources + +VC1.0 candidate SV calls were derived from 4 sources: + +| Data source | SV type | # candidates | +|:------------------------------------------------------------|:---------|-------------:| +| [Pop-Manta][1.1] | DEL, INS | 174,532 | +| [PG-pop][1.2] | DEL | 9,740 | +| [Parliament insertions][1.3][1](#English2015) | INS | 233 | +| [PopIns Icelandic insertions][1.4][2](#Kehr2017) | INS | 483 | +| **Total** | DEL, INS | **184,988** | + +Of these candidate loci, **183,098** were bi-allelic in at least one sample in +this release. + +## Populations used + +VC1.0 candidate calls were evaluated on 243 samples from: +* [HiSeqX Diversity Panel][2.1] +* [HiSeqX PGx Panel][2.2] +* [HiSeq2000 Platinum Genomes pedigree][2.3] +* [HiSeqX Platinum Genomes parents and grandparents][2.4] + +Variants are reported for 221 individuals, including NA12878, NA12877, the +entire Diversity Panel, and 69 members of the PGx panel (excluding NA18942). + +## Software used + +| Process | Tool | Version | +|:-----------------------------------|:------------|------------:| +| Graph realignment & joint calling | `paragraph` | pre-release | + +## Dataset summary + +### Allele frequency + +The allele frequency distribution is as expected — there are more rare SVs +than common SVs. Most SVs have minor allele frequencies (MAFs) greater than 5%. + +![Minor allele frequency](images/vc1_0/minor_allele_frequency.png) + +## Validation results + +### Validation methods + +Calls were validated using: +* Platinum Genomes pedigree consistency +* Diversity / PGx panel HWE + +### Pedigree consistency + +Consistency status within the Platinum Genomes pedigree was as follows: + +| Status | Count | Percent | +|:----------------------|-------:|--------:| +| Pedigree consistent | 37,792 | 54.01% | +| Uniformly homozygous | 99,909 | 20.43% | +| Pedigree inconsistent | 46,578 | 25.18% | +| Other | 709 | 0.38% | + +![Pedigree Hamming distance](images/vc1_0/pedigree_hamming_distance.png) + +When considering all variant types that could be assessed for pedigree +consistency. the Hamming distances for pedigree inconsistent loci was generally +≤ 3. This suggests that most of these failing calls were incorrectly +genotyped at a few members within the pedigree but might be recovered with +improved genotyping methods. + +![Pedigree Hamming distance by type](images/vc1_0/pedigree_hamming_distance_by_type.png) + +When breaking down performance by variant type, we see that in general, more +pedigree-consistent calls were derived from deletion candidates than insertion +candidates. The observation that few loci seem to have extensive genotyping +errors within the pedigree holds. + +As described [in the wiki][3.1.1], we cannot assess the consistency status of +variants that are uniformly homozygous within the pedigree. + +### HWE + +Loci with MAF > 5% and chi-squared test p-value ≥ 0.05 were considered to +be in HWE. **71,505** total loci satisfied these criteria. + +We chose the MAF cutoff to ensure that we had a sufficient number of samples to +observe heterozygous and homozygous alternate individuals within the population +if HWE held. While the p-value cutoff is conservative, we felt that this was the +right choice for our initial dataset release. + +The p-value distribution indicates that many of these loci *do not* satisfy our +HWE criteria: + +![HWE p-values](images/vc1_0/hwe_pvalues.png) + +Loci may not be in HWE for two reasons: +1. `paragraph` genotyping errors +2. Insufficient genotype observations (likely due to low MAF) + +When we evaluate the HWE ternary plot, we do see an enrichment of alleles with +low MAF (lower right corner of the triangle) that are not in HWE, which +substantiates option 2. These loci may be in HWE in a larger or more uniform +population. + +![HWE ternary plot](images/vc1_0/hwe_ternary_plot.png) + +We expect that as our joint calling methods improve, we will see more loci +satisfy our HWE requirements, provided there are no other factors causing +deviation from HWE. + +## References + +1. English, et al (2015) Assessing structural + variation in a personal genome-towards a human reference diploid genome. *BMC + Genomics.* 16:286 [doi:10.1186/s12864-015-1479-3][6.2] +2. Kehr, et al (2017) Diversity in non-repetitive human + sequences not found in the reference genome. *Nat Genet.* 49(4):588-593. + [doi: 10.1038/ng.3801][6.1] + +[1.1]: ../../../wiki/Input-Data-Sources#pop-manta +[1.2]: ../../../wiki/Input-Data-Sources#pg-pop +[1.3]: ../../../wiki/Input-Data-Sources#parliament-insertions +[1.4]: ../../../wiki/Input-Data-Sources#popins-icelandic-insertions +[2.1]: ../../../wiki/HiSeqX-Diversity-Panel +[2.2]: ../../../wiki/HiSeqX-PGx-Panel +[2.3]: ../../../wiki/Sample-Information#pg-hiseq2000 +[2.4]: ../../../wiki/Sample-Information#pg-hiseqx +[3.1.1]: ../../../wiki/Validation-Methods#unassessable-loci +[6.1]: https://www.nature.com/ng/journal/v49/n4/full/ng.3801.html +[6.2]: https://bmcgenomics.biomedcentral.com/articles/10.1186/s12864-015-1479-3 +","Markdown" +"Pharmacogenetics","Illumina/Polaris","cohorts/1000_genomes/1kg_sample_metadata.md",".md","5530","198","

Sample metadata

+ + +### Genome-wide coverage +* This is the genome-wide coverage in the framework of our CNV calling pipeline. In this sense it is not strictly read based coverage, but rather the average number of reads that fall into our 1kb depth bins. +* The methods here follow from Canvas CNV calling depth binning convention, updated to fit within the (very similar) Dragen CNV calling paradigm. For a detailed description of the Canvas depth binning method see Section 5.1 of the software design description ([link](https://github.com/Illumina/canvas/raw/master/SoftwareDesignDescription.pdf)). + +__file:__ [data/average_count_per_bin.csv](./data/average_count_per_bin.csv) + + +begining of file: + + + + sample + HG00096 114 + HG00097 109 + HG00099 127 + HG00100 106 + HG00101 114 + Name: average count per bin, dtype: int64 + + + +distribution of data: + + + +![png](plots/1kg_sample_metadata_4_3.png) + + +### Quantification of replication timing and GC bias +* In our standard normalization pipeline we do a GC bias adjustment, while when dealing with cell lines we add in an additional adjusment for differences in replication timing across the genome. +* Shown here is the average absolute value of change in the depth value before and after each of these adjustments. These metrics give us an idea of the magnatude of each of these biases in the samples. +* For cell lines the replication adjustment happens after GC adjustment, so we record the change after each adjusment (GC-raw, and rep-GC) as well as after both adjustments (rep-raw). + +__file:__ [data/bias_adjustment_pct_changed.csv](./data/bias_adjustment_pct_changed.csv) + + +begining of file: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GC-rawrep-GCrep-raw
HG000960.0200.0180.027
HG000970.0240.0270.038
HG000990.0230.0320.040
HG001000.0180.0190.026
HG001010.0240.0190.029
+ + + +### Quantification of depth variance +* One key metric we use for quantification of data quality for CNV pipelines is the variance in our depth of coverage. +* We calculate this as the median-absolute-deviation of normalized, binned depth data across various length scales. +* The 1-bin variance is simply the variance of the depth bin data, the 10 and 100 bin variance are the variance of larger length window (roughly 10kb and 100kb, respectively). These larger windows better model noise in CNV calling that is likely to cause false positive and false negitive calls, as these represent more systematic (as opposed to random) variance. +* This variance metadata is shown for depth after normalization and GC adjustment, with and without the additional adjustment for genome-wide replication timing trends. + +__file:__ [data/depth_variance.csv](./data/depth_variance.csv) + + +begining of file: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
adjustment-typeGCGC+replication
window-size (# of bins)110100110100
HG000967.462.811.857.362.401.04
HG000977.693.282.517.492.531.22
HG000997.593.643.027.262.561.38
HG001007.552.801.817.472.411.01
HG001017.472.821.877.372.411.07
+ + + + +92 samples are filtered at a z-score=3 cutoff. + + + +![png](plots/1kg_sample_metadata_10_1.png) + + + +List of filtered samples. + + + HG00111 HG00313 HG00327 HG00335 HG00732 HG01113 HG01133 HG01137 + HG01259 HG01272 HG01303 HG01308 HG01359 HG01495 HG01551 HG01631 + HG01702 HG01705 HG01761 HG01850 HG01873 HG01917 HG01961 HG01977 + HG01980 HG02054 HG02086 HG02144 HG02450 HG02651 HG02652 HG02808 + HG02810 HG02811 HG02816 HG02817 HG02819 HG02839 HG02947 HG03055 + HG03077 HG03401 HG03428 HG03634 HG03643 HG03644 HG03713 HG03796 + HG03884 NA12006 NA12749 NA12777 NA12814 NA18520 NA18946 NA19080 + NA19113 NA19372 NA19472 NA19473 NA19655 NA19747 NA20274 NA20532 + NA20534 NA20535 NA20581 NA20786 NA20803 NA20826 NA20828 NA20846 + NA20875 NA20886 NA20888 NA20903 NA21089 NA21111 NA21116 NA21118 + NA21120 NA21127 + +","Markdown" +"Pharmacogenetics","Illumina/Polaris","cohorts/1000_genomes/band_level_events.md",".md","44830","2880","## Band-level events chromosome level coverage +* Here we are looking at all samples with analmolous read-depth spanning at least one chromosome band +* Some of these samples are noisy and get filtered with the noise filter + + 67 samples with large chromosomal alteration spanning + at lease two bands: + ``` + HG00106 HG00110 HG00141 HG00271 HG00275 HG00285 HG00611 HG00614 + HG00662 HG00736 HG01167 HG01512 HG01528 HG01617 HG01917 HG02144 + HG02164 HG02278 HG02392 HG02465 HG02855 HG03061 HG03238 HG03363 + HG03439 HG03455 HG03521 HG03869 HG03890 HG03928 HG04161 NA06984 + NA07037 NA11843 NA11920 NA11992 NA12046 NA12058 NA12340 NA12341 + NA12342 NA12717 NA12748 NA12814 NA18522 NA18523 NA18579 NA18592 + NA18635 NA18644 NA18956 NA19010 NA19083 NA19213 NA19355 NA19454 + NA19652 NA19750 NA20342 NA20509 NA20517 NA20533 NA20538 NA20795 + NA20911 NA21088 NA21118 ``` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
madmedianz-score
HG00106chr1515q13.2-15q13.326.5132.544.3
HG00110chr1818q22.2-18q238.7105.211.0
chr55p15.33-5p14.18.294.8-15.2
HG00141chr1515q13.2-15q13.326.1131.643.1
HG00271chr88q24.13-8q24.38.7106.929.1
HG00275chr44q31.3-4q35.29.1110.248.7
HG00285chr22q12.3-2q37.37.894.6-39.1
HG00611chr44p16.2-4p16.116.4126.755.5
HG00614chr55q11.2-5q12.114.179.4-63.3
HG00662chr66p21.32-6p21.210.0118.430.2
HG00736chr44q35.1-4q35.210.3114.930.4
HG01167chr77q31.1-7q32.37.089.9-44.7
HG01512chr1717p13.2-17p13.111.589.2-21.8
HG01528chr55q33.3-5q3419.8108.233.8
HG01617chr1212q21.2-12q21.3113.179.8-24.7
HG01917chr1111q13.1-11q13.210.8112.410.6
chr1616p11.2-16q11.211.1110.311.3
chr1919p13.3-19p1212.0112.910.4
19q13.32-19q13.3311.8115.011.2
chr66p22.2-6p21.3211.2109.911.9
HG02144chr44q13.3-4q35.29.0106.235.2
HG02164chr22q14.2-2q14.38.593.6-18.0
HG02278chr77q36.1-7q36.39.088.5-29.5
HG02392chr22q22.2-2q24.28.094.0-15.2
HG02465chr1919q13.12-19q13.439.094.3-10.2
chr66p22.3-6p21.319.194.6-10.7
HG02855chr1515q14-15q15.38.094.6-16.9
HG03061chr1818q22.1-18q2310.055.5-127.5
chr33q26.2-3q2910.1146.9236.4
HG03238chr88q24.22-8q24.311.386.0-42.9
HG03363chr1111p15.5-11p1211.7137.8162.4
HG03439chr99q34.11-9q34.39.2114.217.9
HG03455chr1111q21-11q22.28.294.8-14.4
HG03521chr2020q11.21-20q13.138.194.2-16.8
HG03869chr1010q21.1-10q26.38.5107.441.3
chr1313q33.2-13q347.792.6-17.9
HG03890chr1616p13.11-16p12.318.4132.649.5
HG03928chr1212p13.33-12q13.118.7105.112.3
HG04161chr1313q14.11-13q22.18.094.1-20.2
chr22q24.1-2q24.37.892.3-25.6
NA06984chr1414q31.1-14q32.3311.7149.0188.1
chr1818q22.2-18q238.551.3-103.7
NA07037chr1111q23.3-11q258.6108.329.4
NA11843chr1313q31.1-13q349.0105.721.5
NA11920chr66q23.3-6q24.29.590.2-30.8
NA11992chr66p25.3-6p22.38.394.9-23.7
NA12046chr1111q14.2-11q258.6105.428.9
NA12058chr1515q14-15q26.39.0117.156.5
NA12340chr2020q13.13-20q13.328.089.0-34.3
NA12341chr1414q31.3-14q32.339.8133.997.4
chr44q26-4q35.28.3109.049.1
NA12342chr1111q22.1-11q23.29.469.8-107.8
NA12717chr55p14.1-5p1215.4134.0135.3
NA12748chr1313q31.2-13q3410.4133.2124.6
NA12814chr99q22.2-9q34.38.9105.716.3
NA18522chr1212p13.33-12q13.28.9105.111.9
NA18523chr11p13.2-1p13.116.381.9-60.0
NA18579chr22p23.2-2p23.121.1107.520.4
NA18592chr88p23.3-8p23.27.993.2-12.2
8q21.2-8q24.38.2107.052.4
NA18635chr88p23.3-8p127.993.8-27.9
NA18644chr22q32.1-2q37.37.493.2-47.6
chr44q34.3-4q35.28.1106.718.8
NA18956chr44q32.1-4q35.28.8105.023.3
NA19010chr22q12.2-2q12.320.8122.241.2
NA19083chr99q21.11-9q21.138.294.1-10.7
NA19213chr11q42.2-1q448.394.6-24.2
NA19355chr22q22.2-2q24.38.775.1-78.8
NA19454chr2020p13-20p11.2110.0138.6120.0
NA19652chr1212q12-12q24.338.6105.713.8
NA19750chr22q22.2-2q24.17.972.3-73.1
NA20342chr22p22.3-2p22.28.088.2-37.1
NA20509chr1717p13.3-17p11.29.287.6-27.9
chr55q31.1-5q35.39.0115.778.6
NA20517chr88p22-8p21.18.394.2-27.6
chr99q21.31-9q34.38.8105.619.5
NA20533chr1313q14.3-13q3410.5136.2141.3
chr1717p13.3-17p13.110.872.0-44.1
NA20538chr44q34.3-4q35.28.9106.016.9
NA20795chr99p22.2-9p22.120.1106.814.0
NA20911chr1515q26.1-15q26.211.084.7-37.3
NA21088chr33q25.2-3q25.3120.994.9-14.3
NA21118chr1818q22.3-18q238.590.8-21.0
chr55q21.3-5q35.39.1110.069.4
+ + + +

NA18579

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr22p23.2-2p23.1107.521.120.4
+ + + +![png](plots/band_level_events_4_2.png) + + + +

NA07037

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr1111q23.3-11q25108.38.629.4
+ + + +![png](plots/band_level_events_4_5.png) + + + +

HG00141

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr1515q13.2-15q13.3131.626.143.1
+ + + +![png](plots/band_level_events_4_8.png) + + + +

NA19355

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr22q22.2-2q24.375.18.7-78.8
+ + + +![png](plots/band_level_events_4_11.png) + + + +

NA20533

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr1313q14.3-13q34136.210.5141.3
chr1717p13.3-17p13.172.010.8-44.1
+ + + +![png](plots/band_level_events_4_14.png) + + + +

HG02392

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr22q22.2-2q24.294.08.0-15.2
+ + + +![png](plots/band_level_events_4_17.png) + + + +

HG01512

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr1717p13.2-17p13.189.211.5-21.8
+ + + +![png](plots/band_level_events_4_20.png) + + + +

HG00285

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr22q12.3-2q37.394.67.8-39.1
+ + + +![png](plots/band_level_events_4_23.png) + + + +

NA18635

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr88p23.3-8p1293.87.9-27.9
+ + + +![png](plots/band_level_events_4_26.png) + + + +

NA20538

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr44q34.3-4q35.2106.08.916.9
+ + + +![png](plots/band_level_events_4_29.png) + + + +

NA11843

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr1313q31.1-13q34105.79.021.5
+ + + +![png](plots/band_level_events_4_32.png) + + + +

HG01917

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr1111q13.1-11q13.2112.410.810.6
chr1616p11.2-16q11.2110.311.111.3
chr1919p13.3-19p12112.912.010.4
19q13.32-19q13.33115.011.811.2
chr66p22.2-6p21.32109.911.211.9
+ + + +![png](plots/band_level_events_4_35.png) + + + +

HG03455

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr1111q21-11q22.294.88.2-14.4
+ + + +![png](plots/band_level_events_4_38.png) + + + +

NA06984

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr1414q31.1-14q32.33149.011.7188.1
chr1818q22.2-18q2351.38.5-103.7
+ + + +![png](plots/band_level_events_4_41.png) + + + +

NA11920

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr66q23.3-6q24.290.29.5-30.8
+ + + +![png](plots/band_level_events_4_44.png) + + + +

NA12340

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr2020q13.13-20q13.3289.08.0-34.3
+ + + +![png](plots/band_level_events_4_47.png) + + + +

NA21118

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr1818q22.3-18q2390.88.5-21.0
chr55q21.3-5q35.3110.09.169.4
+ + + +![png](plots/band_level_events_4_50.png) + + + +

NA18523

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr11p13.2-1p13.181.916.3-60.0
+ + + +![png](plots/band_level_events_4_53.png) + + + +

HG01528

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr55q33.3-5q34108.219.833.8
+ + + +![png](plots/band_level_events_4_56.png) + + + +

NA19083

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr99q21.11-9q21.1394.18.2-10.7
+ + + +![png](plots/band_level_events_4_59.png) + + + +

NA19213

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr11q42.2-1q4494.68.3-24.2
+ + + +![png](plots/band_level_events_4_62.png) + + + +

HG03439

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr99q34.11-9q34.3114.29.217.9
+ + + +![png](plots/band_level_events_4_65.png) + + + +

HG03061

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr1818q22.1-18q2355.510.0-127.5
chr33q26.2-3q29146.910.1236.4
+ + + +![png](plots/band_level_events_4_68.png) + + + +

NA20795

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr99p22.2-9p22.1106.820.114.0
+ + + +![png](plots/band_level_events_4_71.png) + + + +

NA21088

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr33q25.2-3q25.3194.920.9-14.3
+ + + +![png](plots/band_level_events_4_74.png) + + + +

HG00110

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr1818q22.2-18q23105.28.711.0
chr55p15.33-5p14.194.88.2-15.2
+ + + +![png](plots/band_level_events_4_77.png) + + + +

NA18522

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr1212p13.33-12q13.2105.18.911.9
+ + + +![png](plots/band_level_events_4_80.png) + + + +

NA20342

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr22p22.3-2p22.288.28.0-37.1
+ + + +![png](plots/band_level_events_4_83.png) + + + +

NA12748

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr1313q31.2-13q34133.210.4124.6
+ + + +![png](plots/band_level_events_4_86.png) + + + +

NA20509

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr1717p13.3-17p11.287.69.2-27.9
chr55q31.1-5q35.3115.79.078.6
+ + + +![png](plots/band_level_events_4_89.png) + + + +

NA18644

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr22q32.1-2q37.393.27.4-47.6
chr44q34.3-4q35.2106.78.118.8
+ + + +![png](plots/band_level_events_4_92.png) + + + +

NA12717

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr55p14.1-5p12134.015.4135.3
+ + + +![png](plots/band_level_events_4_95.png) + + + +

NA18592

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr88p23.3-8p23.293.27.9-12.2
8q21.2-8q24.3107.08.252.4
+ + + +![png](plots/band_level_events_4_98.png) + + + +

HG02144

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr44q13.3-4q35.2106.29.035.2
+ + + +![png](plots/band_level_events_4_101.png) + + + +

NA20911

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr1515q26.1-15q26.284.711.0-37.3
+ + + +![png](plots/band_level_events_4_104.png) + + + +

HG03238

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr88q24.22-8q24.386.011.3-42.9
+ + + +![png](plots/band_level_events_4_107.png) + + + +

HG04161

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr1313q14.11-13q22.194.18.0-20.2
chr22q24.1-2q24.392.37.8-25.6
+ + + +![png](plots/band_level_events_4_110.png) + + + +

NA19652

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr1212q12-12q24.33105.78.613.8
+ + + +![png](plots/band_level_events_4_113.png) + + + +

HG03521

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr2020q11.21-20q13.1394.28.1-16.8
+ + + +![png](plots/band_level_events_4_116.png) + + + +

HG03869

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr1010q21.1-10q26.3107.48.541.3
chr1313q33.2-13q3492.67.7-17.9
+ + + +![png](plots/band_level_events_4_119.png) + + + +

NA12058

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr1515q14-15q26.3117.19.056.5
+ + + +![png](plots/band_level_events_4_122.png) + + + +

NA19454

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr2020p13-20p11.21138.610.0120.0
+ + + +![png](plots/band_level_events_4_125.png) + + + +

NA19010

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr22q12.2-2q12.3122.220.841.2
+ + + +![png](plots/band_level_events_4_128.png) + + + +

HG01617

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr1212q21.2-12q21.3179.813.1-24.7
+ + + +![png](plots/band_level_events_4_131.png) + + + +

HG02278

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr77q36.1-7q36.388.59.0-29.5
+ + + +![png](plots/band_level_events_4_134.png) + + + +

HG03928

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr1212p13.33-12q13.11105.18.712.3
+ + + +![png](plots/band_level_events_4_137.png) + + + +

HG02164

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr22q14.2-2q14.393.68.5-18.0
+ + + +![png](plots/band_level_events_4_140.png) + + + +

NA18956

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr44q32.1-4q35.2105.08.823.3
+ + + +![png](plots/band_level_events_4_143.png) + + + +

NA20517

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr88p22-8p21.194.28.3-27.6
chr99q21.31-9q34.3105.68.819.5
+ + + +![png](plots/band_level_events_4_146.png) + + + +

HG00736

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr44q35.1-4q35.2114.910.330.4
+ + + +![png](plots/band_level_events_4_149.png) + + + +

HG03363

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr1111p15.5-11p12137.811.7162.4
+ + + +![png](plots/band_level_events_4_152.png) + + + +

NA11992

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr66p25.3-6p22.394.98.3-23.7
+ + + +![png](plots/band_level_events_4_155.png) + + + +

HG00275

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr44q31.3-4q35.2110.29.148.7
+ + + +![png](plots/band_level_events_4_158.png) + + + +

HG00662

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr66p21.32-6p21.2118.410.030.2
+ + + +![png](plots/band_level_events_4_161.png) + + + +

NA12814

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr99q22.2-9q34.3105.78.916.3
+ + + +![png](plots/band_level_events_4_164.png) + + + +

NA12341

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr1414q31.3-14q32.33133.99.897.4
chr44q26-4q35.2109.08.349.1
+ + + +![png](plots/band_level_events_4_167.png) + + + +

NA12342

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr1111q22.1-11q23.269.89.4-107.8
+ + + +![png](plots/band_level_events_4_170.png) + + + +

HG00614

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr55q11.2-5q12.179.414.1-63.3
+ + + +![png](plots/band_level_events_4_173.png) + + + +

HG00106

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr1515q13.2-15q13.3132.526.544.3
+ + + +![png](plots/band_level_events_4_176.png) + + + +

HG00271

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr88q24.13-8q24.3106.98.729.1
+ + + +![png](plots/band_level_events_4_179.png) + + + +

NA19750

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr22q22.2-2q24.172.37.9-73.1
+ + + +![png](plots/band_level_events_4_182.png) + + + +

HG01167

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr77q31.1-7q32.389.97.0-44.7
+ + + +![png](plots/band_level_events_4_185.png) + + + +

NA12046

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr1111q14.2-11q25105.48.628.9
+ + + +![png](plots/band_level_events_4_188.png) + + + +

HG00611

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr44p16.2-4p16.1126.716.455.5
+ + + +![png](plots/band_level_events_4_191.png) + + + +

HG02465

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr1919q13.12-19q13.4394.39.0-10.2
chr66p22.3-6p21.3194.69.1-10.7
+ + + +![png](plots/band_level_events_4_194.png) + + + +

HG02855

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr1515q14-15q15.394.68.0-16.9
+ + + +![png](plots/band_level_events_4_197.png) + + + +

HG03890

+ + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
chr1616p13.11-16p12.3132.618.449.5
+ + + +![png](plots/band_level_events_4_200.png) + +","Markdown" +"Pharmacogenetics","Illumina/Polaris","cohorts/1000_genomes/1kg_sample_UPD.md",".md","727","34","# 1000 genomes uniparental isodisomy identification +* These samples were mostly identified with a semi-automated pipeline, backed up by manual curation +* A more robust pipeline is in the works, but we are including these as they are good examples for testing. This may not be a comprehensive list of UPDs and mosaic UPDs in this cohort. + +### NA12874 -- large single ROH on 1q, presumably UPD + + +![png](plots/1kg_sample_UPD_3_0.png) + + +### NA19462 -- mosaic UPD on 1p + + +![png](plots/1kg_sample_UPD_5_0.png) + + +### HG00110 -- mosaic UPD on 5q + + +![png](plots/1kg_sample_UPD_7_0.png) + + +### NA19788 -- mosaic UPD on 9q + + +![png](plots/1kg_sample_UPD_9_0.png) + + +### NA20282 -- mosaic UPD on 3q + + +![png](plots/1kg_sample_UPD_11_0.png) + +","Markdown" +"Pharmacogenetics","Illumina/Polaris","cohorts/1000_genomes/x_chrom_loss.md",".md","16182","1141","## Samples with x-chromosome loss + + +
32 female samples with x-chromosome dropout:
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG03511female1.000.0
NA19332female1.020.0
NA20506female1.080.0
HG00361female1.140.0
NA20530female1.140.0
NA19395female1.140.0
NA20533female1.200.0
HG01366female1.300.0
HG03019female1.300.0
HG00154female1.360.0
NA19054female1.360.0
HG04202female1.380.0
NA20832female1.500.0
NA18864female1.500.0
HG01137female1.520.0
NA18978female1.540.0
HG03055female1.600.0
NA20790female1.620.0
HG00732female1.640.0
NA18963female1.640.0
HG03401female1.700.0
HG02144female1.740.0
NA20769female1.760.0
HG00864female1.760.0
HG02652female1.760.0
NA18520female1.760.0
HG03016female1.760.0
NA11933female1.780.0
NA20535female1.780.0
HG01806female1.780.0
HG03634female1.800.0
NA20892female1.800.0
+ + + +

HG03511

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG03511female1.00.0
+ + + +![png](plots/x_chrom_loss_4_2.png) + + + +

NA19332

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
NA19332female1.020.0
+ + + +![png](plots/x_chrom_loss_4_5.png) + + + +

NA20506

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
NA20506female1.080.0
+ + + +![png](plots/x_chrom_loss_4_8.png) + + + +

HG00361

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG00361female1.140.0
+ + + +![png](plots/x_chrom_loss_4_11.png) + + + +

NA20530

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
NA20530female1.140.0
+ + + +![png](plots/x_chrom_loss_4_14.png) + + + +

NA19395

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
NA19395female1.140.0
+ + + +![png](plots/x_chrom_loss_4_17.png) + + + +

NA20533

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
NA20533female1.20.0
+ + + +![png](plots/x_chrom_loss_4_20.png) + + + +

HG01366

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG01366female1.30.0
+ + + +![png](plots/x_chrom_loss_4_23.png) + + + +

HG03019

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG03019female1.30.0
+ + + +![png](plots/x_chrom_loss_4_26.png) + + + +

HG00154

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG00154female1.360.0
+ + + +![png](plots/x_chrom_loss_4_29.png) + + + +

NA19054

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
NA19054female1.360.0
+ + + +![png](plots/x_chrom_loss_4_32.png) + + + +

HG04202

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG04202female1.380.0
+ + + +![png](plots/x_chrom_loss_4_35.png) + + + +

NA20832

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
NA20832female1.50.0
+ + + +![png](plots/x_chrom_loss_4_38.png) + + + +

NA18864

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
NA18864female1.50.0
+ + + +![png](plots/x_chrom_loss_4_41.png) + + + +

HG01137

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG01137female1.520.0
+ + + +![png](plots/x_chrom_loss_4_44.png) + + + +

NA18978

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
NA18978female1.540.0
+ + + +![png](plots/x_chrom_loss_4_47.png) + + + +

HG03055

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG03055female1.60.0
+ + + +![png](plots/x_chrom_loss_4_50.png) + + + +

NA20790

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
NA20790female1.620.0
+ + + +![png](plots/x_chrom_loss_4_53.png) + + + +

HG00732

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG00732female1.640.0
+ + + +![png](plots/x_chrom_loss_4_56.png) + + + +

NA18963

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
NA18963female1.640.0
+ + + +![png](plots/x_chrom_loss_4_59.png) + + + +

HG03401

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG03401female1.70.0
+ + + +![png](plots/x_chrom_loss_4_62.png) + + + +

HG02144

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG02144female1.740.0
+ + + +![png](plots/x_chrom_loss_4_65.png) + + + +

NA20769

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
NA20769female1.760.0
+ + + +![png](plots/x_chrom_loss_4_68.png) + + + +

HG00864

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG00864female1.760.0
+ + + +![png](plots/x_chrom_loss_4_71.png) + + + +

HG02652

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG02652female1.760.0
+ + + +![png](plots/x_chrom_loss_4_74.png) + + + +

NA18520

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
NA18520female1.760.0
+ + + +![png](plots/x_chrom_loss_4_77.png) + + + +

HG03016

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG03016female1.760.0
+ + + +![png](plots/x_chrom_loss_4_80.png) + + + +

NA11933

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
NA11933female1.780.0
+ + + +![png](plots/x_chrom_loss_4_83.png) + + + +

NA20535

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
NA20535female1.780.0
+ + + +![png](plots/x_chrom_loss_4_86.png) + + + +

HG01806

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG01806female1.780.0
+ + + +![png](plots/x_chrom_loss_4_89.png) + + + +

HG03634

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG03634female1.80.0
+ + + +![png](plots/x_chrom_loss_4_92.png) + + + +

NA20892

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
NA20892female1.80.0
+ + + +![png](plots/x_chrom_loss_4_95.png) + +","Markdown" +"Pharmacogenetics","Illumina/Polaris","cohorts/1000_genomes/x_chrom_gain.md",".md","2793","196","## Samples with x-chromosome gain + + +
5 female samples with x-chromosome gain:
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
NA20821female2.900.0
HG02805female2.600.0
NA18946female2.440.0
HG02102female2.260.0
HG00261female2.200.0
+ + + +

NA20821

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
NA20821female2.90.0
+ + + +![png](plots/x_chrom_gain_3_2.png) + + + +

HG02805

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG02805female2.60.0
+ + + +![png](plots/x_chrom_gain_3_5.png) + + + +

NA18946

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
NA18946female2.440.0
+ + + +![png](plots/x_chrom_gain_3_8.png) + + + +

HG02102

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG02102female2.260.0
+ + + +![png](plots/x_chrom_gain_3_11.png) + + + +

HG00261

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG00261female2.20.0
+ + + +![png](plots/x_chrom_gain_3_14.png) + +","Markdown" +"Pharmacogenetics","Illumina/Polaris","cohorts/1000_genomes/chromosome_level_events.md",".md","20233","955","## Whole chromosome level coverage +* This is the per-chromosome coverage as calculated with our CNV depth binning approach. +* Power to detect chromosome-wide events varies per chromosome, but in general we are fairly well powered to detect events at greater than 5-10% purity with no additional modeling. +* From the below plot, it can be seen that some chromosomes are a bit noisier than others, particularly chr9, chr12, and chr19. When calling mosaic trisomy events, we account for the baseline noise and variance across the population. + +__file:__ [data/chromosome_coverage.csv](./data/chromosome_coverage.csv) + +![png](plots/chromosome_level_events_3_1.png) +*shown here with values doubled, such that a value of 2 represents the expected coverage for a normal diploid segment + + +## Karyotype-band level coverage +* Here we break down coverage by karyotype band, with coordinates obtained from the UCSC table browser. +* We look at this data for two major reasons: + * We want to distinguish whole chromosome mosaic events, from large CNVs of higher purity. To do this, we need finer resolution data to understand if an event covers the full chromosome or just part of it. + * We want to identify large CNVs covering multiple chromosome bands. These are unlikly to be in the germline of these presumably healthy individuals, so we will flag these as well to 1) use as test cases mimicking pathogenic variants and 2) exclude these individuals from background calculations. + +There are two main files here, one with per-band coverage across each sample, and a second with consecutive bands with normal or anamolous coverage merged using a rough segmentation method. +* __band x sample file:__ [data/band_stats.csv.gz](./data/band_stats.csv.gz) +* __merged-band file:__ [data/chrom_stats.csv.gz](./data/chrom_stats.csv.gz) + +28 samples with full chromosome alteration: + + HG00142 HG00189 HG00623 HG01137 HG01303 HG01357 HG01414 HG01506 + HG01602 HG01702 HG01704 HG02322 HG02409 HG02485 HG02634 HG02651 + HG02652 HG02805 HG03118 HG03796 HG03940 HG04198 HG04227 NA12156 + NA19378 NA20348 NA20759 NA21143 + + +chromosomes with trisomies: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
subjectCHROM
HG00142chr11130.49.6169.4
chr13129.69.7144.9
HG00189chr9111.69.147.2
HG00623chr12133.39.584.7
HG01137chr12115.49.039.0
HG01303chr12119.19.348.4
chr5119.19.3142.4
HG01357chr12137.510.495.3
HG01414chr12106.88.712.0
HG01506chr11114.18.978.4
HG01602chr9130.59.7123.8
HG01702chr12109.49.123.7
HG01704chr12106.28.58.8
HG02322chr12139.910.4101.3
HG02409chr9109.28.837.6
HG02485chr12107.78.819.4
HG02634chr11120.08.8111.2
HG02651chr12115.39.238.8
HG02652chr12109.78.824.4
HG02805chr9108.28.933.5
HG03118chr12108.28.620.6
HG03796chr12106.98.917.3
HG03940chr12111.29.028.4
HG04198chr12112.48.231.4
HG04227chr12106.48.78.8
NA12156chr9114.58.458.9
NA19378chr12120.39.651.4
NA20348chr12108.98.722.4
NA20759chr12124.99.363.1
NA21143chr12106.28.112.8
chr14107.28.133.7
chr9106.28.025.5
+ + +67 samples with large chromosomal alteration spanning at lease two bands: + + HG00106 HG00110 HG00141 HG00271 HG00275 HG00285 HG00611 HG00614 + HG00662 HG00736 HG01167 HG01512 HG01528 HG01617 HG01917 HG02144 + HG02164 HG02278 HG02392 HG02465 HG02855 HG03061 HG03238 HG03363 + HG03439 HG03455 HG03521 HG03869 HG03890 HG03928 HG04161 NA06984 + NA07037 NA11843 NA11920 NA11992 NA12046 NA12058 NA12340 NA12341 + NA12342 NA12717 NA12748 NA12814 NA18522 NA18523 NA18579 NA18592 + NA18635 NA18644 NA18956 NA19010 NA19083 NA19213 NA19355 NA19454 + NA19652 NA19750 NA20342 NA20509 NA20517 NA20533 NA20538 NA20795 + NA20911 NA21088 NA21118 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
subjectCHROMband(s)madmedianz-score
HG00106chr1515q13.2-15q13.326.5132.544.3
HG00110chr1818q22.2-18q238.7105.211.0
chr55p15.33-5p14.18.294.8-15.2
HG00141chr1515q13.2-15q13.326.1131.643.1
HG00271chr88q24.13-8q24.38.7106.929.1
HG00275chr44q31.3-4q35.29.1110.248.7
HG00285chr22q12.3-2q37.37.894.6-39.1
HG00611chr44p16.2-4p16.116.4126.755.5
HG00614chr55q11.2-5q12.114.179.4-63.3
HG00662chr66p21.32-6p21.210.0118.430.2
HG00736chr44q35.1-4q35.210.3114.930.4
HG01167chr77q31.1-7q32.37.089.9-44.7
HG01512chr1717p13.2-17p13.111.589.2-21.8
HG01528chr55q33.3-5q3419.8108.233.8
HG01617chr1212q21.2-12q21.3113.179.8-24.7
HG01917chr1111q13.1-11q13.210.8112.410.6
chr1616p11.2-16q11.211.1110.311.3
chr1919p13.3-19p1212.0112.910.4
19q13.32-19q13.3311.8115.011.2
chr66p22.2-6p21.3211.2109.911.9
HG02144chr44q13.3-4q35.29.0106.235.2
HG02164chr22q14.2-2q14.38.593.6-18.0
HG02278chr77q36.1-7q36.39.088.5-29.5
HG02392chr22q22.2-2q24.28.094.0-15.2
HG02465chr1919q13.12-19q13.439.094.3-10.2
chr66p22.3-6p21.319.194.6-10.7
HG02855chr1515q14-15q15.38.094.6-16.9
HG03061chr1818q22.1-18q2310.055.5-127.5
chr33q26.2-3q2910.1146.9236.4
HG03238chr88q24.22-8q24.311.386.0-42.9
HG03363chr1111p15.5-11p1211.7137.8162.4
HG03439chr99q34.11-9q34.39.2114.217.9
HG03455chr1111q21-11q22.28.294.8-14.4
HG03521chr2020q11.21-20q13.138.194.2-16.8
HG03869chr1010q21.1-10q26.38.5107.441.3
chr1313q33.2-13q347.792.6-17.9
HG03890chr1616p13.11-16p12.318.4132.649.5
HG03928chr1212p13.33-12q13.118.7105.112.3
HG04161chr1313q14.11-13q22.18.094.1-20.2
chr22q24.1-2q24.37.892.3-25.6
NA06984chr1414q31.1-14q32.3311.7149.0188.1
chr1818q22.2-18q238.551.3-103.7
NA07037chr1111q23.3-11q258.6108.329.4
NA11843chr1313q31.1-13q349.0105.721.5
NA11920chr66q23.3-6q24.29.590.2-30.8
NA11992chr66p25.3-6p22.38.394.9-23.7
NA12046chr1111q14.2-11q258.6105.428.9
NA12058chr1515q14-15q26.39.0117.156.5
NA12340chr2020q13.13-20q13.328.089.0-34.3
NA12341chr1414q31.3-14q32.339.8133.997.4
chr44q26-4q35.28.3109.049.1
NA12342chr1111q22.1-11q23.29.469.8-107.8
NA12717chr55p14.1-5p1215.4134.0135.3
NA12748chr1313q31.2-13q3410.4133.2124.6
NA12814chr99q22.2-9q34.38.9105.716.3
NA18522chr1212p13.33-12q13.28.9105.111.9
NA18523chr11p13.2-1p13.116.381.9-60.0
NA18579chr22p23.2-2p23.121.1107.520.4
NA18592chr88p23.3-8p23.27.993.2-12.2
8q21.2-8q24.38.2107.052.4
NA18635chr88p23.3-8p127.993.8-27.9
NA18644chr22q32.1-2q37.37.493.2-47.6
chr44q34.3-4q35.28.1106.718.8
NA18956chr44q32.1-4q35.28.8105.023.3
NA19010chr22q12.2-2q12.320.8122.241.2
NA19083chr99q21.11-9q21.138.294.1-10.7
NA19213chr11q42.2-1q448.394.6-24.2
NA19355chr22q22.2-2q24.38.775.1-78.8
NA19454chr2020p13-20p11.2110.0138.6120.0
NA19652chr1212q12-12q24.338.6105.713.8
NA19750chr22q22.2-2q24.17.972.3-73.1
NA20342chr22p22.3-2p22.28.088.2-37.1
NA20509chr1717p13.3-17p11.29.287.6-27.9
chr55q31.1-5q35.39.0115.778.6
NA20517chr88p22-8p21.18.394.2-27.6
chr99q21.31-9q34.38.8105.619.5
NA20533chr1313q14.3-13q3410.5136.2141.3
chr1717p13.3-17p13.110.872.0-44.1
NA20538chr44q34.3-4q35.28.9106.016.9
NA20795chr99p22.2-9p22.120.1106.814.0
NA20911chr1515q26.1-15q26.211.084.7-37.3
NA21088chr33q25.2-3q25.3120.994.9-14.3
NA21118chr1818q22.3-18q238.590.8-21.0
chr55q21.3-5q35.39.1110.069.4
+ +","Markdown" +"Pharmacogenetics","Illumina/Polaris","cohorts/1000_genomes/y_chrom_gain.md",".md","1873","127","## Samples with y-chromosome gain +These y-chromosome changes are a bit hard to see on the plots. + + +
3 male samples with mosaic y-chromosome gain:
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
NA18966male1.021.34
NA11992male1.021.24
HG01882male1.001.20
+ + + +

NA18966

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
NA18966male1.021.34
+ + + +![png](plots/y_chrom_gain_3_2.png) + + + +

NA11992

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
NA11992male1.021.24
+ + + +![png](plots/y_chrom_gain_3_5.png) + + + +

HG01882

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG01882male1.01.2
+ + + +![png](plots/y_chrom_gain_3_8.png) + +","Markdown" +"Pharmacogenetics","Illumina/Polaris","cohorts/1000_genomes/chromosome_level_events_trisomies.md",".md","14325","1014","## Whole chromosome events + +28 samples with full chromosome alteration: + + HG00142 HG00189 HG00623 HG01137 HG01303 HG01357 HG01414 HG01506 + HG01602 HG01702 HG01704 HG02322 HG02409 HG02485 HG02634 HG02651 + HG02652 HG02805 HG03118 HG03796 HG03940 HG04198 HG04227 NA12156 + NA19378 NA20348 NA20759 NA21143 + + + +

HG00142

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
CHROM
chr11130.49.6169.4
chr13129.69.7144.9
+ + + +![png](plots/chromosome_level_events_trisomies_3_2.png) + + + +

HG00189

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
CHROM
chr9111.69.147.2
+ + + +![png](plots/chromosome_level_events_trisomies_3_5.png) + + + +

HG00623

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
CHROM
chr12133.39.584.7
+ + + +![png](plots/chromosome_level_events_trisomies_3_8.png) + + + +

HG01137

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
CHROM
chr12115.49.039.0
+ + + +![png](plots/chromosome_level_events_trisomies_3_11.png) + + + +

HG01303

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
CHROM
chr12119.19.348.4
chr5119.19.3142.4
+ + + +![png](plots/chromosome_level_events_trisomies_3_14.png) + + + +

HG01357

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
CHROM
chr12137.510.495.3
+ + + +![png](plots/chromosome_level_events_trisomies_3_17.png) + + + +

HG01414

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
CHROM
chr12106.88.712.0
+ + + +![png](plots/chromosome_level_events_trisomies_3_20.png) + + + +

HG01506

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
CHROM
chr11114.18.978.4
+ + + +![png](plots/chromosome_level_events_trisomies_3_23.png) + + + +

HG01602

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
CHROM
chr9130.59.7123.8
+ + + +![png](plots/chromosome_level_events_trisomies_3_26.png) + + + +

HG01702

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
CHROM
chr12109.49.123.7
+ + + +![png](plots/chromosome_level_events_trisomies_3_29.png) + + + +

HG01704

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
CHROM
chr12106.28.58.8
+ + + +![png](plots/chromosome_level_events_trisomies_3_32.png) + + + +

HG02322

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
CHROM
chr12139.910.4101.3
+ + + +![png](plots/chromosome_level_events_trisomies_3_35.png) + + + +

HG02409

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
CHROM
chr9109.28.837.6
+ + + +![png](plots/chromosome_level_events_trisomies_3_38.png) + + + +

HG02485

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
CHROM
chr12107.78.819.4
+ + + +![png](plots/chromosome_level_events_trisomies_3_41.png) + + + +

HG02634

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
CHROM
chr11120.08.8111.2
+ + + +![png](plots/chromosome_level_events_trisomies_3_44.png) + + + +

HG02651

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
CHROM
chr12115.39.238.8
+ + + +![png](plots/chromosome_level_events_trisomies_3_47.png) + + + +

HG02652

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
CHROM
chr12109.78.824.4
+ + + +![png](plots/chromosome_level_events_trisomies_3_50.png) + + + +

HG02805

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
CHROM
chr9108.28.933.5
+ + + +![png](plots/chromosome_level_events_trisomies_3_53.png) + + + +

HG03118

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
CHROM
chr12108.28.620.6
+ + + +![png](plots/chromosome_level_events_trisomies_3_56.png) + + + +

HG03796

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
CHROM
chr12106.98.917.3
+ + + +![png](plots/chromosome_level_events_trisomies_3_59.png) + + + +

HG03940

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
CHROM
chr12111.29.028.4
+ + + +![png](plots/chromosome_level_events_trisomies_3_62.png) + + + +

HG04198

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
CHROM
chr12112.48.231.4
+ + + +![png](plots/chromosome_level_events_trisomies_3_65.png) + + + +

HG04227

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
CHROM
chr12106.48.78.8
+ + + +![png](plots/chromosome_level_events_trisomies_3_68.png) + + + +

NA12156

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
CHROM
chr9114.58.458.9
+ + + +![png](plots/chromosome_level_events_trisomies_3_71.png) + + + +

NA19378

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
CHROM
chr12120.39.651.4
+ + + +![png](plots/chromosome_level_events_trisomies_3_74.png) + + + +

NA20348

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
CHROM
chr12108.98.722.4
+ + + +![png](plots/chromosome_level_events_trisomies_3_77.png) + + + +

NA20759

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
CHROM
chr12124.99.363.1
+ + + +![png](plots/chromosome_level_events_trisomies_3_80.png) + + + +

NA21143

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
medianmadz-score
CHROM
chr12106.28.112.8
chr14107.28.133.7
chr9106.28.025.5
+ + + +![png](plots/chromosome_level_events_trisomies_3_83.png) + +","Markdown" +"Pharmacogenetics","Illumina/Polaris","cohorts/1000_genomes/sex_chrom_overview.md",".md","7136","431","# Compile sample-level for ASHG talk + +## Sample sex chromsome coverage + +* Here the `1kg gender` column is the annotated gender on these samples from the 1000 genomes project FTP site. + +__file:__ [data/sex_chromosomes.csv](./data/sex_chromosomes.csv) + + +
begining of file:
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG00096male1.000.98
HG00097female1.980.00
HG00099female1.980.00
HG00100female1.980.00
HG00101male1.001.00
+ + + +
distribution of X and Y coverage across samples:
+ + + +![png](plots/sex_chrom_overview_5_3.png) + + + +
7 male samples with y-chromosome dropout:
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG00246male1.000.32
NA20754male1.020.40
HG01967male1.000.46
HG02053male1.000.54
HG03615male1.000.66
HG00185male1.020.78
HG03352male1.000.80
+ + + +
+ + + +
3 male samples with mosaic y-chromosome gain:
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
NA18966male1.021.34
NA11992male1.021.24
HG01882male1.001.20
+ + + +
32 female samples with x-chromosome dropout:
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG03511female1.000.0
NA19332female1.020.0
NA20506female1.080.0
HG00361female1.140.0
NA20530female1.140.0
NA19395female1.140.0
NA20533female1.200.0
HG01366female1.300.0
HG03019female1.300.0
HG00154female1.360.0
NA19054female1.360.0
HG04202female1.380.0
NA20832female1.500.0
NA18864female1.500.0
HG01137female1.520.0
NA18978female1.540.0
HG03055female1.600.0
NA20790female1.620.0
HG00732female1.640.0
NA18963female1.640.0
HG03401female1.700.0
HG02144female1.740.0
NA20769female1.760.0
HG00864female1.760.0
HG02652female1.760.0
NA18520female1.760.0
HG03016female1.760.0
NA11933female1.780.0
NA20535female1.780.0
HG01806female1.780.0
HG03634female1.800.0
NA20892female1.800.0
+ + + +
+ + + +
5 female samples with x-chromosome gain:
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
NA20821female2.900.0
HG02805female2.600.0
NA18946female2.440.0
HG02102female2.260.0
HG00261female2.200.0
+ +","Markdown" +"Pharmacogenetics","Illumina/Polaris","cohorts/1000_genomes/y_chrom_dropout.md",".md","3864","267","## Samples with y-chromosome dropout +These y-chromosome changes are a bit hard to see on the plots. + + +
7 male samples with y-chromosome dropout:
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG00246male1.000.32
NA20754male1.020.40
HG01967male1.000.46
HG02053male1.000.54
HG03615male1.000.66
HG00185male1.020.78
HG03352male1.000.80
+ + + +

HG00246

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG00246male1.00.32
+ + + +![png](plots/y_chrom_dropout_3_2.png) + + + +

NA20754

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
NA20754male1.020.4
+ + + +![png](plots/y_chrom_dropout_3_5.png) + + + +

HG01967

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG01967male1.00.46
+ + + +![png](plots/y_chrom_dropout_3_8.png) + + + +

HG02053

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG02053male1.00.54
+ + + +![png](plots/y_chrom_dropout_3_11.png) + + + +

HG03615

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG03615male1.00.66
+ + + +![png](plots/y_chrom_dropout_3_14.png) + + + +

HG00185

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG00185male1.020.78
+ + + +![png](plots/y_chrom_dropout_3_17.png) + + + +

HG03352

+ + + + + + + + + + + + + + + + + + + + +
1kg genderx-coveragey-coverage
HG03352male1.00.8
+ + + +![png](plots/y_chrom_dropout_3_20.png) + +","Markdown" +"Pharmacogenetics","gianlucatruda/warfit-learn","setup.py",".py","1031","34","import setuptools + +with open(""README.md"", ""r"") as fh: + long_description = fh.read() + +setuptools.setup( + name=""warfit-learn"", + version=""0.2.1"", + author=""Gianluca Truda"", + author_email=""gianlucatruda@gmail.com"", + description=""A toolkit for reproducible research in warfarin dose estimation"", + long_description=long_description, + long_description_content_type=""text/markdown"", + url=""https://github.com/gianlucatruda/warfit-learn"", + packages=setuptools.find_packages(), + classifiers=[ + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', + ""Operating System :: OS Independent"", + ], + include_package_data=True, + install_requires=[ + 'numpy>=1.14.5', + 'pandas>=0.24.1', + 'scikit_learn>=0.21.2', + 'scipy>=1.1.0', + 'joblib>=0.12.4', + 'tqdm>=4.0', + 'tabulate>=0.8.3', + ] +) +","Python" +"Pharmacogenetics","gianlucatruda/warfit-learn","warfit_learn/__init__.py",".py","152","5","import warnings +# Suppress a harmless sklearn warning or two +warnings.filterwarnings( + action=""ignore"", module=""sklearn"", message=""^internal gelsd"" +)","Python" +"Pharmacogenetics","gianlucatruda/warfit-learn","warfit_learn/metrics/__init__.py",".py","168","6","from .scoring import score_pw20 +from .scoring import score_mae +from .scoring import score_r2 +from .scoring import score_hybrid +from .scoring import confidence_interval +","Python" +"Pharmacogenetics","gianlucatruda/warfit-learn","warfit_learn/metrics/scoring.py",".py","2132","70",""""""" +A toolkit for reproducible research in warfarin dose estimation. +Copyright (C) 2019 Gianluca Truda + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +"""""" + +from sklearn.metrics import mean_absolute_error, r2_score +import numpy as np + + +def score_pw20(y_true, y_pred): + """"""Custom metric function for PW20"""""" + patients_in_20 = 0 + for i, _ in enumerate(y_true): + if 0.8 * y_true[i] < y_pred[i] < 1.2 * y_true[i]: + patients_in_20 += 1 + return float(100 * patients_in_20 / len(y_true)) + + +def score_mae(y_true, y_pred): + """"""Scoring metric for MAE using sklearn metric for mean_absolute_error"""""" + return mean_absolute_error(y_true, y_pred) + + +def score_r2(y_true, y_pred): + """"""Scoring metric using sklearn's r2 metric"""""" + return r2_score(y_true, y_pred) + + +def score_hybrid(y_true, y_pred): + """"""Custom metric function. A hybrid of MAE and PW20"""""" + return score_pw20(y_true, y_pred) / (score_mae(y_true, y_pred) ** 2) + + +def confidence_interval(data, confidence=0.95): + """"""Calculates confidence interval start and end for some data. + + Makes use of the percentile method. + + Parameters + ---------- + data : array-like + The 1D-array or list of values. + confidence : float, optional + The conidence level (inverse of alpha), by default 0.95 + + Returns + ------- + Tuple + (interval_start, interval_end) + """""" + + p = ((1.0-confidence)/2.0) * 100 + lower = np.percentile(data, p) + p = (confidence+((1.0-confidence)/2.0)) * 100 + upper = np.percentile(data, p) + return lower, upper +","Python" +"Pharmacogenetics","gianlucatruda/warfit-learn","warfit_learn/estimators/__init__.py",".py","33","1","from .estimators import Estimator","Python" +"Pharmacogenetics","gianlucatruda/warfit-learn","warfit_learn/estimators/estimators.py",".py","2522","86",""""""" +A toolkit for reproducible research in warfarin dose estimation. +Copyright (C) 2019 Gianluca Truda + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +"""""" + +from sklearn.base import BaseEstimator + + +class Estimator(BaseEstimator): + """"""Wrapper class for any scikit-learn Estimator. + + This allows us to give the estimators a human-relevant + description that is displayed in the automatically-generated + results. + """""" + + def __init__(self, estimator: BaseEstimator, identifier: str): + if not isinstance(identifier, str): + identifier = str(identifier) + if not isinstance(estimator, BaseEstimator): + raise TypeError + self.__identifier = identifier + self.__estimator = estimator + self.__is_trained = False + + @property + def identifier(self): + """"""The identifier (name) for the Estimator. + """""" + return self.__identifier + + @property + def estimator(self): + """"""The underlying sklearn Estimator object. + """""" + return self.__estimator + + @property + def is_trained(self): + """"""The train status of the Estimator + """""" + return self.__is_trained + + def fit(self, X, y): + """"""Train the Estimator on provided data. + + Parameters + ---------- + X : array-like + A multi-dimensional array of input data. + y : array-like + A single-dimensional array of target data. + """""" + self.__estimator.fit(X, y) + self.__is_trained = True + + def predict(self, X): + """"""Predict the y-value for the given data. + + NOTE: It's wise to fit() the estimator before trying to predict. + + Parameters + ---------- + X : array-like + A multi-dimensional array of input data. + + Returns + ------- + array-like + A single-dimensional array of predicted data. + """""" + return self.__estimator.predict(X) +","Python" +"Pharmacogenetics","gianlucatruda/warfit-learn","warfit_learn/preprocessing/preprocessor.py",".py","12189","452",""""""" +A toolkit for reproducible research in warfarin dose estimation. +Copyright (C) 2019 Gianluca Truda + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +"""""" + +import pandas as pd +import numpy as np +from sklearn.linear_model import LinearRegression + +FILTER_COLUMNS = [ + 'Age', + 'Therapeutic Dose of Warfarin', + 'Subject Reached Stable Dose of Warfarin', + 'Gender', + 'CYP2C9 consensus', + 'Imputed VKORC1', +] +RARE_ALLELES = [ + '*1/*5', + '*1/*6', + '*1/*11', + '*1/*13', + '*1/*14', +] + +IWPC_PARAMS = [ + ""Race (OMB)"", + ""Age"", + ""Height (cm)"", + ""Weight (kg)"", + ""Amiodarone (Cordarone)"", + ""Carbamazepine (Tegretol)"", + ""Phenytoin (Dilantin)"", + ""Rifampin or Rifampicin"", + ""Current Smoker"", + ""CYP2C9 consensus"", + ""Imputed VKORC1"", + ""Therapeutic Dose of Warfarin"", + 'INR on Reported Therapeutic Dose of Warfarin', +] + + +def prepare_iwpc(data: pd.DataFrame, drop_inr=True): + """"""Prepare IWPC data for experimentation. + + NOTE: This is equivalent to calling `clean_iwpc()` and + then `format_iwpc()`. + + Parameters + ---------- + data : pd.DataFrame + The raw IWPC data. + drop_inr : bool, optional + Whether to drop the INR field, by default True + + Returns + ------- + pd.DataFrame + The cleaned and preprocessed IWPC dataset. + """""" + + assert(isinstance(data, pd.DataFrame)) + assert(_verify_shape(data)) + + _data = clean_iwpc(data) + _data = format_iwpc(_data) + + assert(_data.shape[0] == 5741) + + if drop_inr: + _data.drop('INR on Reported Therapeutic Dose of Warfarin', + axis=1, inplace=True) + + return _data + + +def clean_iwpc(data: pd.DataFrame): + """"""Clean the IWPC dataset. + + Imputes missing height and weight using linear regression. + Imputes missing vkorc1 genotypes using IWPC algorithm. + Vectorises categorical features to one-hot encoded format. + + NOTE: The output is not yet ready for training a model. You should + call `format_iwpc(data)` with the output `data` to vectorise into + an ML-ready format. + + Parameters + ---------- + data : pd.DataFrame + The raw IWPC dataset. + + Returns + ------- + pd.DataFrame + The cleaned IWPC dataset. + """""" + + assert(isinstance(data, pd.DataFrame)) + assert(_verify_shape(data)) + + _data = data.copy() + _data = _drop_height_weight(_data) + _data = _drop_race_gender(_data) + _data = _define_dose_groups(_data) + _dummies = _get_dummy_categoricals(_data) + _heights = _get_imputed_heights(_dummies) + _weights = _get_imputed_weights(_dummies) + _data = _replace_height_and_weight(_data, _heights, _weights) + _data = _impute_genotypes(_data) + _data = _drop_unusable_rows(_data) + _data = _exclude_rare_alleles(_data) + _data = _exclude_extreme_doses(_data) + + return _data + + +def format_iwpc(data: pd.DataFrame, mode='df', params=None): + """"""Format cleaned IWPC dataset into ML-ready dataframe. + + NOTE: This requires a cleaned IWPC dataset, i.e. the output of the + `clean_iwpc()` function. + + Parameters + ---------- + data : pd.DataFrame + The cleaned IWPC dataset. + mode : str, optional + The return mode, either 'df' for a Pandas dataframe or 'array' + for two NumPy arrays, by default 'df'. + params : list-like, optional + List of the which parameters should be included in the output, + by default `IWPC_PARAMS` (the ones standardised in the research). + + Returns + ------- + + pd.DataFrame + A dataframe of the formatted IWPC data, if in `df` mode. + + Tuple + A tuple of (X, y) numpy arrays where `X` is the multi-dimensional + input matrix and `y` is the single-dimensional target feature. + This is only returned if `array` mode. + + Raises + ------ + KeyError + All parameters in `params` must be the name of a column in `data`. + """""" + + assert(isinstance(data, pd.DataFrame)) + + if params is None: + params = IWPC_PARAMS + + for p in params: + if p not in data.columns: + raise KeyError(f""key '{p}' is not in the data provided"") + + _data = data.copy() + + _data = pd.get_dummies(_data[params]) + + # Fill NaNs with zero + _data = _data.fillna(value=0) + + # Ensure that no NaNs remain + assert(_data.isnull().values.any() == False) + + if mode == 'array': + y = _data['Therapeutic Dose of Warfarin'].values + X = _data.drop(['Therapeutic Dose of Warfarin'], axis=1).values + return X, y + else: + return _data + + +def describe_iwpc_cohort(data: pd.DataFrame): + """"""Describes the distribution of the cohort. + + Parameters + ---------- + data : pd.DataFrame + The IWPC dataset after `clean_iwpc()` has been run on it. + """""" + + _interest_columns = [ + 'Therapeutic Dose of Warfarin', + 'Height (cm)', + 'Weight (kg)', + 'INR on Reported Therapeutic Dose of Warfarin', + ] + + _meds_of_interest = [ + 'Carbamazepine (Tegretol)', + 'Phenytoin (Dilantin)', + 'Rifampin or Rifampicin', + 'Amiodarone (Cordarone)', + ] + + _enzyme_inducers = [ + 'Carbamazepine (Tegretol)', + 'Phenytoin (Dilantin)', + 'Rifampin or Rifampicin', + ] + + for i in _interest_columns: + print(data[i].describe(), end='\n\n') + + for race in ['Asian', 'White', 'Black']: + print(data['Race (OMB)'][data['Race (OMB)'].str.contains( + race)].describe(), end='\n\n') + + print(data['Age'].value_counts().sort_values(), end='\n\n') + + for med in _meds_of_interest: + print(data[med][data[med] == 1].value_counts(), end='\n\n') + + print( + 'Patients on enzyme enducers: ', + data[_enzyme_inducers][data[_enzyme_inducers].any(axis=1)].shape[0], + end='\n\n' + ) + + print(data['Imputed VKORC1'].value_counts().sort_values(), end='\n\n') + + print(data['CYP2C9 consensus'].value_counts( + ).sort_values(ascending=False), end='\n\n') + + for cat in ['Gender', 'Current Smoker']: + print(data[cat].value_counts(), end='\n\n') + + +def _verify_shape(df: pd.DataFrame): + """"""Ensures data it of specific shape + """""" + + return df.shape == (6256, 68) + + +def _drop_height_weight(df: pd.DataFrame): + """"""Drop rows with both height AND weight missing + """""" + + _df = df.copy() + _df.dropna(subset=['Weight (kg)', 'Height (cm)'], how='all', inplace=True) + + return _df + + +def _drop_race_gender(df: pd.DataFrame): + """"""Drop rows where race AND gender are missing + """""" + + _df = df.copy() + _df.dropna(subset=['Race (OMB)', 'Gender'], inplace=True) + + return _df + + +def _define_dose_groups(df: pd.DataFrame): + """"""Classify dose (low, inter, high) based on race and dose distribution + """""" + + RACE = 'Race (OMB)' + DOSE = 'Therapeutic Dose of Warfarin' + GROUP = 'dose_group' + + # df.loc[DOSE] = df[DOSE].astype(float) + + def _group(x, lower, upper): + if x[DOSE] < lower: + return 'low' + elif x[DOSE] > upper: + return 'high' + else: + return 'inter' + + df[GROUP] = 'none' + for race in df[RACE].unique(): + dist = df[df[RACE] == race][DOSE].describe() + df.loc[df[RACE] == race, GROUP] = df[df[RACE] == race].apply( + lambda x: _group(x, float(dist['25%']), float(dist['75%'])), axis=1) + + return df + + +def _get_dummy_categoricals(df: pd.DataFrame): + """"""One-hot encode categorical columns + """""" + + _dummied = pd.get_dummies( + df[[ + 'Weight (kg)', + 'Height (cm)', + 'Race (OMB)', + 'Gender']], + columns=['Race (OMB)', 'Gender']) + + return _dummied + + +def _get_imputed_heights(df: pd.DataFrame): + """"""Impute height using weight, race, sex + """""" + + train = df[(df['Height (cm)'].isnull() == False) & ( + df['Weight (kg)'].isnull() == False)] + pred = df[(df['Height (cm)'].isnull())] + + x_train = train.drop(['Height (cm)'], axis='columns') + y_train = train['Height (cm)'] + x_pred = pred.drop(['Height (cm)'], axis='columns') + linreg = LinearRegression() + linreg.fit(x_train, y_train) + imputed_heights = linreg.predict(x_pred) + + return imputed_heights + + +def _get_imputed_weights(df: pd.DataFrame): + """"""Impute weight using height, race, sex + """""" + + train = df[(df['Weight (kg)'].isnull() == False) & ( + df['Height (cm)'].isnull() == False)] + pred = df[(df['Weight (kg)'].isnull())] + + x_train = train.drop(['Weight (kg)'], axis='columns') + y_train = train['Weight (kg)'] + x_pred = pred.drop(['Weight (kg)'], axis='columns') + + linreg = LinearRegression() + linreg.fit(x_train, y_train) + imputed_weights = linreg.predict(x_pred) + + return imputed_weights + + +def _replace_height_and_weight(data: pd.DataFrame, + heights: np.array, + weights: np.array, + ): + """"""Insert imputed heights and weights into data + """""" + + _data = data.copy() + + _data.loc[_data['Height (cm)'].isnull(), 'Height (cm)'] = heights + _data.loc[_data['Weight (kg)'].isnull(), 'Weight (kg)'] = weights + # Sanity check + assert(_data[['Height (cm)', 'Weight (kg)'] + ].isnull().values.any() == False) + + return _data + + +def _impute_vkorc1_row(row: pd.Series): + """"""Impute VKORCI genotype using Klein et al. 2009 technique + """""" + + rs2359612 = row['VKORC1 genotype: 2255C>T (7566); chr16:31011297; rs2359612; A/G'] + rs9934438 = row['VKORC1 genotype: 1173 C>T(6484); chr16:31012379; rs9934438; A/G'] + rs9923231 = row['VKORC1 genotype: -1639 G>A (3673); chr16:31015190; rs9923231; C/T'] + rs8050894 = row['VKORC1 genotype: 1542G>C (6853); chr16:31012010; rs8050894; C/G'] + race = row['Race (OMB)'] + black_missing_mixed = [ + 'Black or African American', + 'Missing or Mixed Race'] + + if rs9923231 in ['A/A', 'A/G', 'G/A', 'G/G']: + return rs9923231 + elif race not in black_missing_mixed and rs2359612 == 'C/C': + return 'G/G' + elif race not in black_missing_mixed and rs2359612 == 'T/T': + return 'A/A' + elif rs9934438 == 'C/C': + return 'G/G' + elif rs9934438 == 'T/T': + return 'A/A' + elif rs9934438 == 'C/T': + return 'A/G' + elif race not in black_missing_mixed and rs8050894 == 'G/G': + return 'G/G' + elif race not in black_missing_mixed and rs8050894 == 'C/C': + return 'A/A' + elif race not in black_missing_mixed and rs8050894 == 'C/G': + return 'A/G' + else: + return 'Unknown' + + +def _impute_genotypes(df: pd.DataFrame, func=_impute_vkorc1_row): + """"""Impute and insert VKORC1 and CYP2C9 for each row + """""" + + _df = df.copy() + + # Impute VKORC1 genotypes + _df['Imputed VKORC1'] = _df.apply(func, axis=1) + + # Convert NaN CYP2C9 genotypes to 'Missing' + _df.loc[_df['CYP2C9 consensus'].isna(), 'CYP2C9 consensus'] = 'Unknown' + + return _df + + +def _drop_unusable_rows(df: pd.DataFrame, col_names=None): + """"""Remove essential rows that are missing + """""" + + if col_names is None: + col_names = FILTER_COLUMNS + + _df = df.copy() + _df.dropna(subset=col_names, inplace=True) + + return _df + + +def _exclude_rare_alleles(df: pd.DataFrame, alleles=None): + """"""Remove rows with rare alleles + """""" + + if alleles is None: + alleles = RARE_ALLELES + + _df = df[df['CYP2C9 consensus'].isin(alleles) == False] + return _df + + +def _exclude_extreme_doses(df: pd.DataFrame, threshold=315): + """"""Exclude extreme weekly warfarin doses + """""" + + _df = df[df['Therapeutic Dose of Warfarin'] < 315] + return _df +","Python" +"Pharmacogenetics","gianlucatruda/warfit-learn","warfit_learn/preprocessing/__init__.py",".py","161","5","from .preprocessor import prepare_iwpc +from .preprocessor import describe_iwpc_cohort +from .preprocessor import format_iwpc +from .preprocessor import clean_iwpc +","Python" +"Pharmacogenetics","gianlucatruda/warfit-learn","warfit_learn/datasets/__init__.py",".py","29","1","from .loader import load_iwpc","Python" +"Pharmacogenetics","gianlucatruda/warfit-learn","warfit_learn/datasets/loader.py",".py","1075","38",""""""" +A toolkit for reproducible research in warfarin dose estimation. +Copyright (C) 2019 Gianluca Truda + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +"""""" + +import pandas as pd +from os.path import dirname, join + + +def load_iwpc() -> pd.DataFrame: + """"""Loads raw IWPC dataset as dataframe object. + + Returns + ------- + pd.DataFrame + The raw IWPC dataset. + """""" + + module_path = dirname(__file__) + fpath = join(module_path, 'data', 'iwpc.pkl') + + df = pd.read_pickle(fpath) + + return df +","Python" +"Pharmacogenetics","gianlucatruda/warfit-learn","warfit_learn/evaluation/__init__.py",".py","87","3","from .evaluation import evaluate_estimator +from .evaluation import evaluate_estimators +","Python" +"Pharmacogenetics","gianlucatruda/warfit-learn","warfit_learn/evaluation/evaluation.py",".py","8178","229",""""""" +A toolkit for reproducible research in warfarin dose estimation. +Copyright (C) 2019 Gianluca Truda + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +"""""" + +from typing import List +from ..estimators import Estimator +from ..metrics import score_mae, score_pw20, score_r2 +from sklearn.model_selection import train_test_split +from sklearn.preprocessing import StandardScaler +from sklearn.utils import resample +import numpy as np +import pandas as pd +from joblib import Parallel, delayed +import multiprocessing +from tabulate import tabulate + + +def evaluate_estimator(estimator: Estimator, + data: pd.DataFrame, + technique='mccv', + target_column='Therapeutic Dose of Warfarin', + resamples=100, + test_size=0.2, + squaring=False, + parallelism=0.5): + """"""Evaluation function for a single estimator. + + NOTE: You would typically not call this function directly, unless + you are evaluating only a single type of estimator. + + Parameters + ---------- + estimator : Estimator + The Estimator object to train-evaluate. + data : pd.DataFrame + The data on which to train and evaluate. + technique : str, optional + The CV method to use. Either 'mccv' for monte-carlo CV or + 'bootstrap' for bootstrap resampling, by default 'mccv'. + target_column : str, optional + The name of the target column in the provided data, + by default 'Therapeutic Dose of Warfarin' + resamples : int, optional + The number of times to resample and evaluate, by default 100. + The more resamples performed, the more reliable the aggregated + results. + test_size : float, optional + The fraction of the data to be used as the test/evaluation set, + by default 0.2 + squaring : bool, optional + Whether the predictions and truth values must be squared before + comparson, by default False. Only enable this if you + square-rooted your target variable to un-skew the distribution. + parallelism : float, optional + The fraction of your processors to parallelise the evaluation + over, by default 0.5. Setting this to 1.0 will probably give you + the fastest evaluation, but will demand all your CPU resources. + + Returns + ------- + Dictionary + A dictionary of lists, with results from each trial. Keys of the + dictionary are ['PW20', 'MAE', 'R2']. + """""" + + assert(technique in ['mccv', 'bootstrap']) + results = {'PW20': [], 'MAE': [], 'R2': []} + + avail_cores = multiprocessing.cpu_count() + num_cores = max(int(avail_cores * parallelism), 1) + + try: + if technique == 'bootstrap': + replace = True + elif technique == 'mccv': + replace = False + + res = Parallel(n_jobs=num_cores)(delayed(_train_eval)( + estimator, + data, + target_column=target_column, + test_size=test_size, + squaring=squaring, + replace=replace) for i in range(resamples)) + + results['PW20'] = [r[0] for r in res] + results['MAE'] = [r[1] for r in res] + results['R2'] = [r[2] for r in res] + + return results + + except Exception as e: + print(""Error occurred:"", e) + return results + + +def evaluate_estimators(estimators: List[Estimator], + data: pd.DataFrame, + target_column='Therapeutic Dose of Warfarin', + scale=True, + parallelism=0.5, + *args, + **kwargs): + """"""Evaluation function for a list of Estimators. + + Parameters + ---------- + estimators : List[Estimator] + A list of Estimator objects. + data : pd.DataFrame + The data on which to train and evaluate. + target_column : str, optional + The name of the target column in the provided data, + by default 'Therapeutic Dose of Warfarin' + scale : bool, optional + Whether or not to scale the input features prior to training, + by default True. + parallelism : float, optional + The fraction of your processors to parallelise the evaluation + over, by default 0.5. Setting this to 1.0 will probably give you + the fastest evaluation, but will demand all your CPU resources. + technique : str, optional + The CV method to use. Either 'mccv' for monte-carlo CV or + 'bootstrap' for bootstrap resampling, by default 'mccv'. + resamples : int, optional + The number of times to resample and evaluate, by default 100. + The more resamples performed, the more reliable the aggregated + results. + test_size : float, optional + The fraction of the data to be used as the test/evaluation set, + by default 0.2 + squaring : bool, optional + Whether the predictions and truth values must be squared before + comparson, by default False. Only enable this if you + square-rooted your target variable to un-skew the distribution. + + Returns + ------- + pd.DataFrame + Dataframe of results with the name of the Estimator, and the + results in terms of MAE, PW20, and R2. + """""" + + _data = data.copy() + + avail_cores = multiprocessing.cpu_count() + num_cores = max(int(avail_cores * parallelism), 1) + print(f'Using {num_cores} / {avail_cores} CPU cores...') + + if scale: + x_cols = list(_data.columns) + x_cols.remove(target_column) + scaler = StandardScaler() + _data[x_cols] = scaler.fit_transform(_data[x_cols]) + + results = [] + for _, est in enumerate(estimators): + print(f'\n{est.identifier}...') + res = evaluate_estimator(est, _data, + target_column=target_column, + *args, **kwargs) + res_dict = { + 'Estimator': [est.identifier for x in range(len(res['PW20']))], + 'PW20': res['PW20'], + 'MAE': res['MAE'], + 'R2': res['R2'], + } + prog = {k: [np.mean(res_dict[k])] + for k in list(res_dict.keys())[1:]} + print(tabulate(prog, headers=prog.keys())) + results.append(res_dict) + + # Compile results to single DF + df_res = pd.DataFrame() + for res in results: + df_res = df_res.append(pd.DataFrame.from_dict(res)) + + print(f""\n\n{df_res.groupby(['Estimator']).agg(np.mean)}\n"") + + return df_res + + +def _train_eval(estimator: Estimator, + data, + test_size, + target_column, + squaring, + replace=False): + """"""Trains and evaluates a single Estimator for one iteration. + + NOTE: This should not be called directly by the user. + """""" + + train, test = train_test_split(data, test_size=test_size) + if replace: + # Bootstrap resampling + train = resample(train, replace=True) + y_train = train[target_column].values + x_train = train.drop([target_column], axis=1).values + y_test = test[target_column].values + # Square the dose (to undo upstream sqrt call) + if squaring: + y_test = np.square(y_test) + x_test = test.drop([target_column], axis=1).values + + estimator.fit(x_train, y_train) + predicts = estimator.predict(x_test) + if squaring: + predicts = np.square(predicts) + + return ( + score_pw20(y_test, predicts), + score_mae(y_test, predicts), + score_r2(y_test, predicts)) +","Python" +"Pharmacogenetics","gianlucatruda/warfit-learn","docs/experiment_results.ipynb",".ipynb","135548","2373","{ + ""nbformat"": 4, + ""nbformat_minor"": 0, + ""metadata"": { + ""colab"": { + ""name"": ""warfit_experiment_results_publication.ipynb"", + ""version"": ""0.3.2"", + ""provenance"": [], + ""collapsed_sections"": [] + }, + ""kernelspec"": { + ""name"": ""python3"", + ""display_name"": ""Python 3"" + } + }, + ""cells"": [ + { + ""cell_type"": ""markdown"", + ""metadata"": { + ""id"": ""Sv9q5lzHXkfn"", + ""colab_type"": ""text"" + }, + ""source"": [ + ""# Experimental Results using warfit-learn\n"", + ""\n"", + ""Project page: [pypi.org/project/warfit-learn/](http://pypi.org/project/warfit-learn/)"" + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": { + ""id"": ""mwRafiFDXsBj"", + ""colab_type"": ""text"" + }, + ""source"": [ + ""Import dependencies and configure environment"" + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""HbcABVj3fpkD"", + ""colab_type"": ""code"", + ""colab"": {} + }, + ""source"": [ + ""%matplotlib inline\n"", + ""%load_ext autoreload\n"", + ""%autoreload 2"" + ], + ""execution_count"": 0, + ""outputs"": [] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""PQ7Aov6qWd60"", + ""colab_type"": ""code"", + ""colab"": {} + }, + ""source"": [ + ""import pandas as pd\n"", + ""import numpy as np\n"", + ""from matplotlib import pyplot as plt\n"", + ""import seaborn as sns\n"", + ""import sklearn\n"", + ""\n"", + ""import warfit_learn"" + ], + ""execution_count"": 0, + ""outputs"": [] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""SWy5V4sXipwc"", + ""colab_type"": ""code"", + ""colab"": {} + }, + ""source"": [ + ""pd.set_option('mode.chained_assignment', None)"" + ], + ""execution_count"": 0, + ""outputs"": [] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": { + ""id"": ""EYeaq-s1YII2"", + ""colab_type"": ""text"" + }, + ""source"": [ + ""Load the IWPC and PathCare datasets"" + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""YOgKBbxoX6XS"", + ""colab_type"": ""code"", + ""colab"": {} + }, + ""source"": [ + ""from warfit_learn import datasets\n"", + ""iwpc_data = datasets.load_iwpc()\n"", + ""\n"", + ""path_data = pd.read_csv('datasets/RAW/PathCare/PATH-whole.csv')"" + ], + ""execution_count"": 0, + ""outputs"": [] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""h3G20-bgYjyA"", + ""colab_type"": ""code"", + ""outputId"": ""6be408ee-b27f-498f-99c9-799ee06b23d7"", + ""colab"": { + ""base_uri"": ""https://localhost:8080/"", + ""height"": 34 + } + }, + ""source"": [ + ""iwpc_data.shape, path_data.shape"" + ], + ""execution_count"": 0, + ""outputs"": [ + { + ""output_type"": ""execute_result"", + ""data"": { + ""text/plain"": [ + ""((6256, 68), (8985, 38))"" + ] + }, + ""metadata"": { + ""tags"": [] + }, + ""execution_count"": 28 + } + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": { + ""id"": ""n-KqLVIDYybA"", + ""colab_type"": ""text"" + }, + ""source"": [ + ""Preprocess the IWPC data in the style of [Ma et a. 2018](https://journals.plos.org/plosone/article/comments?id=10.1371/journal.pone.0205872), and generate an ML-ready version by vectorising categoricals and dropping unused features."" + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""43e-ndheYs8W"", + ""colab_type"": ""code"", + ""outputId"": ""30a60650-e23a-4531-8d79-67580fe21582"", + ""colab"": { + ""base_uri"": ""https://localhost:8080/"", + ""height"": 34 + } + }, + ""source"": [ + ""from warfit_learn import preprocessing\n"", + ""\n"", + ""iwpc_inspect = preprocessing.clean_iwpc(iwpc_data)\n"", + ""iwpc = preprocessing.prepare_iwpc(iwpc_data, drop_inr=False)\n"", + ""iwpc.shape, iwpc_inspect.shape"" + ], + ""execution_count"": 0, + ""outputs"": [ + { + ""output_type"": ""execute_result"", + ""data"": { + ""text/plain"": [ + ""((5741, 33), (5741, 70))"" + ] + }, + ""metadata"": { + ""tags"": [] + }, + ""execution_count"": 29 + } + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": { + ""id"": ""L9_W59opZFNu"", + ""colab_type"": ""text"" + }, + ""source"": [ + ""Remove the non-therapeutic data from the PathCare dataset and select features"" + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""KezZC-dtZAMc"", + ""colab_type"": ""code"", + ""outputId"": ""3c4345b0-d368-4de5-dee0-80eac71cf24a"", + ""colab"": { + ""base_uri"": ""https://localhost:8080/"", + ""height"": 204 + } + }, + ""source"": [ + ""path = path_data[path_data['isInTherapeutic'] == 1].drop(['patientID', 'requestID'], axis='columns')\n"", + ""path.shape\n"", + ""\n"", + ""path = path[[\n"", + "" \""sex\"",\n"", + "" \""dob\"",\n"", + "" \""aspirin\"",\n"", + "" \""paracetamol\"",\n"", + "" \""amiodarone\"",\n"", + "" \""atrialFibrilation\"",\n"", + "" \""deepVeinThrombosis\"",\n"", + "" \""valveReplacement\"",\n"", + "" \""takenDoseWeek\"",\n"", + "" \""inr\"",\n"", + ""]].dropna()\n"", + ""\n"", + ""\n"", + ""path = pd.concat([path, pd.get_dummies(path['sex'])], axis=1, sort=False)\n"", + ""path.drop(['sex'], axis='columns', inplace=True)\n"", + ""\n"", + ""path.head()"" + ], + ""execution_count"": 0, + ""outputs"": [ + { + ""output_type"": ""execute_result"", + ""data"": { + ""text/plain"": [ + "" dob aspirin paracetamol amiodarone atrialFibrilation \\\n"", + ""1 1937 0 0 0 1 \n"", + ""5 1935 0 0 0 1 \n"", + ""11 1946 0 0 0 0 \n"", + ""13 1927 0 1 0 1 \n"", + ""20 1961 0 0 0 0 \n"", + ""\n"", + "" deepVeinThrombosis valveReplacement takenDoseWeek inr F M \n"", + ""1 0 0 45.0 3.0 0 1 \n"", + ""5 0 0 35.0 2.1 0 1 \n"", + ""11 0 0 17.5 2.2 1 0 \n"", + ""13 0 0 22.5 2.7 1 0 \n"", + ""20 0 0 47.5 2.2 1 0 "" + ], + ""text/html"": [ + ""
\n"", + ""\n"", + ""\n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + ""
dobaspirinparacetamolamiodaroneatrialFibrilationdeepVeinThrombosisvalveReplacementtakenDoseWeekinrFM
1193700010045.03.001
5193500010035.02.101
11194600000017.52.210
13192701010022.52.710
20196100000047.52.210
\n"", + ""
"" + ] + }, + ""metadata"": { + ""tags"": [] + }, + ""execution_count"": 30 + } + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": { + ""id"": ""gcBveI9rZUSv"", + ""colab_type"": ""text"" + }, + ""source"": [ + ""Have a look at the features and types of both datasets"" + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""eIXg_VO3ZROQ"", + ""colab_type"": ""code"", + ""outputId"": ""17409158-4e44-4917-c02e-3c2420807cb0"", + ""colab"": { + ""base_uri"": ""https://localhost:8080/"", + ""height"": 663 + } + }, + ""source"": [ + ""iwpc.info()"" + ], + ""execution_count"": 0, + ""outputs"": [ + { + ""output_type"": ""stream"", + ""text"": [ + ""\n"", + ""Int64Index: 5741 entries, 0 to 6255\n"", + ""Data columns (total 33 columns):\n"", + ""Height (cm) 5741 non-null float64\n"", + ""Weight (kg) 5741 non-null float64\n"", + ""Amiodarone (Cordarone) 5741 non-null float64\n"", + ""Carbamazepine (Tegretol) 5741 non-null float64\n"", + ""Phenytoin (Dilantin) 5741 non-null float64\n"", + ""Rifampin or Rifampicin 5741 non-null float64\n"", + ""Current Smoker 5741 non-null float64\n"", + ""Therapeutic Dose of Warfarin 5741 non-null float64\n"", + ""INR on Reported Therapeutic Dose of Warfarin 5741 non-null float64\n"", + ""Race (OMB)_Asian 5741 non-null uint8\n"", + ""Race (OMB)_Black or African American 5741 non-null uint8\n"", + ""Race (OMB)_Unknown 5741 non-null uint8\n"", + ""Race (OMB)_White 5741 non-null uint8\n"", + ""Age_10 - 19 5741 non-null uint8\n"", + ""Age_20 - 29 5741 non-null uint8\n"", + ""Age_30 - 39 5741 non-null uint8\n"", + ""Age_40 - 49 5741 non-null uint8\n"", + ""Age_50 - 59 5741 non-null uint8\n"", + ""Age_60 - 69 5741 non-null uint8\n"", + ""Age_70 - 79 5741 non-null uint8\n"", + ""Age_80 - 89 5741 non-null uint8\n"", + ""Age_90+ 5741 non-null uint8\n"", + ""CYP2C9 consensus_*1/*1 5741 non-null uint8\n"", + ""CYP2C9 consensus_*1/*2 5741 non-null uint8\n"", + ""CYP2C9 consensus_*1/*3 5741 non-null uint8\n"", + ""CYP2C9 consensus_*2/*2 5741 non-null uint8\n"", + ""CYP2C9 consensus_*2/*3 5741 non-null uint8\n"", + ""CYP2C9 consensus_*3/*3 5741 non-null uint8\n"", + ""CYP2C9 consensus_Unknown 5741 non-null uint8\n"", + ""Imputed VKORC1_A/A 5741 non-null uint8\n"", + ""Imputed VKORC1_A/G 5741 non-null uint8\n"", + ""Imputed VKORC1_G/G 5741 non-null uint8\n"", + ""Imputed VKORC1_Unknown 5741 non-null uint8\n"", + ""dtypes: float64(9), uint8(24)\n"", + ""memory usage: 583.1 KB\n"" + ], + ""name"": ""stdout"" + } + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""2bMsinqQZZ8S"", + ""colab_type"": ""code"", + ""outputId"": ""91aa4f10-2715-403f-a213-556b8bf94864"", + ""colab"": { + ""base_uri"": ""https://localhost:8080/"", + ""height"": 289 + } + }, + ""source"": [ + ""path.info()"" + ], + ""execution_count"": 0, + ""outputs"": [ + { + ""output_type"": ""stream"", + ""text"": [ + ""\n"", + ""Int64Index: 4621 entries, 1 to 8983\n"", + ""Data columns (total 11 columns):\n"", + ""dob 4621 non-null int64\n"", + ""aspirin 4621 non-null int64\n"", + ""paracetamol 4621 non-null int64\n"", + ""amiodarone 4621 non-null int64\n"", + ""atrialFibrilation 4621 non-null int64\n"", + ""deepVeinThrombosis 4621 non-null int64\n"", + ""valveReplacement 4621 non-null int64\n"", + ""takenDoseWeek 4621 non-null float64\n"", + ""inr 4621 non-null float64\n"", + ""F 4621 non-null uint8\n"", + ""M 4621 non-null uint8\n"", + ""dtypes: float64(2), int64(7), uint8(2)\n"", + ""memory usage: 370.0 KB\n"" + ], + ""name"": ""stdout"" + } + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": { + ""id"": ""QBK1obZhZljw"", + ""colab_type"": ""text"" + }, + ""source"": [ + ""Examine the values and distributions of both datasets"" + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""IwKzlVWbZapI"", + ""colab_type"": ""code"", + ""outputId"": ""caa0a8cd-0396-44eb-ae93-74fc0f466fe6"", + ""colab"": { + ""base_uri"": ""https://localhost:8080/"", + ""height"": 414 + } + }, + ""source"": [ + ""iwpc.describe()"" + ], + ""execution_count"": 0, + ""outputs"": [ + { + ""output_type"": ""execute_result"", + ""data"": { + ""text/plain"": [ + "" Height (cm) Weight (kg) Amiodarone (Cordarone) \\\n"", + ""count 5741.000000 5741.000000 5741.000000 \n"", + ""mean 167.979150 78.794878 0.048772 \n"", + ""std 10.581973 22.316584 0.215410 \n"", + ""min 124.970000 30.000000 0.000000 \n"", + ""25% 160.020000 63.000000 0.000000 \n"", + ""50% 167.640000 76.000000 0.000000 \n"", + ""75% 175.790577 90.700000 0.000000 \n"", + ""max 202.000000 237.700000 1.000000 \n"", + ""\n"", + "" Carbamazepine (Tegretol) Phenytoin (Dilantin) Rifampin or Rifampicin \\\n"", + ""count 5741.000000 5741.000000 5741.000000 \n"", + ""mean 0.005574 0.004529 0.000697 \n"", + ""std 0.074457 0.067150 0.026389 \n"", + ""min 0.000000 0.000000 0.000000 \n"", + ""25% 0.000000 0.000000 0.000000 \n"", + ""50% 0.000000 0.000000 0.000000 \n"", + ""75% 0.000000 0.000000 0.000000 \n"", + ""max 1.000000 1.000000 1.000000 \n"", + ""\n"", + "" Current Smoker Therapeutic Dose of Warfarin \\\n"", + ""count 5741.000000 5741.000000 \n"", + ""mean 0.083957 31.967232 \n"", + ""std 0.277348 16.765840 \n"", + ""min 0.000000 2.100000 \n"", + ""25% 0.000000 20.020000 \n"", + ""50% 0.000000 28.000000 \n"", + ""75% 0.000000 40.000000 \n"", + ""max 1.000000 230.000000 \n"", + ""\n"", + "" INR on Reported Therapeutic Dose of Warfarin Race (OMB)_Asian ... \\\n"", + ""count 5741.000000 5741.000000 ... \n"", + ""mean 2.152263 0.263891 ... \n"", + ""std 0.815865 0.440779 ... \n"", + ""min 0.000000 0.000000 ... \n"", + ""25% 2.000000 0.000000 ... \n"", + ""50% 2.340000 0.000000 ... \n"", + ""75% 2.600000 1.000000 ... \n"", + ""max 6.100000 1.000000 ... \n"", + ""\n"", + "" CYP2C9 consensus_*1/*2 CYP2C9 consensus_*1/*3 CYP2C9 consensus_*2/*2 \\\n"", + ""count 5741.000000 5741.000000 5741.000000 \n"", + ""mean 0.131510 0.083957 0.010103 \n"", + ""std 0.337987 0.277348 0.100012 \n"", + ""min 0.000000 0.000000 0.000000 \n"", + ""25% 0.000000 0.000000 0.000000 \n"", + ""50% 0.000000 0.000000 0.000000 \n"", + ""75% 0.000000 0.000000 0.000000 \n"", + ""max 1.000000 1.000000 1.000000 \n"", + ""\n"", + "" CYP2C9 consensus_*2/*3 CYP2C9 consensus_*3/*3 \\\n"", + ""count 5741.000000 5741.000000 \n"", + ""mean 0.011845 0.003484 \n"", + ""std 0.108196 0.058925 \n"", + ""min 0.000000 0.000000 \n"", + ""25% 0.000000 0.000000 \n"", + ""50% 0.000000 0.000000 \n"", + ""75% 0.000000 0.000000 \n"", + ""max 1.000000 1.000000 \n"", + ""\n"", + "" CYP2C9 consensus_Unknown Imputed VKORC1_A/A Imputed VKORC1_A/G \\\n"", + ""count 5741.000000 5741.000000 5741.000000 \n"", + ""mean 0.022296 0.295245 0.358474 \n"", + ""std 0.147657 0.456192 0.479594 \n"", + ""min 0.000000 0.000000 0.000000 \n"", + ""25% 0.000000 0.000000 0.000000 \n"", + ""50% 0.000000 0.000000 0.000000 \n"", + ""75% 0.000000 1.000000 1.000000 \n"", + ""max 1.000000 1.000000 1.000000 \n"", + ""\n"", + "" Imputed VKORC1_G/G Imputed VKORC1_Unknown \n"", + ""count 5741.000000 5741.000000 \n"", + ""mean 0.328166 0.018115 \n"", + ""std 0.469586 0.133380 \n"", + ""min 0.000000 0.000000 \n"", + ""25% 0.000000 0.000000 \n"", + ""50% 0.000000 0.000000 \n"", + ""75% 1.000000 0.000000 \n"", + ""max 1.000000 1.000000 \n"", + ""\n"", + ""[8 rows x 33 columns]"" + ], + ""text/html"": [ + ""
\n"", + ""\n"", + ""\n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + ""
Height (cm)Weight (kg)Amiodarone (Cordarone)Carbamazepine (Tegretol)Phenytoin (Dilantin)Rifampin or RifampicinCurrent SmokerTherapeutic Dose of WarfarinINR on Reported Therapeutic Dose of WarfarinRace (OMB)_Asian...CYP2C9 consensus_*1/*2CYP2C9 consensus_*1/*3CYP2C9 consensus_*2/*2CYP2C9 consensus_*2/*3CYP2C9 consensus_*3/*3CYP2C9 consensus_UnknownImputed VKORC1_A/AImputed VKORC1_A/GImputed VKORC1_G/GImputed VKORC1_Unknown
count5741.0000005741.0000005741.0000005741.0000005741.0000005741.0000005741.0000005741.0000005741.0000005741.000000...5741.0000005741.0000005741.0000005741.0000005741.0000005741.0000005741.0000005741.0000005741.0000005741.000000
mean167.97915078.7948780.0487720.0055740.0045290.0006970.08395731.9672322.1522630.263891...0.1315100.0839570.0101030.0118450.0034840.0222960.2952450.3584740.3281660.018115
std10.58197322.3165840.2154100.0744570.0671500.0263890.27734816.7658400.8158650.440779...0.3379870.2773480.1000120.1081960.0589250.1476570.4561920.4795940.4695860.133380
min124.97000030.0000000.0000000.0000000.0000000.0000000.0000002.1000000.0000000.000000...0.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0000000.000000
25%160.02000063.0000000.0000000.0000000.0000000.0000000.00000020.0200002.0000000.000000...0.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0000000.000000
50%167.64000076.0000000.0000000.0000000.0000000.0000000.00000028.0000002.3400000.000000...0.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0000000.000000
75%175.79057790.7000000.0000000.0000000.0000000.0000000.00000040.0000002.6000001.000000...0.0000000.0000000.0000000.0000000.0000000.0000001.0000001.0000001.0000000.000000
max202.000000237.7000001.0000001.0000001.0000001.0000001.000000230.0000006.1000001.000000...1.0000001.0000001.0000001.0000001.0000001.0000001.0000001.0000001.0000001.000000
\n"", + ""

8 rows × 33 columns

\n"", + ""
"" + ] + }, + ""metadata"": { + ""tags"": [] + }, + ""execution_count"": 33 + } + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""YlDN5YtCZsKC"", + ""colab_type"": ""code"", + ""outputId"": ""bafb3df0-899d-4edb-9af5-9e936cc2c19d"", + ""colab"": { + ""base_uri"": ""https://localhost:8080/"", + ""height"": 317 + } + }, + ""source"": [ + ""path.describe()"" + ], + ""execution_count"": 0, + ""outputs"": [ + { + ""output_type"": ""execute_result"", + ""data"": { + ""text/plain"": [ + "" dob aspirin paracetamol amiodarone atrialFibrilation \\\n"", + ""count 4621.000000 4621.000000 4621.000000 4621.000000 4621.000000 \n"", + ""mean 1947.423501 0.017745 0.016447 0.028349 0.433240 \n"", + ""std 13.828309 0.132038 0.127199 0.165985 0.495577 \n"", + ""min 1917.000000 0.000000 0.000000 0.000000 0.000000 \n"", + ""25% 1937.000000 0.000000 0.000000 0.000000 0.000000 \n"", + ""50% 1945.000000 0.000000 0.000000 0.000000 0.000000 \n"", + ""75% 1956.000000 0.000000 0.000000 0.000000 1.000000 \n"", + ""max 2004.000000 1.000000 1.000000 1.000000 1.000000 \n"", + ""\n"", + "" deepVeinThrombosis valveReplacement takenDoseWeek inr \\\n"", + ""count 4621.000000 4621.000000 4621.000000 4621.000000 \n"", + ""mean 0.109717 0.029214 29.627639 2.455897 \n"", + ""std 0.312570 0.168425 16.039975 0.333768 \n"", + ""min 0.000000 0.000000 0.000000 1.800000 \n"", + ""25% 0.000000 0.000000 17.500000 2.200000 \n"", + ""50% 0.000000 0.000000 27.500000 2.400000 \n"", + ""75% 0.000000 0.000000 37.500000 2.700000 \n"", + ""max 1.000000 1.000000 210.000000 3.900000 \n"", + ""\n"", + "" F M \n"", + ""count 4621.000000 4621.000000 \n"", + ""mean 0.528673 0.471327 \n"", + ""std 0.499231 0.499231 \n"", + ""min 0.000000 0.000000 \n"", + ""25% 0.000000 0.000000 \n"", + ""50% 1.000000 0.000000 \n"", + ""75% 1.000000 1.000000 \n"", + ""max 1.000000 1.000000 "" + ], + ""text/html"": [ + ""
\n"", + ""\n"", + ""\n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + ""
dobaspirinparacetamolamiodaroneatrialFibrilationdeepVeinThrombosisvalveReplacementtakenDoseWeekinrFM
count4621.0000004621.0000004621.0000004621.0000004621.0000004621.0000004621.0000004621.0000004621.0000004621.0000004621.000000
mean1947.4235010.0177450.0164470.0283490.4332400.1097170.02921429.6276392.4558970.5286730.471327
std13.8283090.1320380.1271990.1659850.4955770.3125700.16842516.0399750.3337680.4992310.499231
min1917.0000000.0000000.0000000.0000000.0000000.0000000.0000000.0000001.8000000.0000000.000000
25%1937.0000000.0000000.0000000.0000000.0000000.0000000.00000017.5000002.2000000.0000000.000000
50%1945.0000000.0000000.0000000.0000000.0000000.0000000.00000027.5000002.4000001.0000000.000000
75%1956.0000000.0000000.0000000.0000001.0000000.0000000.00000037.5000002.7000001.0000001.000000
max2004.0000001.0000001.0000001.0000001.0000001.0000001.000000210.0000003.9000001.0000001.000000
\n"", + ""
"" + ] + }, + ""metadata"": { + ""tags"": [] + }, + ""execution_count"": 34 + } + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""FNCEmKmnaEH3"", + ""colab_type"": ""code"", + ""outputId"": ""459f4490-649b-4121-f618-657a45d22ab2"", + ""colab"": { + ""base_uri"": ""https://localhost:8080/"", + ""height"": 314 + } + }, + ""source"": [ + ""plt.figure()\n"", + ""iwpc[[\n"", + "" 'INR on Reported Therapeutic Dose of Warfarin',\n"", + "" 'Therapeutic Dose of Warfarin',\n"", + "" 'Height (cm)',\n"", + "" 'Weight (kg)',\n"", + ""]].hist()\n"", + ""plt.tight_layout()\n"", + ""plt.show()"" + ], + ""execution_count"": 0, + ""outputs"": [ + { + ""output_type"": ""display_data"", + ""data"": { + ""text/plain"": [ + ""
"" + ] + }, + ""metadata"": { + ""tags"": [] + } + }, + { + ""output_type"": ""display_data"", + ""data"": { + ""text/plain"": [ + ""
"" + ], + ""image/png"": ""iVBORw0KGgoAAAANSUhEUgAAAbgAAAEYCAYAAAAu1uNdAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDIuMi4yLCBodHRwOi8vbWF0cGxvdGxpYi5vcmcvhp/UCwAAIABJREFUeJzt3X+8HFV9//HXm58iQZMYvUIIBCVWgqmAkR8V9VosApZvsI+vCE0hIBqx+AXb+AN/1KRQNVbUlq8WjRKBiiDfIiVWLI3oJaTKT4v8ipgACUkICRAIXEAl8Pn+cc4mc5fde3fv3bv37uT9fDz2sbtnZmfOzJyZz8yZs2cUEZiZmZXNdiOdATMzs+HgAGdmZqXkAGdmZqXkAGdmZqXkAGdmZqXkAGdmZqXkADdIkj4t6TsNjjtP0veGOL+dJd0jafehTKfGdI+V9INWTtNGF0k9kj4wiN9NlhSSdhiOfI0kSW+VdO9I52O4SHqPpNWSeiUdOALz30XSjyRtkvT/BjmNuyV1DyUf22yAk7RS0jur0k6RtLSR30fEFyKi6YNGo3mpYTawJCLWtWKeFRHxI2B/SX/cyulWKy5jXs8h6RNV46ypFOh8UvBc3kGfkPQLSYcNZx4L+bhI0h/yvDdKWizp9e2Yd428DFuQkfTNvIy9eXmfK3z/SavnN5LyOty38j0iboiIPxrEdCrl8qn8+q2kr7f6xLMFzgM+EhFjIuJ/igMkfUvSBYXvO0p6uk7aoYOc//8GuoBXRMR7BzOBiNg/InoGOX9gGw5wHeh04F+HadqXkQJoO20EPiFpt37G+UFEjAEmAD8HBnUmOEj/mOc9EVgLXNjGeQMw3FdOEXF6PgCOAb5AXt/5dXQr51Wyq8AfRMRuwHjgPcCrgdtGWZDbG7i7zrAlwNsK36cDDwJvrUoDuK3ZGUvaPs//txGxeRC/b1lZcYDrh6Q9JF0p6RFJD0g6szCsT7WjpJMlrZL0mKS/q3FVtpOkS/JZ392Spuff/SuwF/CjfObc56omj7MX8BrgpkLaLpK+kue5SdLSnFY54z81V1E8Lul0SW+WdEe+Gvp61Sx6gHe3Yp01YRnwS+BvBxox7ySXAhMlvbLWOJK2k/TZvD425HX98jyssk5mSXpQ0qOSPtNIJiPiWeAK4ICq+b1f0rK8fq+VtHdhWEg6U9L9eV5flrRdE/k8TdKDwM9IByOAJ3L5OKyB+f+ZpN/kcvF1QI0saz9m1lpveVnOlnRfLvdXSBrfz7Ig6f9JejjnbYmk/QvTu0jpqnJx3k+ur1qu1+dhGyXdK+n4wrA+1bAq1MZIqqzDX+d1+D5J3ZLWFMafJOmHeV9/rMY+8iIR8VxE3A28D3gEmFOY3gclrch5XSRpj5wuSV/L2/5JSXdKekMetrOk8/K6Xp/XxS615l2vHOVp9ALb5+W9r8bPlwD7SZqQv78VuBzYtSrtlxHxXJ7fQNvtAknXSHo6T/9zwPvy+j5N0msl/Syv20clXSppbGEaKyV9UtIdwNOSdlDfWp95uXy96BjaHwe4OvIB6UfAr0ln8UcAH5X0rhrjTgX+BZgJ7A68PP+m6H+RCtFYYBHwdYCIOIl09nRsPnP+xxrZmQbcX3U2dB7wJuBPSGeSnwBeKAw/BJhC2vn+CfgM8E5gf+B4SW8vjLsMmCzpZf2skuHwd6R1Or6/kSTtBJwMPAY8Xme0U/LrHaSTgTHkdVxwOPBHpG35OUn7DZRBSbsCJwIrCmkzgE8DfwG8EriBdBVc9B7SWfBBwAzg/U3k8+3AfsC72HqmPTaXj1/2N/98gPoh8FnSle99wFsGWs4B1Ftv/wc4Lud3D9K2+UY/ywLwE1K5fBXwK9KJS9FM4Nyc99srw/N2WAx8P//2BOBf8r7Xr4iorMM35nXY556z0hXHfwCrgMmkfffygaZbmP7zwNXkKyBJfwp8ETiedDxYVZjekaRt+jrSceJ4UrkGmJ/TDwD2zfn4XJ3ZnkKNchQRv89X5JXlfW2N/K7Oeapcsb2NVIZ+UZW2pPCzgbbbXwKfB3YjlZNijcCFpJOsL5LKyX7AJGBe1TROJJ1oj61z5VfzGNqviNgmX8BKoBd4ovB6Bliahx8CPFj1m08B382f5wHfy58/B1xWGO+lwB+AdxbG/Wlh+FTg2aq8vLOfvM4Ebix83w54llSAq8edDAQwsZD2GPC+wvcrgY8Wvu+Yf7PXMK/vyvo4pbCerwC+lD+vAboL6+wPebs8n5ehu5/pXwf8deH7HwHPATsU1smeheE3AyfUmdZFwO/yvF8AHgD+uDD8J8BpVdvjGWDv/D2AowrD/xq4rol8vqbG9tyhkfmTTgSKZUV5vX5ggO0zj1yea8y75nojnRgdURi2e3/LUmOeY/M4Ly+s98sLw8fkbT+JdKJ2Q9XvvwXMzZ97istYLGOFbbJv4Xs3sCZ/Pox0BbZDvbz2t55y+unA8vz5QlIVd3E5nsvr5E+B3wKHAttVbaengdcW0g4DHmi2vNda3jpl/Gu57GwgHbNOL6Q9Dry9ie12SSPrqTD8OOB/qo4P768aZyUNHkPrvbb1K7jjImJs5UU6EFXsDeyhVKX3hKQnSGfNXTWmswewuvIlIp5h61lZxcOFz88AL1Hjdc2Pk86MKiYALyGdndezvvD52RrfxxS+V6b9RIP5aaXPAR+WVGu9XpG3SxdwF+mKtZ49SGelFatIB9ridKu3QXEdVDsvz3syaX0VGyTsDfxzoVxsJB2gilftqwufV+X8NZrP4m9r6W/+1WUxGpjeQOqtt72Bqwr5WEYKSDWXRdL2kuYrVWk+STqAQSrPLxo/InpJy7ZHntchVfvjTNL9r6GaBKyKQdwvKphIyitUbeO8HI+RTjp/Rrry+AawQdKCXHPySlKQua2wfP+Z02tppBz1p3IfrlI79AywtJC2C/mWSLPbrRZJXZIul7Q2T+N7Vb8fcBoM4hi6rQe4/qwmnT2NLbx2i4hjaoy7Dtiz8iXXm7+iiXkN9EiHO4B9ChvzUdIVxouqHwZpP2BlRDzZouk1LCJ+Q6pSq3tPLCIeJTWCmaf6N/IfIh0EK/YCNtM3sA8mfw8CZ5ECSuV+yGrgQ1VlY5eI+EXhp5Oq8vJQE/mMOp8r+pv/uuK8JakqL620Gji6Kh8viYi1dfL/l6Tq2neSqucmV7JZGKeY9zGk6veH8ryur5rXmIj4cB79aVKAqGgm8K0G9mrihLOPfDvjWFI1H1Rt41y9+gpSYyUi4vyIeBPpKuR1wMdJ+/SzwP6F5Xt5bK1urDbU8r4EeCOpSrCS77tJ6//dwC0R8buc3sh2G+gY9oU8zrSIeBnwV1W/b2QaTXOAq+9m4Kl843OXfBbzBklvrjHuvwHHSvqTfL9oHs3d2F9PqkevKSLWkO4BHZy/vwAsBL6q1BBme0mHSdq5iXkWvZ1U7TVS/h44lVT1UVNE3AtcS7rXWMtlwN9I2icfGCv3AIZyVl6Z92LSAaXS0vSbwKcqN9rzzf3qptAflzRO0iRSgKzc92k2n4+QqkmL5aO/+f+Y9LePv8gH7DNpzVVOLd8EPq/cEETSK/P9wXp2A35Pupp5KWnZqx0j6fC8H51Lqm5dTbpH9jpJJyk1Yd9RqeFU5X7g7cBfSHqp0t8BTquabn/72M2kE4P5knaV9BJJA963zA0h9iNt01cDX82DLgNOlXRA3ie/ANwUEStzng+RtCMpKP8OeCHv098GvibpVXn6E2vd8y/MY9DlPSJWkNbJWeQAl6/2b8ppxftvjWy3gexGuiW0SdJEUlAfdg5wdUS6cfznpBu+D5DOsL5DOoOpHvdu0g33y0k7Si+pXvv3Dc7ui8Bnc9XEx+qM8y3gpML3jwF3AreQqka+xOC354l5+iMiIh4g/QVi1wFG/TIwu3IAqLIwT2MJaXv9jrRNWuXLpL817BwRV5HW9+W5uuUuoLpZ/dWkJta3k4JO5W8GTeUzVx19HvjvXD4O7W/++Wr3vaQGC4+RGgb89xCXvZ5/Jt3s/y9JTwE3ku5d13MJqSptLXBPHr/a94G5pDL9JtKZPhHxFKmBxgmkk42HSeugclL3NdI92/XAxby4EcQ84OK8Do8vDsj7+rGkhh0Pku5Zvq+f5XifUkvFTXn5HwPeFBEP5en9lNSA6krS8eC1Od8ALyMFssfzuniMVLYAPkk6kb0xb9ef0rdqvKgV5X0JqQq0WD5uIDUkKQa4RrbbQP6e1OBqE2l/+OEgptE05Rt21kL5jOoJYEo+eLdimjsD/0O6qd+yP3tLOhY4KSKOH3Bka4ikIG37FQOObFtIuojU8OOzI50XK4cy/flyROVAcR2pavI80tXVylZNPyJ+T6qzb6lIPZn8qNXTNTMbaa6ibJ0ZpKqTh0jVQieEL4/NzEbMgFWUkhaS7kVtiIjKP+7nAR8k3QAH+HREXJOHfYp0g/d54MyIuDanH0Wqs98e+E5EzG/50piZmWWNBLi3kRpNXFIV4Hoj4ryqcaeSWvccTPqfxk9JzWAh/bnxz0g3cG8BToyIe1q2JGZmZgUD3oOLiCWSJjc4vRmkngh+DzwgaUvTdmBFRNwPIOnyPG6/AW7ChAkxeXKjs26/p59+ml13Hajh37ZhoHVx2223PRoR9f60ag2qtU90UjnslLwOdz69P7THUBqZfETSycCtwJyIeJz0b/5iE9I1bO3dYXVVes3mxJJmk/9v1NXVxXnnnVdrtFGht7eXMWP66wxj2zHQunjHO96xqu5Aa9jkyZO59dZb+6T19PTQ3d09MhlqUqfkdbjzKcn7QxsMNsBdQPoTZuT3r7C1M9khiYgFwAKA6dOnx2jeGTplZ20HrwszG20GFeAiYkt3MJK+TeplANIfAYvdAu2Z0+gn3czMrOUG9TeBqv4A30PqSQHSv/pPUHom0T6k5vI3kxqVTMndyuxE+lf/osFn28zMrH8DXsFJuoz0aIkJSg8InAt0SzqAVEW5EvgQpC6rJF1BajyyGTgjd4ODpI+Q+hLcHliYu7cyYPLZP25ovJXz2/1MUrP+NVp2K+ZM28wpA/zG5dxapZFWlCfWSL6wRlpl/M+T+s6rTr8GuKap3JmZmQ2SezIxM7NScoAzM7NScoAza4KkSZJ+LukeSXdLOiunj5e0WNLy/D4up0vS+ZJWSLpD0kGFac3K4y+XNGuklsmsrBzgzJqzmdSxwVTgUOCM3EXd2cB1ETGF9FSJs/P4R5NaE08hdWBwAaSASGqwdQipt5+5laBoZq3hAGfWhIhYFxG/yp+fApaReuuZQXrQJvn9uPx5Bqkf14iIG4Gx+W827wIWR8TG3AvQYuCoNi6KWen5eXBmg5T7aD0QuAnoKjyI9mGgK3+eyIu7qZvYT3qt+fTpvq6np6fP8N7e3heltcucaZubGr9rl4F/M1LLUjSS69RaxwFumDT7/yDrLPmp7VcCH42IJyVtGRYRkZ/q3RIDdV83kt2kDfSftmpzpm3mK3f2f9hZObN7CDlqDXc9Vw6uojRrkqQdScHt0oj4YU5eX+nhJ79vyOn1uq/rr1s7M2sBBzizJihdql0ILIuIrxYGLQIqLSFnAVcX0k/OrSkPBTblqsxrgSMljcuNS47MaWbWIq6i7CDNVHu6u6Nh8xbgJOBOSbfntE8D84ErJJ0GrAKOz8OuAY4BVgDPAKcCRMRGSeeS+mkFOCciNrZnEcy2DQ5wZk2IiKWA6gw+osb4AZxRZ1oLgYWty52ZFbmK0szMSskBzszMSskBzszMSskBzszMSskBzszMSskBzszMSskBzszMSskBzszMSskBzszMSskBzszMSskBzszMSmnAACdpoaQNku4qpI2XtFjS8vw+LqdL0vmSVki6Q9JBhd/MyuMvlzSr1rzMzMxapZEruIuAo6rSzgaui4gpwHX5O8DRwJT8mg1cACkgAnOBQ4CDgbmVoGhmZjYcBgxwEbEEqH6Mxwzg4vz5YuC4QvolkdwIjM0Pf3wXsDgiNkbE48BiXhw0zczMWmaw9+C68kMbAR4GuvLnicDqwnhrclq9dDMzs2Ex5OfBRURIilZkBkDSbFL1Jl1dXfT09LRq0i3X29tbN39zpm1ub2aqtHu99bcuzMxGwmAD3HpJu0fEulwFuSGnrwUmFcbbM6etBbqr0ntqTTgiFgALAKZPnx7d3d21RhsVenp6qJe/U5p4+vZwWDmzu63z629dmJmNhMFWUS4CKi0hZwFXF9JPzq0pDwU25arMa4EjJY3LjUuOzGlmZmbDYsArOEmXka6+JkhaQ2oNOR+4QtJpwCrg+Dz6NcAxwArgGeBUgIjYKOlc4JY83jkRUd1wxczMrGUGDHARcWKdQUfUGDeAM+pMZyGwsKncmZmZDZJ7MjEzs1JygDMzs1JygDMzs1JygDMzs1JygDMzs1JygDMzs1JygDMzs1JygDMzs1JygDMzs1JygDMzs1JygDMzs1Ia8vPgbHSa3ODjelbOf/cw58TMbGT4Cs7MzErJAc6sSZIWStog6a5C2nhJiyUtz+/jcroknS9phaQ7JB1U+M2sPP5ySbNqzcvMBs8Bzqx5FwFHVaWdDVwXEVOA6/J3gKOBKfk1G7gAUkAkPVvxEOBgYG4lKJpZa/geXJOK97bmTNvMKQ3e67LyiIglkiZXJc8gPRgY4GKgB/hkTr8kPyvxRkljJe2ex11cefCvpMWkoHnZMGffbJvhAGfWGl0RsS5/fhjoyp8nAqsL463JafXSX0TSbNLVH11dXfT09PQZ3tvb+6K0dpkzbXNT43ftMvBvRmpZikZynVrrOMCZtVhEhKRo4fQWAAsApk+fHt3d3X2G9/T0UJ3WLs3WYMyZtpmv3Nn/YWflzO4h5Kg1RnKdWuv4HpxZa6zPVY/k9w05fS0wqTDenjmtXrqZtYgDnFlrLAIqLSFnAVcX0k/OrSkPBTblqsxrgSMljcuNS47MaWbWIq6iNGuSpMtIjUQmSFpDag05H7hC0mnAKuD4PPo1wDHACuAZ4FSAiNgo6VzgljzeOZUGJ2bWGg5wZk2KiBPrDDqixrgBnFFnOguBhS3MmpkVuIrSzMxKaUgBTtJKSXdKul3SrTmt6R4dzMzMWq0VV3DviIgDImJ6/t5Ujw5mZmbDYTiqKGeQenIgvx9XSL8kkhuBSo8OZmZmLTfURiYB/Ff+U+u38h9Sm+3RYV0hbcBeG0ZasReGRnplGO1atX7d84OZjTZDDXCHR8RaSa8CFkv6TXHgYHp0GKjXhpF2SlVflAP1yjDatarXCPf8YGajzZCqKCNibX7fAFxF6hW92R4dzMzMWm7QAU7SrpJ2q3wm9cRwF8336GBmZtZyQ6lf6wKuklSZzvcj4j8l3UITPTqYmZkNh0EHuIi4H3hjjfTHaLJHBzMzs1ZzTyZmZlZKDnBmZlZKDnBmZlZKnf0nLjPjzrWbGnqy9sr57254mpObfFK32WjkKzgzMyslBzgzMyslBzgzMyslBzgzMyslBzgzMyslBzgzMyslBzgzMyslBzgzMysl/9F7G9fMH3qb+aOwmdlI8xWcmZmVkgOcmZmVkgOcmZmVku/Bmdmo0uh9Yd8TtoH4Cs7MzErJAc7MzErJVZSZn39lZlYuvoIzM7NScoAzM7NSansVpaSjgH8Gtge+ExHz250Hs9GinfuDq+FtW9PWKzhJ2wPfAI4GpgInSprazjyYjRbeH8yGV7uv4A4GVkTE/QCSLgdmAPe0OR82CP1dAcyZtplT8nD/P6lh3h+GwP2o2kDaHeAmAqsL39cAhxRHkDQbmJ2/9kq6t015a9qZMAF4dKTzMRoU14W+VHOUvduZnw4x4P4ADe0THVMOR2qfqVMm+zPc+fT+0Aaj7m8CEbEAWDDS+WiEpFsjYvpI52M08LoYPgPtE5207jslr52ST+tfu1tRrgUmFb7vmdPMtkXeH8yGUbsD3C3AFEn7SNoJOAFY1OY8mI0W3h/MhlFbqygjYrOkjwDXkppFL4yIu9uZhxbriKrUNvG6aFIL94dOWvedktdOyaf1QxEx0nkwMzNrOfdkYmZmpeQAZ2ZmpeQAV4ekhZI2SLqrkDZP0lpJt+fXMYVhn5K0QtK9kt41MrkePpImSfq5pHsk3S3prJw+XtJiScvz+7icLknn53Vyh6SDRnYJOp+ko3L5WiHp7BrDd5b0gzz8JkmTRyCPNctJ1TjdkjYV9qPPtTufhbyslHRnzsetNYa7HHeyiPCrxgt4G3AQcFchbR7wsRrjTgV+DewM7APcB2w/0svQ4vWxO3BQ/rwb8Nu83P8InJ3Tzwa+lD8fA/wEEHAocNNIL0Mnv0iNUO4DXgPslMvb1Kpx/hr4Zv58AvCD0VJOqsbpBv5jpNdpzstKYEI/w12OO/jlK7g6ImIJsLHB0WcAl0fE7yPiAWAFqRum0oiIdRHxq/z5KWAZqSeOGcDFebSLgePy5xnAJZHcCIyVtHubs10mW7r1iog/AJVuvYqK2+LfgCMkqY157K+cdCqX4w7mANe8j+SqioWV6jhqd7nUyTt1v3LV14HATUBXRKzLgx4GuvLnbWqdtEEj63PLOBGxGdgEvKItuauhqpxUO0zSryX9RNL+bc1YXwH8l6Tbcpdo1VyOO5gDXHMuAF4LHACsA74ystlpP0ljgCuBj0bEk8VhERGkA4Zt4/orJ8CvgL0j4o3A/wX+vd35Kzg8Ig4iPdHhDElvG8G8WIs5wDUhItZHxPMR8QLwbbZWQ24TXS5J2pF00Lo0In6Yk9dXqmzy+4acvk2skzZqZH1uGUfSDsDLgcfakruCOuVki4h4MiJ68+drgB0lTWhzNit5WZvfNwBX8eJbCy7HHcwBrglVde/vASotLBcBJ+RWbPsAU4Cb252/4ZTv5VwILIuIrxYGLQJm5c+zgKsL6SfnVmiHApsKVZnWvEa69Spui/8N/CxfVbdNP+WkOM6rK/cGJR1MOg6NRCDeVdJulc/AkWzdpytcjjvYqHuawGgh6TJSa68JktYAc4FuSQeQquFWAh8CiIi7JV1Beo7XZuCMiHh+JPI9jN4CnATcKen2nPZpYD5whaTTgFXA8XnYNaQWaCuAZ4BT25vdcok63XpJOge4NSIWkQLLv0paQWogdcIIZLVeOdkLICK+SQq+H5a0GXgWOKHdgTjrAq7KsXYH4PsR8Z+STi/k1eW4g7mrLjMzKyVXUZqZWSk5wJmZWSk5wJmZWSk5wJmZWSk5wJmZWSk5wJmZWSk5wJmZWSk5wJmZWSk5wJmZWSk5wJmZWSk5wJmZWSk5wJmZWSkNOcBJmifpe63IzGgj6ZuS/m6k8zEc8uM/vivpcUkj8mgfSW+RtFxSr6TjBvH7t0q6dzjyZkPTzL4j6SJJ/zDE+b1S0m8k7ZK/90j6wCCm0yVpmaSdh5IfGx0GDHD54FN5vSDp2cL3me3IZDtIOkXS0mJaRJweEecOYlor83p6StITkn4h6XRJo+mK+XDgz4A9I6LPQx4l7ZC37yGFtJmSokbab4aQh3OAr0fEmIho+qnOEXFDRPzREOZvmaRPSfpJVdryOmkDPoZnsPtOnbyFpH0HGO1s4KKIeHYo84qI9cDPgdlDmY6NDgMecPPBZ0xEjAEeBI4tpF3ayszkpxCXxbERsRuwN+mZaZ8kPa9rtNgbWBkRT1cPiIjNwC+BtxWS3wb8pkbakmZnXNjOewN3N/v7qmlYaywB/kTS9rDl4b47AgdWpe3LILb5cMpXW7OAVtUkXUp+1qN1tlZdUewk6ZJ8xXK3pOmVAZL2kHSlpEckPSDpzMKweZL+TdL3JD0JnCLpYEm/zFc+6yR9PT/BuPKbkHSmpPslPSrpy8UrI0nvz1UMj0u6VtLeOX1y/u0OhXF7JH1A0n7AN4HD8pXLE3l4n6oTSTMk3S7pSUn3STpqoBUTEZvywyjfB8yS9IY8rZfndfaIpFWSPltZDkn7Srpe0qa8jD8o5OH1khZL2ijpXknH157zlnW/KI+7QtIHc/ppwHcKy/v3NX6+hL7B7K3Al2qkLcnTbGS7nSFpObBc0n3Aa4Af5TzsLOnUvO2eytv3Q4Xfd0taI+mTkh4GvltJK4yzUtLHJN2R190PJL2k3w1kFbeQAtoB+ftbSVcy91al3RcRD0H/ZbHGvvOJXC4eyvtc9VXZOEk/ztv+Jkmvzb+rBNNf53Lyvhp5PwR4IiLW1BiGpN1zmfh4/r6PpCV5Xj+V9A31vc1yE/CayrHDOlhENPwiPcX6nVVp84DfkZ56uz3wReDGPGw74Dbgc8BOpAPa/cC7Cr99Djguj7sL8CbgUNITdicDy4CPFuYXpB1vPOkpwb8FPpCHzSA9eXe//PvPAr/Iwybn3+5QmFZP4benAEurlu0i4B/y54OBTaRqve2AicDrG11POf1B4MP58yXA1cBuOW+/BU7Lwy4DPpPn8xLg8Jy+K7Ca9FThHYADgUeBqXXysQT4lzyNA4BHgD+tt7xVv3076anQ2wETSE/rfimwvpAWwF55/Ea22+K83XaptZ6AdwOvBZTn/wxwUB7WTXpa+peAnXNZ6QbWVK33m4E98nyWAac3U8a35Rdpv/qb/PnrwPuBz1elLWykLFbtO0cBDwP75zL0vVwe9i2M+xhpH9uBdAV1eVXZ2beffJ8B/LgqrQf4ALAPad+aXRj2S+A80jHpcOBJ4HtVv78D+F8jvU38GtqrVVdwSyPimoh4HvhX4I05/c3AKyPinIj4Q0TcD3wbKNbh/zIi/j0iXoiIZyPitoi4MSI2R8RK4Fukg13RlyJiY0Q8CPwTcGJOPx34YkQsi1TN9gXggBadiZ1G2rkX57yujYhm7z89BIxXqvI5AfhURDyVl/MrwEl5vOdI1Xd7RMTvIqJyb/DPSdWK383r53+AK4H3Vs9I0iTgLcAn8zRuJ121ndxgXm8iHYymkc7cl0bEM8ADhbSVeRvQ4Hb7Yt5uNe+TRMSPI+K+SK4H/ivPp+IFYG5E/L7eNIDzI+KhiNgI/IitVx82sOvZeoX+VuCG/CqmXZ8/N1wWgeOB70bE3bkMzasxzlURcXPeby+lue02FniqRvpUUtCeGxELACTtRToufS4fk5YCi2r89qk8XetgrQpwDxc+PwO8JFcVnrVQAAAPgklEQVQF7g3skautnshVf58Gugrjry5OSNLrJP2HpIeVqi2/QLpaoM5vVpHO2Mnz++fCvDaSrgYmDnH5ACYB9w1xGhNJeZpAqg5aVRi2iq35/AQp3zcrVfm+P6fvDRxStT5nAq+uMa89gI0RUdzxi/PoV0T8jnQ19Lb8uiEPWlpI23IvZhDb7UUkHS3pxlzl9QSpVqA4jUdyvvpTXRbHDDC+bbUEOFzSeNKJ6XLgF6R7c+OBN7B1mzdbFovbvlY5GMp2e5xUE1JtJrAW+LeqvGzMgba//OwGPNFEHmwUGu5WfauBByJibOG1W0QcUxgnqn5zAakxw5SIeBkpIKpqnEmFz3uRrowq8/tQ1fx2iYhfAJXGFC8t/La4M1bno9ayvHaAceqS9GZScFlKqsqpXKVV7EXaGYmIhyPigxGxB+lm97/k+xWrgeurlm9MRHy4xiwrV4vFHX/LPBpUuQ9XOZuHrWf0W+6/ZY1st7rrWKmhwJWkqqOuiBgLXFM1jYG2kQ3NL4GXAx8E/hsgIp4klaUPAg9FxAN53GbK4jpgz8L3STXGGYo7gNfVSJ9H2te+n2tNKnkZL6l4HOiTn3xyvi/w6xbn09psuAPczcBTuWHALpK2l/SGfLCvZzdSnXivpNcDtXaYj0sal6vhzgIqjTC+CXxK0v6wpSHHewEi4hHSwf2vcj7eT9+AtR7Ys9gwosqFwKmSjpC0naSJOX/9kvQySX8OXE6q578zV+VeAXxe0m65CvVvya3AJL1XUuWA8DjpwP4C8B/A6ySdJGnH/HqzUiOZPiJiNens+4uSXiLpj0nVrM20NFsCvIN0ALgnp/036d7XAfQNcI1st/7sRLq39giwWdLRwJFNTsOGIFf73koqizcUBi3NacXt3XBZJJX1UyXtlwNLs/8tXU+6f1/PzcBYSdW1E8+Rqkx3BS6RtF1ErCIt4zxJO0k6DDi26ncHk6pfV2EdbVgDXD6Q/znpYPgA6WzqO6SzxHo+BvwlqQ7822wNXkVXkxqv3A78mNz8PiKuIjVCuDxXk90FHF343QeBj5NuaO9PCgAVPyM1WX9Y0qM1luVm0g31r5Eam1xP3yuwaj+S9BTpTPczwFfz7yv+D+mq8n7SAeT7wMI87M3ATZJ6SfcHzoqI+3N145Gk+3cPkap1Ko0uajmR1ODjIeAq0r2In/aT52q/IG2rmyLy3f6IR0lBaEOuwqpoZLvVlZftTNLB8PE8rVr3Rmx4XQ+8ilQmK27IaVsCXDNlMSJ+ApxPuh+2ArgxD/p9g3maB1ycq0Jf1Go4Iv5AaqjyV3WG/QXptshCpZbKM4HDSMeBfyCV1WJeZpJOlq3DKR+3OoakIFWDrRjpvJhZ8/JV3l3AzrlRSSum+UpSID6wnwZI9X77A+A3ETFX0qtIQf7ABu732ijnAGdmw07Se0j3VF8KXAy8EBFNd8/Wory8mdTY6wHSVei/A4fllqBWIqOp6ygzK68PARtILZGfp/l7tK30atL/5HpJVacfdnArp467gjMzM2uEr+DMzKyURnWHtRMmTIjJkyf3SXv66afZddddRyZDg9SJeYbW5vu22257NCJe2ZKJbcNq7ROjSaeW9WrDvRzeH9pjVAe4yZMnc+utt/ZJ6+npobu7e2QyNEidmGdobb4l+T9FLVBrnxhNOrWsVxvu5fD+0B6uojQzs1JygDNrgqRJkn4u6Z7cT+hZOX280qNjluf3cTldks5XelzRHZIOKkxrVh5/uaRZI7VMZmXlAGfWnM3AnIiYSno80BmSppKeKH1dREwBrsvfIfWkMyW/ZpP67CR3XjyX9Cyzg4G5laBoZq0xqu/BDdXks3/c8Lgr5797GHNiZRER60gd9hIRT0laRupEewapj05If2TuIT3FfQZwSe7q7EZJY5WejN0NLM6P9UHSYtJz0y4brrw3sz80yvuNjWalDnBmw0nSZNKDPm8iPQFhXR70MFsfCTWRvo9jWZPT6qXXms9s0tUfXV1d9PT0DCq/c6a1pFesPqrz0tvbO+j8jSZlWY5tnQOc2SBIGkN6vM9HI+JJaetTfSIicpdyLZEf1rkAYPr06THY1n2nDMcV3MzuPt/ditJGE9+DM2uSpB1Jwe3SiPhhTl6fqx7J7xty+lr6Pm9sz5xWL93MWsQBzqwJSpdqFwLLIuKrhUGLgEpLyFmkRzpV0k/OrSkPBTblqsxrgSPzcw3HkTr9vbYtC2G2jXAVpVlz3gKcBNwp6fac9mlgPnCFpNOAVUDluWXXAMeQnoP2DPmZgBGxUdK5wC15vHMqDU7MrDUc4MyaEBFLAdUZfESN8QM4o860FrL1Ibdm1mKuojQzs1JygDMzs1JygDMzs1JygDMzs1JygDMzs1JygDMzs1JygDMzs1JygDMzs1JygDMzs1JygDMzs1JygDMzs1LqyL4oh+PJxGZmVi6+gjMzs1IaMMBJmiTp55LukXS3pLNy+nhJiyUtz+/jcroknS9phaQ7JB1UmNasPP5ySbPqzdPMzGyoGrmC2wzMiYipwKHAGZKmAmcD10XEFOC6/B3gaGBKfs0GLoAUEIG5wCHAwcDcSlA0MzNrtQEDXESsi4hf5c9PAcuAicAM4OI82sXAcfnzDOCSSG4ExkraHXgXsDgiNkbE48Bi4KiWLo2ZmVnW1D04SZOBA4GbgK6IWJcHPQx05c8TgdWFn63JafXSzczMWq7hVpSSxgBXAh+NiCelrQ81joiQFK3IkKTZpKpNurq66Onp6TO8t7eXOdOeb8Ws+qieTyv19vYO6/SHS6fm28wMGgxwknYkBbdLI+KHOXm9pN0jYl2ugtyQ09cCkwo/3zOnrQW6q9J7qucVEQuABQDTp0+P7u7uPsN7enr4ytKnG8l2U1bO7B5wnMHq6emhejk6Qafm28wMGmtFKeBCYFlEfLUwaBFQaQk5C7i6kH5ybk15KLApV2VeCxwpaVxuXHJkTjMzM2u5Rq7g3gKcBNwp6fac9mlgPnCFpNOAVcDxedg1wDHACuAZ4FSAiNgo6VzgljzeORGxsSVLYWZmVmXAABcRSwHVGXxEjfEDOKPOtBYCC5vJoJmZ2WC4JxMzMyslBzgzMyslBzgzMyslBzgzMyslBzgzMyslBzgzMyslBzgzMyslBzgzMyslBzgzMyslBzgzMyslBzgzMyslBzgzMyslBzgzMyslBzizJklaKGmDpLsKaeMlLZa0PL+Py+mSdL6kFZLukHRQ4Tez8vjLJc2qNS8zGzwHOLPmXQQcVZV2NnBdREwBrsvfAY4GpuTXbOACSAERmAscAhwMzK0ERTNrDQc4syZFxBKg+mG9M4CL8+eLgeMK6ZdEciMwVtLuwLuAxRGxMSIeBxbz4qBpZkPgAGfWGl0RsS5/fhjoyp8nAqsL463JafXSzaxFBnyit5k1JyJCUrRqepJmk6o36erqoqenZ1DTmTNtc6uytEV1Xnp7ewedv9GkLMuxrXOAM2uN9ZJ2j4h1uQpyQ05fC0wqjLdnTlsLdFel99SacEQsABYATJ8+Pbq7u2uNNqBTzv7xoH7Xn5Uzu/t87+npYbD5G03KshzbOldRmrXGIqDSEnIWcHUh/eTcmvJQYFOuyrwWOFLSuNy45MicZmYt4is4syZJuox09TVB0hpSa8j5wBWSTgNWAcfn0a8BjgFWAM8ApwJExEZJ5wK35PHOiYjqhitmNgQOcGZNiogT6ww6osa4AZxRZzoLgYUtzFrbTa6q9pwzbXPdqtCV89/djiyZbeEqSjMzKyUHODMzKyUHODMzK6UBA5z73TMzs07UyBXcRbjfPTMz6zADBjj3u2dmZp1osH8TGLZ+9wbqlqi3t5c5054fZLbrG85ueTq1259OzbeZGbTgf3Ct7ndvoG6Jenp6+MrSp1s1uy2quxxqpU7t9qdT821mBoNvRbk+Vz3SRL97tdLNzMyGxWADnPvdMzOzUW3AKkr3u2dmZp1owADnfvfMzKwTuScTMzMrJQc4MzMrJQc4MzMrJT8PLqt+rlU9fqaVmVln8BWcmZmVkgOcmZmVkgOcmZmVkgOcmZmVkgOcmZmVkgOcmZmVkgOcmZmVkv8HZ9bhGv0Pp9m2xldwZmZWSg5wZmZWSq6iNLO2cHd41m6+gjMzs1JygDMzs1JygDMzs1JygDMzs1JygDMzs1JygDMzs1JygDMzs1JygDMzs1LyH72b5D+rmg0v72PWKm2/gpN0lKR7Ja2QdHa75282mnh/MBs+bQ1wkrYHvgEcDUwFTpQ0tZ15MBstvD+YDa92V1EeDKyIiPsBJF0OzADuaXM+hl2xmmXOtM2c0k+1i6tatlnbzP4wHIbjMUHeF8ul3QFuIrC68H0NcEhxBEmzgdn5a6+ke6umMQF4dNhyOAzOHCDP+lIbM9OcVq7rvVs0nTIZcH+AhvaJUWOgsj7aFfbF4V4O7w9tMOoamUTEAmBBveGSbo2I6W3M0pB1Yp6hc/NdNgPtE6NJWcpMWZZjW9fuRiZrgUmF73vmNLNtkfcHs2HU7gB3CzBF0j6SdgJOABa1OQ9mo4X3B7Nh1NYqyojYLOkjwLXA9sDCiLi7ycl0RFVNlU7MM3RuvjtCi/aH0aYsZaYsy7FNU0SMdB7MzMxazl11mZlZKTnAmZlZKXVMgBvNXRpJWihpg6S7CmnjJS2WtDy/j8vpknR+Xo47JB00gvmeJOnnku6RdLekszol7zYyOrWsV3PZ3zZ0RIDrgC6NLgKOqko7G7guIqYA1+XvkJZhSn7NBi5oUx5r2QzMiYipwKHAGXm9dkLebWRcRGeW9Wou+9uAjghwFLo0iog/AJUujUaFiFgCbKxKngFcnD9fDBxXSL8kkhuBsZJ2b09O+4qIdRHxq/z5KWAZqXeNUZ93GxmdWtaruexvGzolwNXq0mjiCOWlUV0RsS5/fhjoyp9H5bJImgwcCNxEh+XdRlxHlxeX/fLqlADX0SL9F2PU/h9D0hjgSuCjEfFkcdhoz7uNLp1WXlz2y61TAlwndmm0vlKFkd835PRRtSySdiTt4JdGxA9zckfk3UaNjiwvLvvl1ykBrhO7NFoEzMqfZwFXF9JPzq2yDgU2FapE2kqSgAuBZRHx1cKgUZ93G1U6rry47G8jIqIjXsAxwG+B+4DPjHR+qvJ2GbAOeI5UN38a8ApSK6zlwE+B8XlckVqE3gfcCUwfwXwfTqqCuQO4Pb+O6YS8+zViZaYjy3qN5XDZ3wZe7qrLzMxKqVOqKM3MzJriAGdmZqXkAGdmZqXkAGdmZqXkAGdmZqXkAGdmZqXkAGdmZqX0/wFzKc4hOvF/fQAAAABJRU5ErkJggg==\n"" + }, + ""metadata"": { + ""tags"": [], + ""needs_background"": ""light"" + } + } + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""9B6x06oxa4gA"", + ""colab_type"": ""code"", + ""outputId"": ""67b4d4f7-0b6e-4fb0-e6e6-2b3114e36c9e"", + ""colab"": { + ""base_uri"": ""https://localhost:8080/"", + ""height"": 314 + } + }, + ""source"": [ + ""plt.figure()\n"", + ""path[[\n"", + "" 'inr',\n"", + "" 'takenDoseWeek',\n"", + ""]].hist()\n"", + ""plt.tight_layout()\n"", + ""plt.show()"" + ], + ""execution_count"": 0, + ""outputs"": [ + { + ""output_type"": ""display_data"", + ""data"": { + ""text/plain"": [ + ""
"" + ] + }, + ""metadata"": { + ""tags"": [] + } + }, + { + ""output_type"": ""display_data"", + ""data"": { + ""text/plain"": [ + ""
"" + ], + ""image/png"": ""iVBORw0KGgoAAAANSUhEUgAAAagAAAEYCAYAAAAJeGK1AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDIuMi4yLCBodHRwOi8vbWF0cGxvdGxpYi5vcmcvhp/UCwAAHlJJREFUeJzt3XuUXGWd7vHvY8JNQBII9sQkQ+KYcQ5ORsRekBHHacXhEpQw56ALDyOBE1eOa8DxkhmNlyWM1+gZZEQ9OFEyBGVARB0yEi+ZmDoZnJNwUSRc5KTFYJIJiRIINIyXht/5Y78N26IqnXRV7XpT/XzW6tW73v1W7V/t7qqn97vf3qWIwMzMLDfP6XYBZmZmjTigzMwsSw4oMzPLkgPKzMyy5IAyM7MsOaDMzCxLDqgeIuluSQPdrsOsHSRdJekj3a5jfySpJukt3a6jVQ6oHhIRL4mIWrfrMGtG0mZJr+1yDVdJ+rWkx9LXXZI+LumIDm5zoqQhSSeW2s6VFA3aftypOvY3DqhxTtLEbtdg1gWfjIjDgaOBC4C5wPclHdqJjUXEMPB/gVeVml8F/LhB27pO1LA/ckD1kJG/TiVdIul6SVenvxDvltRf1+89ku4EHndIWRUkfQn4XeBf0tHEuyV9VdKDknZLWifpJU3ue7iktZIuV+EgSX8n6WeSdkj6vKRDUt8BSVslLZa0U9J2SRc0etyI+GVE3AqcCRxFEVZIeo6kD0h6ID3G1SNHWJIOlvRlSQ9JekTSrZL60rojJF2ZtrlN0kckTUibW8dvh9GfAJ9o0LauVMMSST9J27pe0pGlfTJX0r+nGn7UbHhf0lRJd0r6mz38eLLkgOpdZwLXAZOAlcBn69a/CTgDmJT+ujPrqIh4M/Az4PURcVhEfBL4FjAbeD7wA+Ca+vtJOgpYA3w/Iv4qiuuzLQV+HzgOeBEwDfhg6W6/AxyR2hcCn5M0eQ+1PQaspggIgPPT16uBFwKH8cxraEF67BkUofZW4D/TuquA4VTTy4BTgJFzQeuAk1LwTAEOBa4HTii1/ReeOYJ6G3AW8KfAC4CHgc+lfTINuAn4CHAk8NfA1yQdXbfvZgH/B/hsRPyvZs8/Vw6o3nVzRKyKiCeBLwEvrVt/eURsiYj/bHBfs0pExPKIeCwifgVcAry07lzQCyjeYL8aER8AkCRgEfDOiNiVwuVjwDml+/0G+FBE/CYiVgFDwItHKec/KN7sAc4FPhUR90fEEPBe4Jw02vAbimB6UUQ8GRG3R8Sj6ShqHvCOiHg8InYCl5Xq2gA8F5hDEYQ3R8QTwE9LbZsj4mep/1uB90fE1tL+OTvV8BfAqvQafyoiVgO3pe2POBZYC1wcEctGee5Z8tBO73qwtPwEcLCkiaWjpS1dqMnsaWno66PAGyjOBT2VVk0BdqflMyjC5fOlux5N8UZ/e5FVxcMBE0p9HqobGXiC4ihoT6YBu9LyC4AHSuseoHi/7KP4g28GcJ2kScCXgfcDxwAHANtLdT2H9FqLiF9KuoViSO+FwL+lPjeX2srnn44BviHpqVLbk6mGY4A3SHp9ad0BFIE04lxgELhhlOedLR9BjV++jL11Q/n37r8D84HXUgyZzUztKvX5AvBtYFVpAsMvKIbUXhIRk9LXERExWgA1JemwVMdIaPwHRQiM+F2Kobsd6ajsbyPiWOAVwOuA8yiC6FfAlFJdz4uI8nm1kfNQf1La1r+V2soBtQU4vfRYkyLi4IjYltZ9qW7doRGxtHT/S9K++qfSebD9igPKzKq0g+JIAeBwijf0hyiOiD7W5D4XAfdRTK44JCKeogiuyyQ9H4pzMpJO3ddi0mSLlwP/THGO5x/TqmuBd0qalcLrY8BXImJY0qslzUlv+o9SDPk9FRHbge8Cl0p6Xjqv9HuS/rS0yXUU57VmAPektu8DAxTn08oB9Xngo5KOSbUeLWl+Wvdl4PWSTpU0IU3cGJA0vXT/31AcnR4KXC1pv3u/3+8KNrP92seBD0h6hOJ8zwPANoo36/WN7pAmRSwCtgI3SjoYeA/F8NV6SY8C/8ro55jK3i3pMYpwvBq4HXhFRDye1i+nGMpbR3GO6JcUkxagmIBxA0U43UtxjuxLad15wIHp+Tyc+k0tbfffKY4WN6TnRUT8Avg5sDMiNpX6fppigtN3U63rgRPTfbZQHH2+L913C/A31L2nR8Svgf9KMSy4fH8LKfkDC83MLEf7VZqamdn44YAyM7MsOaDMzCxLDigzM8tS1v+oO2XKlJg5c2bbH/fxxx/n0EM7ck3IMcmpnpxqgbzquf32238REUeP3jM/e3ot5bSPIa96cqoFeqeevX4tRUS2Xy9/+cujE9auXduRxx2rnOrJqZaIvOoBbosMXhdj+drTaymnfRyRVz051RLRO/Xs7WvJQ3xmZpYlB5SZmWXJAWVmZllyQJmZWZYcUGZmliUHlJmZZckBZWZmWXJAmZlZlkYNKEnLJe2UdFep7UhJqyVtSt8np3ZJulzSoKQ7JR1fus+C1H+TpAWdeTpmZtYr9uYI6irgtLq2JcCaiJgNrEm3AU4HZqevRcAVUAQacDHFh22dAFw8EmpmZmaNjHotvohYJ2lmXfN8io8oBlgB1Cg+4XI+cHW6lMV6SZMkTU19V0fELgBJqylC79qWn8EYzVxy05jvu3npGW2sxGz/5deRddJYLxbbFxHb0/KDFB8nDDCN4qOHR2xNbc3an0XSIoqjL/r6+qjVamMssbmhoSEWz3lyzPdvd01DQ0MdeZ5jkVMtkF89Zladlq9mHhEhqW2fGx8Ry4BlAP39/TEwMNCuh35arVbj0psfH/P9N5870L5iKOrpxPMci5xqgfzqMbPqjHUW3440dEf6vjO1bwNmlPpNT23N2s3MzBoaa0CtBEZm4i0Abiy1n5dm880FdqehwO8Ap0ianCZHnJLazMzMGhp1iE/StRSTHKZI2koxG28pcL2khcADwBtT91XAPGAQeAK4ACAidkn6MHBr6vehkQkTZmZmjezNLL43NVl1coO+AVzY5HGWA8v3qTozMxu3sv7I91x5aq2ZWef5UkdmZpYlB5SZmWXJAWVmZllyQJmZWZYcUGZmliUHlJmZZckBZWZmWXJAmZlZlhxQZmaWJQeUmZllyQFlZmZZckCZmVmWHFBmFZE0Q9JaSfdIulvS21P7kZJWS9qUvk9O7ZJ0uaRBSXdKOr70WAtS/02SFjTbptn+zAFlVp1hYHFEHAvMBS6UdCywBFgTEbOBNek2wOnA7PS1CLgCikCj+Fy2E4ETgItHQs2slzigzCoSEdsj4gdp+THgXmAaMB9YkbqtAM5Ky/OBq6OwHpgkaSpwKrA6InZFxMPAauC0Cp+KWSUcUGZdIGkm8DJgA9AXEdvTqgeBvrQ8DdhSutvW1Nas3ayn+AMLzSom6TDga8A7IuJRSU+vi4iQFG3aziKKoUH6+vqo1WoN+w0NDTVdN5rFc4bHWB0dqafdcqoFxl89DiizCkk6gCKcromIr6fmHZKmRsT2NIS3M7VvA2aU7j49tW0DBuraa/XbiohlwDKA/v7+GBgYqO8CFEHRbN1ozm/l06XPbX897ZZTLTD+6vEQn1lFVBwqXQncGxGfKq1aCYzMxFsA3FhqPy/N5psL7E5Dgd8BTpE0OU2OOCW1mfUUH0GZVeck4M3ARkl3pLb3AUuB6yUtBB4A3pjWrQLmAYPAE8AFABGxS9KHgVtTvw9FxK5qnoJZdRxQZhWJiJsBNVl9coP+AVzY5LGWA8vbV51ZfjzEZ2ZmWXJAmZlZlhxQZmaWJQeUmZllyQFlZmZZckCZmVmWPM28YjMb/Of94jnDo/5H/ualZ3SqJDOzLPkIyszMsuSAMjOzLDmgzMwsSw4oMzPLkgPKzMyy5IAyM7MstRRQkt4p6W5Jd0m6VtLBkmZJ2iBpUNJXJB2Y+h6Ubg+m9TPb8QTMzKw3jTmgJE0D/groj4g/BCYA5wCfAC6LiBcBDwML010WAg+n9stSPzMzs4ZaHeKbCBwiaSLwXGA78BrghrR+BXBWWp6fbpPWn5w+YdTMzOxZxhxQEbEN+DvgZxTBtBu4HXgkIoZTt63AtLQ8DdiS7juc+h811u2bmVlvG/OljiRNpjgqmgU8AnwVOK3VgiQtAhYB9PX1UavVWn3IZxkaGmLxnCfb/rhj1XdIcbmjPenEfmhkaGiosm3tjdzqMbPqtHItvtcCP42InwNI+jpwEjBJ0sR0lDQd2Jb6bwNmAFvTkOARwEP1DxoRy4BlAP39/TEwMNBCiY3VajUuvfnxtj/uWC2eM8ylG/f8o9h87kAltdRqNTqxz8cqt3rMrDqtnIP6GTBX0nPTuaSTgXuAtcDZqc8C4Ma0vDLdJq3/XkREC9s3M7Me1so5qA0Ukx1+AGxMj7UMeA/wLkmDFOeYrkx3uRI4KrW/C1jSQt1mZtbjWvq4jYi4GLi4rvl+4IQGfX8JvKGV7ZmZ2fjhK0mYmVmWHFBmZpYlB5SZmWXJAWVmZllyQJmZWZYcUGZmliUHlJmZZckBZWZmWXJAmZlZlhxQZmaWJQeUmZllyQFlZmZZckCZmVmWHFBmZpYlB5SZmWXJAWVmZllyQJmZWZYcUGZmliUHlJmZZckBZVYRScsl7ZR0V6ntEknbJN2RvuaV1r1X0qCk+ySdWmo/LbUNSlpS9fMwq4oDyqw6VwGnNWi/LCKOS1+rACQdC5wDvCTd539LmiBpAvA54HTgWOBNqa9Zz5nY7QLMxouIWCdp5l52nw9cFxG/An4qaRA4Ia0bjIj7ASRdl/re0+ZyzbrOAWXWfRdJOg+4DVgcEQ8D04D1pT5bUxvAlrr2Exs9qKRFwCKAvr4+arVaw40PDQ01XTeaxXOGx3Q/oCP1tFtOtcD4q8cBZdZdVwAfBiJ9vxT4H+144IhYBiwD6O/vj4GBgYb9arUazdaN5vwlN42xOth8bvvrabecaoHxV48DyqyLImLHyLKkLwDfTDe3ATNKXaenNvbQbtZTPEnCrIskTS3d/HNgZIbfSuAcSQdJmgXMBm4BbgVmS5ol6UCKiRQrq6zZrCo+gjKriKRrgQFgiqStwMXAgKTjKIb4NgP/EyAi7pZ0PcXkh2Hgwoh4Mj3ORcB3gAnA8oi4u+KnYlYJB5RZRSLiTQ2ar9xD/48CH23QvgpY1a66Nm7b3dK5JLNO8RCfmZllyUdQ+4mZrcyWWnpGGysxM6uGj6DMzCxLDigzM8uSA8rMzLLkgDIzsyw5oMzMLEstBZSkSZJukPRjSfdK+mNJR0paLWlT+j459ZWky9Nn2Nwp6fj2PAUzM+tFrR5BfRr4dkT8AfBS4F5gCbAmImYDa9JtKD6/Znb6WkRxkUwzM7OGxhxQko4AXkX6T/iI+HVEPELx2TQrUrcVwFlpeT5wdRTWA5PqrkNmZmb2tFaOoGYBPwf+UdIPJX1R0qFAX0RsT30eBPrS8jSe/Tk20zAzM2uglStJTASOB94WERskfZpnhvMAiIiQFPvyoHv7IWutGBoaYvGcJ9v+uGPVd0hrH/w2mn3Zh+PtA9HMLF+tBNRWYGtEbEi3b6AIqB2SpkbE9jSEtzOt39Pn2zxtbz9krRW1Wo1Lb3687Y87VovnDHPpxs5ddarZB8M1Mt4+EM3M8jXmIb6IeBDYIunFqelkio8GWAksSG0LgBvT8krgvDSbby6wuzQUaGZm9lta/bP9bcA16YPT7gcuoAi96yUtBB4A3pj6rgLmAYPAE6mvmZlZQy0FVETcAfQ3WHVyg74BXNjK9szMbPzwlSTMzCxLDigzM8uSA8rMzLLkgDIzsyw5oMzMLEsOKDMzy5IDyszMsuSAMjOzLDmgzMwsSw4oMzPLkgPKzMyy5IAyM7MsOaDMzCxLDigzM8uSA8rMzLLkgDIzsyw5oMzMLEutfuR7V81cctOY7rd4zjD7+VM3M+t5fpceB/YlyBfPGeb8Uv/NS8/oRElmZqPyEJ+ZmWXJAWVmZllyQJmZWZYcUGZmliUHlJmZZckBZVYRScsl7ZR0V6ntSEmrJW1K3yendkm6XNKgpDslHV+6z4LUf5OkBd14LmZVcECZVecq4LS6tiXAmoiYDaxJtwFOB2anr0XAFVAEGnAxcCJwAnDxSKiZ9RoHlFlFImIdsKuueT6wIi2vAM4qtV8dhfXAJElTgVOB1RGxKyIeBlbz7NAz6wkOKLPu6ouI7Wn5QaAvLU8DtpT6bU1tzdrNeo6vJGGWiYgISdGux5O0iGJ4kL6+Pmq1WsN+fYeMXP6rWs3qGRoaarquajnVAuOvHgeUWXftkDQ1IranIbydqX0bMKPUb3pq2wYM1LXXGj1wRCwDlgH09/fHwMBAo2585pobuXRj9W8Fm88daNheq9VoVmvVcqoFxl89HuIz666VwMhMvAXAjaX289JsvrnA7jQU+B3gFEmT0+SIU1KbWc/xEZRZRSRdS3H0M0XSVorZeEuB6yUtBB4A3pi6rwLmAYPAE8AFABGxS9KHgVtTvw9FRP3EC7Oe4IAyq0hEvKnJqpMb9A3gwiaPsxxY3sbSzLLkIT4zM8uSA8rMzLLUckBJmiDph5K+mW7PkrQhXaLlK5IOTO0HpduDaf3MVrdtZma9qx1HUG8H7i3d/gRwWUS8CHgYWJjaFwIPp/bLUj8zM7OGWgooSdOBM4AvptsCXgPckLrUX7pl5JIuNwAnp/5mZmbP0uoR1N8D7waeSrePAh6JiJF/Sy9fhuXpS7Sk9btTfzMzs2cZ8zRzSa8DdkbE7ZIG2lXQ3l6eBcZ+eZZuXdqlmZzqqa+l25dVye3SLmZWnVb+D+ok4ExJ84CDgecBn6a46vLEdJQ0cnkWeObSLVslTQSOAB6qf9C9vTwLwPlLbhpT4YvnDHfl0i7N5FRPfS3NLkdTldwu7WJm1RnzEF9EvDcipkfETOAc4HsRcS6wFjg7dau/dMvIJV3OTv3bdmFMMzPrLZ34P6j3AO+SNEhxjunK1H4lcFRqfxfPfDCbmZnZs7RlXCkiaqQrKkfE/RSf9Fnf55fAG9qxPTMz632+koSZmWXJAWVmZllyQJmZWZbymNtsZuPOzCb/JrJ4zvCo/0KyeekZnSjJMuMjKDMzy5IDyszMsuSAMjOzLDmgzMwsSw4oMzPLkgPKzMyy5IAyM7MsOaDMzCxLDigzM8uSA8rMzLLkgDIzsyw5oMzMLEsOKDMzy5IDyszMsuSAMjOzLDmgzMwsSw4oMzPLkgPKzMyy5IAyM7MsOaDMzCxLDigzM8uSA8rMzLLkgDIzsyw5oMzMLEsOKDMzy5IDyszMsuSAMsuApM2SNkq6Q9Jtqe1ISaslbUrfJ6d2Sbpc0qCkOyUd393qzTrDAWWWj1dHxHER0Z9uLwHWRMRsYE26DXA6MDt9LQKuqLxSswo4oMzyNR9YkZZXAGeV2q+OwnpgkqSp3SjQrJMmdrsAMwMggO9KCuAfImIZ0BcR29P6B4G+tDwN2FK679bUtr3UhqRFFEdY9PX1UavVGm647xBYPGe4TU+jdXtTT7Pn0m5DQ0OVbWtvjLd6HFBmeXhlRGyT9HxgtaQfl1dGRKTw2msp5JYB9Pf3x8DAQMN+n7nmRi7dmM9bweI5w6PWs/ncgUpqqdVqNNtv3TDe6vEQn1kGImJb+r4T+AZwArBjZOgufd+Zum8DZpTuPj21mfWUMQeUpBmS1kq6R9Ldkt6e2j3zyGwfSDpU0uEjy8ApwF3ASmBB6rYAuDEtrwTOS6+pucDu0lCgWc9o5QhqGFgcEccCc4ELJR2LZx6Z7as+4GZJPwJuAW6KiG8DS4E/k7QJeG26DbAKuB8YBL4A/GX1JZt13pgHntNfbNvT8mOS7qU4UTsfGEjdVgA14D2UZh4B6yVNkjTVf/nZeBcR9wMvbdD+EHByg/YALqygNLOuasuZUUkzgZcBG6ho5hGMfebR/jhrqSr1tXR7xlBus5bMrDotB5Skw4CvAe+IiEclPb2ukzOPAM5fctNYSt6rWUJVyqme+lqqmi3VTG6zlsysOi3N4pN0AEU4XRMRX0/NnnlkZmYta2UWn4ArgXsj4lOlVZ55ZGZmLWtlXOkk4M3ARkl3pLb3Ucw0ul7SQuAB4I1p3SpgHsXMoyeAC1rYtpmZ9bhWZvHdDKjJas88MjOzlvhKEmZmliUHlJmZZckBZWZmWXJAmZlZlhxQZmaWJQeUmZllyQFlZmZZckCZmVmWHFBmZpYlB5SZmWXJAWVmZllyQJmZWZYcUGZmliUHlJmZZckBZWZmWXJAmZlZlhxQZmaWJQeUmZllyQFlZmZZckCZmVmWHFBmZpYlB5SZmWVpYrcLsLzNXHLTmO+7eekZbazEzMYbH0GZmVmWHFBmZpYlB5SZmWXJAWVmZlnyJAnrGE+wMLNW+AjKzMyy5CMoM9vv+Oh8fPARlJmZZckBZWZmWXJAmZlZlnwOyrI0co5h8Zxhzt/H8w0+x2DWG3wEZWZmWao8oCSdJuk+SYOSllS9fbNe4NeRjQeVDvFJmgB8DvgzYCtwq6SVEXFPlXVYb+v1Kch+HbVmX34/6oeY94ffj15S9TmoE4DBiLgfQNJ1wHzALyyzvefXUZf0+h8/uVFEVLcx6WzgtIh4S7r9ZuDEiLio1GcRsCjdfDFwXwdKmQL8ogOPO1Y51ZNTLZBXPS+OiMO7XcTevI5S+96+lnLax5BXPTnVAr1TzzERcfRonbKbxRcRy4BlndyGpNsior+T29gXOdWTUy2QVz2Sbut2Dftib19LOe1jyKuenGqB8VdP1ZMktgEzSrenpzYz23t+Hdm4UHVA3QrMljRL0oHAOcDKimsw29/5dWTjQqVDfBExLOki4DvABGB5RNxdZQ1JR4cQxyCnenKqBfKqJ4taOvA6yuJ5leRUT061wDirp9JJEmZmZnvLV5IwM7MsOaDMzCxLPRtQkmZIWivpHkl3S3p7gz6SdHm6XMydko7vYi0DknZLuiN9fbATtaRtHSzpFkk/SvX8bYM+B0n6Sto3GyTN7GIt50v6eWnfvKUTtdRtc4KkH0r6ZoN1leybKnT7kkmSNkvamH6ut6W2IyWtlrQpfZ/cwe0vl7RT0l2ltobbr+L9okk9l0jaVvr9n1da995Uz32STm1zLQ3ftyrdPxHRk1/AVOD4tHw48P+AY+v6zAO+BQiYC2zoYi0DwDcr2jcCDkvLBwAbgLl1ff4S+HxaPgf4ShdrOR/4bMW/P+8C/qnRz6SqfVPBc5wA/AR4IXAg8KP638sKatgMTKlr+ySwJC0vAT7Rwe2/CjgeuGu07VfxftGknkuAv27Q99j0MzsImJV+lhPaWEvD960q90/PHkFFxPaI+EFafgy4F5hW120+cHUU1gOTJE3tUi2VSc93KN08IH3Vz5aZD6xIyzcAJ0tSl2qplKTpwBnAF5t0qWTfVODpSyZFxK+BkUsmdVt5/64AzurUhiJiHbBrL7ff8feLJvU0Mx+4LiJ+FRE/BQYpfqbtqqXZ+1Zl+6dnA6osDcG8jOKv87JpwJbS7a10ODj2UAvAH6ehrm9JekmH65gg6Q5gJ7A6Iprum4gYBnYDR3WpFoD/loYNbpA0o8H6dvp74N3AU03WV7ZvOqzy3/8GAviupNtVXJoJoC8itqflB4G+imtqtv1u7q+L0u//8tKQZ2X11L1vVbZ/ej6gJB0GfA14R0Q8mnEtP6C4PtVLgc8A/9zJWiLiyYg4juIqBCdI+sNObq/FWv4FmBkRfwSs5pm/3tpO0uuAnRFxe6e2Yb/llRFxPHA6cKGkV5VXRjF21LUj6m5vP7kC+D3gOGA7cGmVG9/T+1an909PB5SkAyh27DUR8fUGXSq7ZMxotUTEoyNDXRGxCjhA0pRO1FK33UeAtcBpdaue3jeSJgJHAA91o5aIeCgifpVufhF4eQfLOAk4U9JmiiGv10j6cl2fyvdNh3T9kkkRsS193wl8g2KIasfI0FD6vrPKmvaw/a7sr4jYkf6Iewr4As8M43W8nibvW5Xtn54NqHRO4Erg3oj4VJNuK4Hz0uyTucDu0qFrpbVI+p2R8xiSTqD42XTkTU/S0ZImpeVDKD5X6Md13VYCC9Ly2cD30l9LlddSN459JsVYeEdExHsjYnpEzKSYAPG9iPiLum6V7JsKdPWSSZIOlXT4yDJwCnAXv71/FwA3VlVT0mz7lbxf1Kv7/f9zin00Us85KmaVzgJmA7e0cbvN3req2z+tzrLI9Qt4JcWh553AHelrHvBW4K2pjyg++O0nwEagv4u1XATcTTErZz3wig7umz8CfpjquQv4YGr/EHBmWj4Y+CrFiddbgBd2sZaPl/bNWuAPKvodGiDN4uvGvqnoOc6jmJ31E+D9FW/7heln+qP0831/aj8KWANsAv4VOLKDNVxLMWz2G4pzJgubbb+K94sm9Xwpbe9OihCYWur//lTPfcDpba6l2ftWZfvHlzoyM7Ms9ewQn5mZ7d8cUGZmliUHlJmZZckBZWZmWXJAmZlZlhxQZmaWJQeUmZll6f8DtrlYH7fINE4AAAAASUVORK5CYII=\n"" + }, + ""metadata"": { + ""tags"": [], + ""needs_background"": ""light"" + } + } + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": { + ""id"": ""QbfMWosQxhXY"", + ""colab_type"": ""text"" + }, + ""source"": [ + ""As we can see in both sets of histograms above, the warfarin doses both have skewed distributions. This reduces the performance of predictive models. Similarly to [Ma et al. 2018](https://journals.plos.org/plosone/article/comments?id=10.1371/journal.pone.0205872), we can take the square root of this feature to produce a normal distribution—which we use for training. In evaluation, we can use warfit-learn's evaluation arguments to square the value and produce legitimate predictions for weekly dosage. "" + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""HN-2K3LQyLlk"", + ""colab_type"": ""code"", + ""colab"": {} + }, + ""source"": [ + ""iwpc['Therapeutic Dose of Warfarin'] = iwpc['Therapeutic Dose of Warfarin'].apply(np.sqrt)\n"", + ""path['takenDoseWeek'] = path['takenDoseWeek'].apply(np.sqrt)"" + ], + ""execution_count"": 0, + ""outputs"": [] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""z4f9WoTIuQzo"", + ""colab_type"": ""code"", + ""colab"": {} + }, + ""source"": [ + """" + ], + ""execution_count"": 0, + ""outputs"": [] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""JcVmbOsbyqoP"", + ""colab_type"": ""code"", + ""outputId"": ""5e1d8092-00ee-41ff-d31e-132fb90365dd"", + ""colab"": { + ""base_uri"": ""https://localhost:8080/"", + ""height"": 286 + } + }, + ""source"": [ + ""iwpc['Therapeutic Dose of Warfarin'].hist()"" + ], + ""execution_count"": 0, + ""outputs"": [ + { + ""output_type"": ""execute_result"", + ""data"": { + ""text/plain"": [ + """" + ] + }, + ""metadata"": { + ""tags"": [] + }, + ""execution_count"": 38 + }, + { + ""output_type"": ""display_data"", + ""data"": { + ""text/plain"": [ + ""
"" + ], + ""image/png"": ""iVBORw0KGgoAAAANSUhEUgAAAYEAAAD8CAYAAACRkhiPAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDIuMi4yLCBodHRwOi8vbWF0cGxvdGxpYi5vcmcvhp/UCwAAF2RJREFUeJzt3X+MXeV95/H3Z02SOkwKZklvHdvdoZXDCpjWwVdAN2p0Z0mIQ1BMqlVqiwU7oZ1EhTRZWWpMWjVRECtrGydbRJd0ElxAUKaIH8ULponLMksj1QmYdT02xGEgTvHU2E2cNR1AtJN+94/7zPYwnh/Xc8/c48vzeUlXc+5znvs83wtn/Jnz496jiMDMzPL0b6ouwMzMquMQMDPLmEPAzCxjDgEzs4w5BMzMMuYQMDPLmEPAzCxjDgEzs4zNGQKSVkh6XNIzkvZL+kxqP0vSTknPpZ9LUrsk3SxpVNJeSRcWxtqQ+j8nacPCvS0zM2uF5vrEsKSlwNKIeFrSO4DdwJXARuBYRGyRtBlYEhGfk3Q58GngcuBi4I8i4mJJZwFPAXUg0jirI+Ins81/9tlnR29vbzvvsWWvvPIKp59+ekfmKkO31QvdV3O31QvdV7PrLd/u3bt/FBHvbKlzRJzUA3gI+ABwgGY4ACwFDqTlPwHWF/ofSOvXA39SaH9Dv5keq1evjk55/PHHOzZXGbqt3ojuq7nb6o3ovppdb/mAp6LFf9NP6pyApF7gPcB3gFpEHE6rXgJqaXkZ8GLhZYdS20ztZmZWkdNa7SipB7gf+GxEvCzp/6+LiJBU2jfRSRoABgBqtRrDw8NlDT2r8fHxjs1Vhm6rF7qv5m6rF7qvZtdbrZZCQNJbaAbA3RHxQGo+ImlpRBxO5w2OpvYxYEXh5ctT2xjQmNI+PN18ETEIDALU6/VoNBrTdSvd8PAwnZqrDN1WL3Rfzd1WL3Rfza63Wq1cHSTgNuDZiPhKYdV2YPIKnw00zxVMtl+TrhK6BDieDht9E7hM0pJ0JdFlqc3MzCrSyp7Ae4GrgRFJe1Lb54EtwL2SrgV+CHwsrdtB88qgUeBV4OMAEXFM0o3Ak6nflyLiWCnvwszM5mXOEIiIbwOaYfWl0/QP4LoZxtoGbDuZAs3MbOH4E8NmZhlzCJiZZcwhYGaWsZY/J2DdoXfzI5XMe3DLhyuZ18za4z0BM7OMOQTMzDLmEDAzy5hDwMwsYw4BM7OMOQTMzDLmEDAzy5hDwMwsYw4BM7OMOQTMzDLmEDAzy5hDwMwsYw4BM7OMOQTMzDLWyo3mt0k6Kmlfoe3PJe1Jj4OT9x6W1CvptcK6rxVes1rSiKRRSTenG9ibmVmFWrmfwO3ALcCdkw0R8RuTy5K2AscL/Z+PiFXTjHMr8FvAd2jejH4N8OjJl2ynolbvY7Cpb4KNJd/zwPcyMJu/OfcEIuIJ4Nh069Jf8x8D7pltDElLgZ+NiF3pRvR3AleefLlmZlYmNf9NnqOT1As8HBEXTGl/H/CViKgX+u0Hvg+8DPx+RPy1pDqwJSLen/r9GvC5iLhihvkGgAGAWq22emhoaD7v7aSNj4/T09PTkbnKMF29I2PHZ+h9aqgthiOvlTtm37Izyh2woNu2Cei+ml1v+fr7+3dP/rs8l3ZvL7meN+4FHAZ+ISJ+LGk18BeSzj/ZQSNiEBgEqNfr0Wg02iyzNcPDw3RqrjJMV2/Zh1rKtqlvgq0j5d7V9OBVjVLHK+q2bQK6r2bXW615/zZKOg34dWD1ZFtEvA68npZ3S3oeeDcwBiwvvHx5ajMzswq1c4no+4HvRcShyQZJ75S0KC3/IrASeCEiDgMvS7oknUe4BniojbnNzKwErVwieg/wN8C5kg5JujatWseJJ4TfB+xNl4zeB3wqIiZPKv828A1gFHgeXxlkZla5OQ8HRcT6Gdo3TtN2P3D/DP2fAi6Ybp2ZmVXDnxg2M8uYQ8DMLGMOATOzjDkEzMwy5hAwM8uYQ8DMLGMOATOzjDkEzMwy5hAwM8uYQ8DMLGMOATOzjDkEzMwy5hAwM8uYQ8DMLGMOATOzjDkEzMwy5hAwM8uYQ8DMLGOt3GN4m6SjkvYV2r4oaUzSnvS4vLDuBkmjkg5I+mChfU1qG5W0ufy3YmZmJ6uVPYHbgTXTtH81Ilalxw4ASefRvAH9+ek1/0PSIkmLgD8GPgScB6xPfc3MrEKt3Gj+CUm9LY63FhiKiNeBH0gaBS5K60Yj4gUASUOp7zMnXbGZmZVGETF3p2YIPBwRF6TnXwQ2Ai8DTwGbIuInkm4BdkXEXanfbcCjaZg1EfGbqf1q4OKIuH6G+QaAAYBarbZ6aGhonm/v5IyPj9PT09ORucowXb0jY8crqqY1tcVw5LVyx+xbdka5AxZ02zYB3Vez6y1ff3//7oiot9J3zj2BGdwK3AhE+rkV+MQ8xzpBRAwCgwD1ej0ajUZZQ89qeHiYTs1Vhunq3bj5kWqKadGmvgm2jsx3s5vewasapY5X1G3bBHRfza63WvP6bYyII5PLkr4OPJyejgErCl2XpzZmaTczs4rM6xJRSUsLTz8KTF45tB1YJ+ltks4BVgLfBZ4EVko6R9JbaZ483j7/ss3MrAxz7glIugdoAGdLOgR8AWhIWkXzcNBB4JMAEbFf0r00T/hOANdFxE/TONcD3wQWAdsiYn/p78bMzE5KK1cHrZ+m+bZZ+t8E3DRN+w5gx0lVZ2ZmC8qfGDYzy5hDwMwsYw4BM7OMOQTMzDLmEDAzy5hDwMwsYw4BM7OMOQTMzDLmEDAzy5hDwMwsYw4BM7OMOQTMzDLmEDAzy5hDwMwsYw4BM7OMOQTMzDLmEDAzy5hDwMwsY3OGgKRtko5K2ldo+0NJ35O0V9KDks5M7b2SXpO0Jz2+VnjNakkjkkYl3SxJC/OWzMysVa3sCdwOrJnSthO4ICJ+Gfg+cENh3fMRsSo9PlVovxX4LWBlekwd08zMOmzOEIiIJ4BjU9q+FRET6ekuYPlsY0haCvxsROyKiADuBK6cX8lmZlYWNf9NnqOT1As8HBEXTLPufwJ/HhF3pX77ae4dvAz8fkT8taQ6sCUi3p9e82vA5yLiihnmGwAGAGq12uqhoaGTf2fzMD4+Tk9PT0fmKsN09Y6MHa+omtbUFsOR18ods2/ZGeUOWNBt2wR0X82ut3z9/f27I6LeSt/T2plI0u8BE8Ddqekw8AsR8WNJq4G/kHT+yY4bEYPAIEC9Xo9Go9FOmS0bHh6mU3OVYbp6N25+pJpiWrSpb4KtI21tdic4eFWj1PGKum2bgO6r2fVWa96/jZI2AlcAl6ZDPETE68DraXm3pOeBdwNjvPGQ0fLUZmZmFZrXJaKS1gC/C3wkIl4ttL9T0qK0/Is0TwC/EBGHgZclXZKuCroGeKjt6s3MrC1z7glIugdoAGdLOgR8gebVQG8DdqYrPXelK4HeB3xJ0j8D/wJ8KiImTyr/Ns0rjRYDj6aHmZlVaM4QiIj10zTfNkPf+4H7Z1j3FHDCiWUzM6uOPzFsZpYxh4CZWcYcAmZmGXMImJllzCFgZpYxh4CZWcYcAmZmGXMImJllzCFgZpYxh4CZWcYcAmZmGXMImJllzCFgZpYxh4CZWcbKvc+fAdDboVs8buqbOOVvJ2lmpzbvCZiZZcwhYGaWMYeAmVnGWgoBSdskHZW0r9B2lqSdkp5LP5ekdkm6WdKopL2SLiy8ZkPq/5ykDeW/HTMzOxmt7gncDqyZ0rYZeCwiVgKPpecAHwJWpscAcCs0Q4PmTeovBi4CvjAZHGZmVo2WQiAingCOTWleC9yRlu8Ariy03xlNu4AzJS0FPgjsjIhjEfETYCcnBouZmXVQO5eI1iLicFp+Cail5WXAi4V+h1LbTO0nkDRAcy+CWq3G8PBwG2W2bnx8vJS5NvVNtF9MC2qLOzdXWRai5oXcPsraJjqp22p2vdUq5XMCERGSooyx0niDwCBAvV6PRqNR1tCzGh4epoy5OnXt/qa+CbaOdNdHPRai5oNXNUodr6isbaKTuq1m11utdq4OOpIO85B+Hk3tY8CKQr/lqW2mdjMzq0g7IbAdmLzCZwPwUKH9mnSV0CXA8XTY6JvAZZKWpBPCl6U2MzOrSEv75ZLuARrA2ZIO0bzKZwtwr6RrgR8CH0vddwCXA6PAq8DHASLimKQbgSdTvy9FxNSTzWZm1kEthUBErJ9h1aXT9A3guhnG2QZsa7k6MzNbUP7EsJlZxhwCZmYZcwiYmWXMIWBmljGHgJlZxhwCZmYZcwiYmWXMIWBmljGHgJlZxhwCZmYZcwiYmWXMIWBmljGHgJlZxhwCZmYZcwiYmWXMIWBmljGHgJlZxuYdApLOlbSn8HhZ0mclfVHSWKH98sJrbpA0KumApA+W8xbMzGy+Wrq95HQi4gCwCkDSImAMeJDmPYW/GhFfLvaXdB6wDjgfeBfwV5LeHRE/nW8NZmbWnrIOB10KPB8RP5ylz1pgKCJej4gf0LwR/UUlzW9mZvNQVgisA+4pPL9e0l5J2yQtSW3LgBcLfQ6lNjMzq4gior0BpLcCfw+cHxFHJNWAHwEB3AgsjYhPSLoF2BURd6XX3QY8GhH3TTPmADAAUKvVVg8NDbVVY6vGx8fp6elpe5yRseMlVDO32mI48lpHpirNQtTct+yMcgcsKGub6KRuq9n1lq+/v393RNRb6TvvcwIFHwKejogjAJM/ASR9HXg4PR0DVhRetzy1nSAiBoFBgHq9Ho1Go4Qy5zY8PEwZc23c/Ej7xbRgU98EW0fK+F/YOQtR88GrGqWOV1TWNtFJ3Vaz661WGYeD1lM4FCRpaWHdR4F9aXk7sE7S2ySdA6wEvlvC/GZmNk9t/Ukm6XTgA8AnC83/TdIqmoeDDk6ui4j9ku4FngEmgOt8ZZCZWbXaCoGIeAX4t1Parp6l/03ATe3MaWZm5fEnhs3MMuYQMDPLmEPAzCxjDgEzs4w5BMzMMuYQMDPLmEPAzCxjDgEzs4w5BMzMMtZd3z5mNo3eBfzCvk19EzN+IeDBLR9esHnNOsV7AmZmGXMImJllzCFgZpYxh4CZWcYcAmZmGXMImJllzCFgZpYxh4CZWcbaDgFJByWNSNoj6anUdpaknZKeSz+XpHZJulnSqKS9ki5sd34zM5u/svYE+iNiVUTU0/PNwGMRsRJ4LD0H+BCwMj0GgFtLmt/MzOZhoQ4HrQXuSMt3AFcW2u+Mpl3AmZKWLlANZmY2hzJCIIBvSdotaSC11SLicFp+Cail5WXAi4XXHkptZmZWAUVEewNIyyJiTNLPATuBTwPbI+LMQp+fRMQSSQ8DWyLi26n9MeBzEfHUlDEHaB4uolarrR4aGmqrxlaNj4/T09PT9jgjY8dLqGZutcVw5LWOTFWabqt5tnr7lp3R2WJaVNZ23Cmut3z9/f27C4fnZ9X2t4hGxFj6eVTSg8BFwBFJSyPicDrcczR1HwNWFF6+PLVNHXMQGASo1+vRaDTaLbMlw8PDlDHXTN86WbZNfRNsHemuL4Lttppnq/fgVY3OFtOisrbjTnG91WrrcJCk0yW9Y3IZuAzYB2wHNqRuG4CH0vJ24Jp0ldAlwPHCYSMzM+uwdv8kqwEPSpoc688i4i8lPQncK+la4IfAx1L/HcDlwCjwKvDxNuc3M7M2tBUCEfEC8CvTtP8YuHSa9gCua2dOMzMrjz8xbGaWMYeAmVnGHAJmZhlzCJiZZcwhYGaWMYeAmVnGHAJmZhlzCJiZZcwhYGaWMYeAmVnGHAJmZhlzCJiZZcwhYGaWMYeAmVnGHAJmZhlzCJiZZcwhYGaWMYeAmVnG5h0CklZIelzSM5L2S/pMav+ipDFJe9Lj8sJrbpA0KumApA+W8QbMzGz+2rnH8ASwKSKelvQOYLeknWndVyPiy8XOks4D1gHnA+8C/krSuyPip23UYGZmbZj3nkBEHI6Ip9PyPwLPAstmeclaYCgiXo+IHwCjwEXznd/MzNpXyjkBSb3Ae4DvpKbrJe2VtE3SktS2DHix8LJDzB4aZma2wBQR7Q0g9QD/G7gpIh6QVAN+BARwI7A0Ij4h6RZgV0TclV53G/BoRNw3zZgDwABArVZbPTQ01FaNrRofH6enp6ftcUbGjpdQzdxqi+HIax2ZqjTdVvNs9fYtO6OzxbSorO24U1xv+fr7+3dHRL2Vvu2cE0DSW4D7gbsj4gGAiDhSWP914OH0dAxYUXj58tR2gogYBAYB6vV6NBqNdsps2fDwMGXMtXHzI+0X04JNfRNsHWnrf2HHdVvNs9V78KpGZ4tpUVnbcae43mq1c3WQgNuAZyPiK4X2pYVuHwX2peXtwDpJb5N0DrAS+O585zczs/a18yfZe4GrgRFJe1Lb54H1klbRPBx0EPgkQETsl3Qv8AzNK4uu85VBZmbVmncIRMS3AU2zascsr7kJuGm+c5qZWbn8iWEzs4w5BMzMMtY9l2mYnWJ6O3QV2FQHt3y4knntzcl7AmZmGXMImJllzCFgZpYxh4CZWcbe1CeGT/bE3aa+iY595YOZ2anAewJmZhlzCJiZZcwhYGaWMYeAmVnGHAJmZhlzCJiZZcwhYGaWMYeAmVnGHAJmZhlzCJiZZazjISBpjaQDkkYlbe70/GZm9q86+t1BkhYBfwx8ADgEPClpe0Q808k6zLrZXN+JtZDfgeUb2rz5dHpP4CJgNCJeiIh/AoaAtR2uwczMkk5/i+gy4MXC80PAxR2uwczmaSFuqdnKnov3QBaOIqJzk0n/CVgTEb+Znl8NXBwR10/pNwAMpKfnAgc6VOLZwI86NFcZuq1e6L6au61e6L6aXW/5/l1EvLOVjp3eExgDVhSeL09tbxARg8Bgp4qaJOmpiKh3et756rZ6oftq7rZ6oftqdr3V6vQ5gSeBlZLOkfRWYB2wvcM1mJlZ0tE9gYiYkHQ98E1gEbAtIvZ3sgYzM/tXHb+9ZETsAHZ0et4WdfwQVJu6rV7ovpq7rV7ovppdb4U6emLYzMxOLf7aCDOzjDkEAEkrJD0u6RlJ+yV9puqaWiFpkaT/I+nhqmuZi6QzJd0n6XuSnpX0q1XXNBdJ/yVtD/sk3SPpZ6quqUjSNklHJe0rtJ0laaek59LPJVXWONUMNf9h2i72SnpQ0plV1lg0Xb2FdZskhaSzq6itLA6BpglgU0ScB1wCXCfpvIprasVngGerLqJFfwT8ZUT8e+BXOMXrlrQM+B2gHhEX0LyQYV21VZ3gdmDNlLbNwGMRsRJ4LD0/ldzOiTXvBC6IiF8Gvg/c0OmiZnE7J9aLpBXAZcDfdbqgsjkEgIg4HBFPp+V/pPkP1LJqq5qdpOXAh4FvVF3LXCSdAbwPuA0gIv4pIv5vtVW15DRgsaTTgLcDf19xPW8QEU8Ax6Y0rwXuSMt3AFd2tKg5TFdzRHwrIibS0100Pz90SpjhvzHAV4HfBbr+pKpDYApJvcB7gO9UW8mc/jvNjfBfqi6kBecA/wD8aTp89Q1Jp1dd1GwiYgz4Ms2/9A4DxyPiW9VW1ZJaRBxOyy8BtSqLmYdPAI9WXcRsJK0FxiLib6uupQwOgQJJPcD9wGcj4uWq65mJpCuAoxGxu+paWnQacCFwa0S8B3iFU+8wxRukY+lraQbYu4DTJf3naqs6OdG89K9r/lKV9Hs0D83eXXUtM5H0duDzwB9UXUtZHAKJpLfQDIC7I+KBquuZw3uBj0g6SPObWP+jpLuqLWlWh4BDETG5d3UfzVA4lb0f+EFE/ENE/DPwAPAfKq6pFUckLQVIP49WXE9LJG0ErgCuilP7uvVfovmHwd+m37/lwNOSfr7SqtrgEAAkiebx6mcj4itV1zOXiLghIpZHRC/Nk5X/KyJO2b9SI+Il4EVJ56amS4FT/R4SfwdcIuntafu4lFP8ZHayHdiQljcAD1VYS0skraF5aPMjEfFq1fXMJiJGIuLnIqI3/f4dAi5M23hXcgg0vRe4muZf1HvS4/Kqi3qT+TRwt6S9wCrgv1Zcz6zSXst9wNPACM3flVPqk6KS7gH+BjhX0iFJ1wJbgA9Ieo7m3syWKmucaoaabwHeAexMv3tfq7TIghnqfVPxJ4bNzDLmPQEzs4w5BMzMMuYQMDPLmEPAzCxjDgEzs4w5BMzMMuYQMDPLmEPAzCxj/w8yZCLqtno10wAAAABJRU5ErkJggg==\n"" + }, + ""metadata"": { + ""tags"": [], + ""needs_background"": ""light"" + } + } + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""vq2GgE0Cyrgo"", + ""colab_type"": ""code"", + ""outputId"": ""8ddc3a42-17a2-4bae-9267-c72a6872e1fb"", + ""colab"": { + ""base_uri"": ""https://localhost:8080/"", + ""height"": 286 + } + }, + ""source"": [ + ""path['takenDoseWeek'].hist()"" + ], + ""execution_count"": 0, + ""outputs"": [ + { + ""output_type"": ""execute_result"", + ""data"": { + ""text/plain"": [ + """" + ] + }, + ""metadata"": { + ""tags"": [] + }, + ""execution_count"": 39 + }, + { + ""output_type"": ""display_data"", + ""data"": { + ""text/plain"": [ + ""
"" + ], + ""image/png"": ""iVBORw0KGgoAAAANSUhEUgAAAYEAAAD8CAYAAACRkhiPAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDIuMi4yLCBodHRwOi8vbWF0cGxvdGxpYi5vcmcvhp/UCwAAFbJJREFUeJzt3X+Q5HV95/Hn6yB6yBjAw8ytu9wtuVq5AjZBdwq587RmD6MrUIKpKw+KU1CT1QrcmautUkiuTisWV1sXf1wscnir7AGlYUKBBAohuuGceKkKKksIyw/RRde4E1yimCWjFsnq+/7o7xy9y8zubHdP9zDf56Oqa/r76e+PV8/O7Gu+P7o7VYUkqZ3+0agDSJJGxxKQpBazBCSpxSwBSWoxS0CSWswSkKQWswQkqcUsAUlqMUtAklrs2FEHOJKTTz651q5d29OyP/rRjzj++OMHG2gJmHOwzDlY5hysYeTcuXPn96vq5YuauaqW9W3Dhg3Vqy996Us9LztM5hwscw6WOQdrGDmB+2uR/8d6OEiSWswSkKQWswQkqcUsAUlqMUtAklrMEpCkFrMEJKnFLAFJajFLQJJabNm/bYReGNZe9fmRbXvP1vNHtm3phc49AUlqMUtAklrMEpCkFrMEJKnFLAFJajFLQJJazBKQpBazBCSpxY5YAkm2J3kqycNdY3+Y5MHmtifJg8342iQ/6Xrsk13LbEiyK8nuJJ9IkqV5SpKkxVrMK4ZvAK4FbpobqKp/P3c/yUeB/V3zP1FVZ82znuuAXwe+AtwNbALuOfrIkqRBOeKeQFV9GXh6vseav+bfBtx8uHUkWQX8fFXd13wI8k3ARUcfV5I0SOn8n3yEmZK1wF1VdeYh468HPlZVE13zPQJ8A3gG+C9V9X+TTABbq+oNzXyvAz5QVRcssL3NwGaA8fHxDVNTU708N2ZnZxkbG+tp2WFaCTl3zeyfd3wY1q8+4aDplfD9XE7MOVjDyLlx48adc/8vH0m/byB3CQfvBTwJ/LOq+kGSDcAfJTnjaFdaVduAbQATExM1OTnZU7jp6Wl6XXaYVkLOy0f5BnKXTh40vRK+n8uJOQdrueXsuQSSHAv8KrBhbqyqngWebe7vTPIE8EpgBljTtfiaZkySNEL9XCL6BuDrVbV3biDJy5Mc09z/RWAd8K2qehJ4Jsk5zXmEdwB39LFtSdIALOYS0ZuBPwdOS7I3ybubhy7m+SeEXw881Fwyeivw3qqaO6n8G8Cngd3AE3hlkCSN3BEPB1XVJQuMXz7P2G3AbQvMfz9w5nyPSZJGw1cMS1KLWQKS1GKWgCS1mCUgSS1mCUhSi1kCktRiloAktZglIEktZglIUotZApLUYpaAJLWYJSBJLWYJSFKLWQKS1GKWgCS1mCUgSS1mCUhSi1kCktRii/mM4e1JnkrycNfYh5LMJHmwuZ3X9djVSXYneTzJm7rGNzVju5NcNfinIkk6WovZE7gB2DTP+Mer6qzmdjdAktPpfAD9Gc0y/zPJMUmOAX4feDNwOnBJM68kaYQW80HzX06ydpHruxCYqqpngW8n2Q2c3Ty2u6q+BZBkqpn30aNOLEkamH7OCVyZ5KHmcNFJzdhq4Ltd8+xtxhYalySNUKrqyDN19gTuqqozm+lx4PtAAR8GVlXVu5JcC9xXVZ9p5rseuKdZzaaq+rVm/O3Aa6rqygW2txnYDDA+Pr5hamqqpyc3OzvL2NhYT8sO00rIuWtm/5DTPGf96hMOml4J38/lxJyDNYycGzdu3FlVE4uZ94iHg+ZTVfvm7if5FHBXMzkDnNI165pmjMOMz7f+bcA2gImJiZqcnOwlJtPT0/S67DCthJyXX/X54YbpsufSyYOmV8L3czkx52Att5w9HQ5Ksqpr8q3A3JVDdwIXJ3lxklOBdcBXga8B65KcmuRFdE4e39l7bEnSIBxxTyDJzcAkcHKSvcAHgckkZ9E5HLQHeA9AVT2S5BY6J3wPAFdU1U+b9VwJfAE4BtheVY8M/NlIko7KYq4OumSe4esPM/81wDXzjN8N3H1U6SRJS8pXDEtSi1kCktRiloAktZglIEktZglIUotZApLUYpaAJLWYJSBJLWYJSFKLWQKS1GKWgCS1mCUgSS1mCUhSi1kCktRiloAktZglIEktZglIUotZApLUYpaAJLXYEUsgyfYkTyV5uGvsd5N8PclDSW5PcmIzvjbJT5I82Nw+2bXMhiS7kuxO8okkWZqnJElarMXsCdwAbDpkbAdwZlX9EvAN4Oqux56oqrOa23u7xq8Dfh1Y19wOXackaciOWAJV9WXg6UPGvlhVB5rJ+4A1h1tHklXAz1fVfVVVwE3ARb1FliQNyiDOCbwLuKdr+tQkf5HkT5O8rhlbDeztmmdvMyZJGqF0/jA/wkzJWuCuqjrzkPHfBiaAX62qSvJiYKyqfpBkA/BHwBnAK4GtVfWGZrnXAR+oqgsW2N5mYDPA+Pj4hqmpqZ6e3OzsLGNjYz0tO0wrIeeumf1DTvOc9atPOGh6JXw/lxNzDtYwcm7cuHFnVU0sZt5je91IksuBC4Bzm0M8VNWzwLPN/Z1JnqBTADMcfMhoTTM2r6raBmwDmJiYqMnJyZ4yTk9P0+uyw7QScl5+1eeHG6bLnksnD5peCd/P5cScg7XccvZ0OCjJJuD9wFuq6sdd4y9Pckxz/xfpnAD+VlU9CTyT5JzmqqB3AHf0nV6S1Jcj7gkkuRmYBE5Oshf4IJ2rgV4M7Giu9LyvuRLo9cDvJPkH4GfAe6tq7qTyb9C50ug4OucQus8jSJJG4IglUFWXzDN8/QLz3gbctsBj9wNnzveYJGk0fMWwJLVYzyeGpeVi7SEnpbesPzCUE9V7tp6/5NuQlpp7ApLUYpaAJLWYJSBJLWYJSFKLWQKS1GKWgCS1mCUgSS1mCUhSi1kCktRiloAktZglIEktZglIUotZApLUYpaAJLWYJSBJLWYJSFKLWQKS1GKLKoEk25M8leThrrGXJdmR5JvN15Oa8ST5RJLdSR5K8uquZS5r5v9mkssG/3QkSUdjsXsCNwCbDhm7Cri3qtYB9zbTAG8G1jW3zcB10CkN4IPAa4CzgQ/OFYckaTQWVQJV9WXg6UOGLwRubO7fCFzUNX5TddwHnJhkFfAmYEdVPV1VPwR28PxikSQNUT/nBMar6snm/veA8eb+auC7XfPtbcYWGpckjcixg1hJVVWSGsS6AJJspnMoifHxcaanp3taz+zsbM/LDtNKyLll/YHhhjmM8eOGk6fff7OV8O++nJizN/2UwL4kq6rqyeZwz1PN+AxwStd8a5qxGWDykPHp+VZcVduAbQATExM1OTk532xHND09Ta/LDtNKyHn5VZ8fbpjD2LL+AB/dNZC/bw5rz6WTfS2/Ev7dlxNz9qafw0F3AnNX+FwG3NE1/o7mKqFzgP3NYaMvAG9MclJzQviNzZgkaUQW9edSkpvp/BV/cpK9dK7y2QrckuTdwHeAtzWz3w2cB+wGfgy8E6Cqnk7yYeBrzXy/U1WHnmyWJA3Rokqgqi5Z4KFz55m3gCsWWM92YPui00mSlpSvGJakFrMEJKnFLAFJajFLQJJabOkvptZQrV3C6/W3rD+wrF4PIKl/7glIUotZApLUYpaAJLWYJSBJLWYJSFKLWQKS1GKWgCS1mCUgSS1mCUhSi1kCktRiloAktZglIEktZglIUotZApLUYj2XQJLTkjzYdXsmyW8m+VCSma7x87qWuTrJ7iSPJ3nTYJ6CJKlXPX+eQFU9DpwFkOQYYAa4HXgn8PGq+kj3/ElOBy4GzgBeAfxJkldW1U97zSBJ6s+gDgedCzxRVd85zDwXAlNV9WxVfRvYDZw9oO1LknqQqup/Jcl24IGqujbJh4DLgWeA+4EtVfXDJNcC91XVZ5plrgfuqapb51nfZmAzwPj4+Iapqamecs3OzjI2NtbTssM0yJy7ZvYPZD3zGT8O9v1kyVY/MMPKuX71CX0t38afz6Vkzuds3LhxZ1VNLGbevksgyYuAvwbOqKp9ScaB7wMFfBhYVVXvOpoS6DYxMVH3339/T9mmp6eZnJzsadlhGmTOpf54yY/uWv6fSDqsnHu2nt/X8m38+VxK5nxOkkWXwCAOB72Zzl7APoCq2ldVP62qnwGf4rlDPjPAKV3LrWnGJEkjMogSuAS4eW4iyaqux94KPNzcvxO4OMmLk5wKrAO+OoDtS5J61Nc+c5LjgV8B3tM1/N+TnEXncNCeuceq6pEktwCPAgeAK7wySJJGq68SqKofAf/kkLG3H2b+a4Br+tmmJGlwfMWwJLWYJSBJLWYJSFKLWQKS1GKWgCS1mCUgSS1mCUhSi1kCktRiloAktZglIEktZglIUotZApLUYpaAJLWYJSBJLWYJSFKLWQKS1GKWgCS1mCUgSS1mCUhSi/VdAkn2JNmV5MEk9zdjL0uyI8k3m68nNeNJ8okku5M8lOTV/W5fktS7Qe0JbKyqs6pqopm+Cri3qtYB9zbTAG8G1jW3zcB1A9q+JKkHS3U46ELgxub+jcBFXeM3Vcd9wIlJVi1RBknSEaSq+ltB8m3gh0AB/6uqtiX526o6sXk8wA+r6sQkdwFbq+rPmsfuBT5QVfcfss7NdPYUGB8f3zA1NdVTttnZWcbGxnp9akMzyJy7ZvYPZD3zGT8O9v1kyVY/MMPKuX71CX0t38afz6Vkzuds3LhxZ9eRmcM6dgDb+zdVNZPkF4AdSb7e/WBVVZKjapqq2gZsA5iYmKjJycmegk1PT9PrssM0yJyXX/X5gaxnPlvWH+CjuwbxI7O0hpVzz6WTfS3fxp/PpWTO3vR9OKiqZpqvTwG3A2cD++YO8zRfn2pmnwFO6Vp8TTMmSRqBvkogyfFJXjp3H3gj8DBwJ3BZM9tlwB3N/TuBdzRXCZ0D7K+qJ/vJIEnqXb/7zOPA7Z3D/hwL/EFV/XGSrwG3JHk38B3gbc38dwPnAbuBHwPv7HP7kqQ+9FUCVfUt4JfnGf8BcO484wVc0c82JUmD4yuGJanFLAFJajFLQJJazBKQpBazBCSpxSwBSWoxS0CSWswSkKQWswQkqcUsAUlqMUtAklps+b85vLRMre3zsxu2rD/Q0+c/7Nl6fl/blbq5JyBJLWYJSFKLWQKS1GKWgCS1mCUgSS1mCUhSi/VcAklOSfKlJI8meSTJ+5rxDyWZSfJgczuva5mrk+xO8niSNw3iCUiSetfP6wQOAFuq6oEkLwV2JtnRPPbxqvpI98xJTgcuBs4AXgH8SZJXVtVP+8ggSepDz3sCVfVkVT3Q3P874DFg9WEWuRCYqqpnq+rbwG7g7F63L0nq30DOCSRZC7wK+EozdGWSh5JsT3JSM7Ya+G7XYns5fGlIkpZYqqq/FSRjwJ8C11TV55KMA98HCvgwsKqq3pXkWuC+qvpMs9z1wD1Vdes869wMbAYYHx/fMDU11VO22dlZxsbGelp2mAaZc9fM/oGsZz7jx8G+nyzZ6gdmpedcv/qEwYc5jDb+Hi2lYeTcuHHjzqqaWMy8fb13UJKfA24DPltVnwOoqn1dj38KuKuZnAFO6Vp8TTP2PFW1DdgGMDExUZOTkz3lm56eptdlh2mQOXt5L5rF2rL+AB/dtfzfbmql59xz6eTgwxxGG3+PltJyy9nP1UEBrgceq6qPdY2v6prtrcDDzf07gYuTvDjJqcA64Ku9bl+S1L9+/lx6LfB2YFeSB5ux3wIuSXIWncNBe4D3AFTVI0luAR6lc2XRFV4ZJEmj1XMJVNWfAZnnobsPs8w1wDW9blOSNFi+YliSWswSkKQWswQkqcUsAUlqMUtAklps+b+i5gXoaD+AvNcPHJekfrknIEktZglIUotZApLUYpaAJLWYJSBJLWYJSFKLrehLRHfN7PfSS0k6DPcEJKnFLAFJajFLQJJazBKQpBazBCSpxSwBSWqxoV8immQT8HvAMcCnq2rrsDNIL2RH+y61/ep+l9s9W88f6ra19Ia6J5DkGOD3gTcDpwOXJDl9mBkkSc8Z9uGgs4HdVfWtqvp7YAq4cMgZJEmNYR8OWg18t2t6L/CaIWeQ1KNhH4qaM8rDUIN+zov9EKlhPedU1VA2BJDk3wGbqurXmum3A6+pqisPmW8zsLmZPA14vMdNngx8v8dlh8mcg2XOwTLnYA0j5z+vqpcvZsZh7wnMAKd0Ta9pxg5SVduAbf1uLMn9VTXR73qWmjkHy5yDZc7BWm45h31O4GvAuiSnJnkRcDFw55AzSJIaQ90TqKoDSa4EvkDnEtHtVfXIMDNIkp4z9NcJVNXdwN1D2lzfh5SGxJyDZc7BMudgLaucQz0xLElaXnzbCElqsRVZAkk2JXk8ye4kV406z3ySnJLkS0keTfJIkveNOtPhJDkmyV8kuWvUWRaS5MQktyb5epLHkvyrUWeaT5L/3PybP5zk5iT/eNSZ5iTZnuSpJA93jb0syY4k32y+njTKjE2m+XL+bvNv/1CS25OcOMqMTabn5ex6bEuSSnLyKLLNWXEl8AJ6a4oDwJaqOh04B7himeac8z7gsVGHOILfA/64qv4l8Mssw7xJVgP/CZioqjPpXCBx8WhTHeQGYNMhY1cB91bVOuDeZnrUbuD5OXcAZ1bVLwHfAK4edqh53MDzc5LkFOCNwF8NO9ChVlwJ8AJ5a4qqerKqHmju/x2d/7BWjzbV/JKsAc4HPj3qLAtJcgLweuB6gKr6+6r629GmWtCxwHFJjgVeAvz1iPP8f1X1ZeDpQ4YvBG5s7t8IXDTUUPOYL2dVfbGqDjST99F5HdJILfD9BPg48H5g5CdlV2IJzPfWFMvyP9c5SdYCrwK+MtokC/ofdH5gfzbqIIdxKvA3wP9uDlt9Osnxow51qKqaAT5C5y/AJ4H9VfXF0aY6ovGqerK5/z1gfJRhFuldwD2jDjGfJBcCM1X1l6POAiuzBF5QkowBtwG/WVXPjDrPoZJcADxVVTtHneUIjgVeDVxXVa8CfsTyOGxxkOZ4+oV0SusVwPFJ/sNoUy1edS4nHPlfr4eT5LfpHG797KizHCrJS4DfAv7rqLPMWYklsKi3plgOkvwcnQL4bFV9btR5FvBa4C1J9tA5tPZvk3xmtJHmtRfYW1Vze1O30imF5eYNwLer6m+q6h+AzwH/esSZjmRfklUAzdenRpxnQUkuBy4ALq3lef37v6DzB8BfNr9Ta4AHkvzTUQVaiSXwgnhriiShc/z6sar62KjzLKSqrq6qNVW1ls738v9U1bL7y7Wqvgd8N8lpzdC5wKMjjLSQvwLOSfKS5mfgXJbhCexD3Alc1ty/DLhjhFkW1Hxg1fuBt1TVj0edZz5VtauqfqGq1ja/U3uBVzc/vyOx4kqgOTE099YUjwG3LNO3pngt8HY6f1k/2NzOG3WoF7j/CHw2yUPAWcB/G3Ge52n2VG4FHgB20fkdXDavIE1yM/DnwGlJ9iZ5N7AV+JUk36SzJzPyTwNcIOe1wEuBHc3v0ydHGpIFcy4rvmJYklpsxe0JSJIWzxKQpBazBCSpxSwBSWoxS0CSWswSkKQWswQkqcUsAUlqsf8HZyEBd0Hlc/YAAAAASUVORK5CYII=\n"" + }, + ""metadata"": { + ""tags"": [], + ""needs_background"": ""light"" + } + } + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": { + ""id"": ""wmOs7_lhhQ1V"", + ""colab_type"": ""text"" + }, + ""source"": [ + ""We can now drop the INR features from both datasets, as they are not features we are training on. We can also drop the dose groups for the IWPC data."" + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""colab_type"": ""code"", + ""id"": ""3U8hCqUMy5bo"", + ""colab"": {} + }, + ""source"": [ + ""iwpc_raw = iwpc.copy()\n"", + ""iwpc.drop(['INR on Reported Therapeutic Dose of Warfarin'], axis='columns', inplace=True)\n"", + ""path.drop(['inr'], axis='columns', inplace=True)"" + ], + ""execution_count"": 0, + ""outputs"": [] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": { + ""id"": ""eZotghiz8ztQ"", + ""colab_type"": ""text"" + }, + ""source"": [ + ""We can now inspect the fields we will be training on"" + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""JniKeCoQ8zAC"", + ""colab_type"": ""code"", + ""outputId"": ""e633951e-c9fa-4673-869f-eda9a2132887"", + ""colab"": { + ""base_uri"": ""https://localhost:8080/"", + ""height"": 255 + } + }, + ""source"": [ + ""iwpc.columns"" + ], + ""execution_count"": 0, + ""outputs"": [ + { + ""output_type"": ""execute_result"", + ""data"": { + ""text/plain"": [ + ""Index(['Height (cm)', 'Weight (kg)', 'Amiodarone (Cordarone)',\n"", + "" 'Carbamazepine (Tegretol)', 'Phenytoin (Dilantin)',\n"", + "" 'Rifampin or Rifampicin', 'Current Smoker',\n"", + "" 'Therapeutic Dose of Warfarin', 'Race (OMB)_Asian',\n"", + "" 'Race (OMB)_Black or African American', 'Race (OMB)_Unknown',\n"", + "" 'Race (OMB)_White', 'Age_10 - 19', 'Age_20 - 29', 'Age_30 - 39',\n"", + "" 'Age_40 - 49', 'Age_50 - 59', 'Age_60 - 69', 'Age_70 - 79',\n"", + "" 'Age_80 - 89', 'Age_90+', 'CYP2C9 consensus_*1/*1',\n"", + "" 'CYP2C9 consensus_*1/*2', 'CYP2C9 consensus_*1/*3',\n"", + "" 'CYP2C9 consensus_*2/*2', 'CYP2C9 consensus_*2/*3',\n"", + "" 'CYP2C9 consensus_*3/*3', 'CYP2C9 consensus_Unknown',\n"", + "" 'Imputed VKORC1_A/A', 'Imputed VKORC1_A/G', 'Imputed VKORC1_G/G',\n"", + "" 'Imputed VKORC1_Unknown'],\n"", + "" dtype='object')"" + ] + }, + ""metadata"": { + ""tags"": [] + }, + ""execution_count"": 41 + } + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""4KzouFmckaZo"", + ""colab_type"": ""code"", + ""colab"": {} + }, + ""source"": [ + ""import warnings\n"", + ""from sklearn.exceptions import ConvergenceWarning\n"", + ""from sklearn.exceptions import ChangedBehaviorWarning\n"", + ""from sklearn.exceptions import DataConversionWarning\n"", + ""warnings.filterwarnings(\""ignore\"", category=ConvergenceWarning)\n"", + ""warnings.filterwarnings(\""ignore\"", category=ChangedBehaviorWarning)\n"", + ""warnings.filterwarnings(\""ignore\"", category=DataConversionWarning)"" + ], + ""execution_count"": 0, + ""outputs"": [] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": { + ""id"": ""QQ0gpUEAwrLG"", + ""colab_type"": ""text"" + }, + ""source"": [ + ""## Evaluation\n"", + ""\n"", + ""We now define a collection of sklearn estimators (or ensembles of sklearn estimators) that have been known to perform well on the IWPC data. We then apply them all to the same IWPC dataset, as well as unseen PathCare dataset, and evaluate performance."" + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""ycx_8S3-dicw"", + ""colab_type"": ""code"", + ""colab"": {} + }, + ""source"": [ + ""from warfit_learn.evaluation import evaluate_estimators"" + ], + ""execution_count"": 0, + ""outputs"": [] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""UwfX26NszWYQ"", + ""colab_type"": ""code"", + ""colab"": {} + }, + ""source"": [ + ""ests = []"" + ], + ""execution_count"": 0, + ""outputs"": [] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": { + ""id"": ""iDf5MnA67-go"", + ""colab_type"": ""text"" + }, + ""source"": [ + ""We'll add a linear regression baseline first."" + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""WA6OPsHw79sk"", + ""colab_type"": ""code"", + ""colab"": {} + }, + ""source"": [ + ""from sklearn.linear_model import LinearRegression\n"", + ""\n"", + ""ests.append(Estimator(\n"", + "" LinearRegression(),\n"", + "" 'LR'))"" + ], + ""execution_count"": 0, + ""outputs"": [] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": { + ""id"": ""oIutIZ1rzrBi"", + ""colab_type"": ""text"" + }, + ""source"": [ + ""[Liu et al. 2015](https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0135784) saw success with off-the-shelf implementations of:\n"", + ""\n"", + ""* Support Vector Regression (SVR)\n"", + ""* Boosted Regression Trees (BRT)\n"", + ""\n"" + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""Edp7LHwVzqae"", + ""colab_type"": ""code"", + ""colab"": {} + }, + ""source"": [ + ""from sklearn.ensemble import GradientBoostingRegressor\n"", + ""from sklearn.svm import LinearSVR\n"", + ""\n"", + ""ests.append(Estimator(\n"", + "" LinearSVR(),\n"", + "" 'SVR'))\n"", + ""\n"", + ""ests.append(Estimator(\n"", + "" GradientBoostingRegressor(),\n"", + "" 'BRT'))"" + ], + ""execution_count"": 0, + ""outputs"": [] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": { + ""id"": ""rUtP2VbV8xOk"", + ""colab_type"": ""text"" + }, + ""source"": [ + ""Ma et al. 2018 found some of the following to be effective as single estimators:\n"", + ""\n"", + ""* Support Vector Regression (SV)\n"", + ""* Multiple Linear Regression (MLR)\n"", + ""* Ridge Regression (RR)\n"", + ""\n"", + ""\n"", + ""Ma et al. 2018 saw their best results with stacked generalization frameworks:\n"", + ""\n"", + ""* SV at Level-1, with GBT, SV, and NN at Level-0\n"", + ""* RR at Level-1, with GBT, RR, and NN at Level-0\n"", + ""\n"", + ""\n"" + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""EtaVdO12rycv"", + ""colab_type"": ""code"", + ""colab"": {} + }, + ""source"": [ + ""from sklearn.linear_model import Ridge\n"", + ""from sklearn.svm import SVR\n"", + ""from sklearn.linear_model import Ridge\n"", + ""from sklearn.ensemble import GradientBoostingRegressor\n"", + ""from sklearn.neural_network import MLPRegressor\n"", + ""from mlxtend.regressor import StackingCVRegressor\n"", + ""\n"", + ""\n"", + ""GBT = GradientBoostingRegressor(learning_rate=0.1, loss=\""lad\"",\n"", + "" max_depth=4,)\n"", + ""RR = Ridge(alpha=1.0)\n"", + ""NN = MLPRegressor(hidden_layer_sizes=(100, ), \n"", + "" activation='logistic', \n"", + "" solver='lbfgs')\n"", + ""SV = SVR(kernel='linear', cache_size=1000)\n"", + ""\n"", + ""\n"", + ""ests.append(Estimator(SV,'SV'))\n"", + ""ests.append(Estimator(RR, 'RR'))\n"", + ""ests.append(Estimator(GBT, 'GBT'))\n"", + ""ests.append(Estimator(NN, 'NN'))\n"", + ""\n"", + ""ests.append(Estimator(\n"", + "" StackingCVRegressor(\n"", + "" regressors=[GBT, SV, NN],\n"", + "" meta_regressor=SV,\n"", + "" cv=5,\n"", + "" ),'Stacked_SV'))\n"", + ""\n"", + ""ests.append(Estimator(\n"", + "" StackingCVRegressor(\n"", + "" regressors=[GBT, RR, NN],\n"", + "" meta_regressor=RR,\n"", + "" cv=5,\n"", + "" ),'Stacked_RR'))"" + ], + ""execution_count"": 0, + ""outputs"": [] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": { + ""id"": ""kN2UaLI_7B1R"", + ""colab_type"": ""text"" + }, + ""source"": [ + ""In this study, supervised learning \""pipelines\"" were generated through Genetic Programming. Here we add a few of the best-performers to our list of estimators."" + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""pXOopd_y7ONr"", + ""colab_type"": ""code"", + ""colab"": {} + }, + ""source"": [ + ""from sklearn.feature_selection import SelectFwe, f_regression, SelectPercentile\n"", + ""from sklearn.preprocessing import StandardScaler, RobustScaler, MaxAbsScaler, \\\n"", + "" MinMaxScaler, FunctionTransformer, Normalizer\n"", + ""from sklearn.linear_model import RidgeCV, ElasticNetCV, LassoLarsCV\n"", + ""from sklearn.tree import DecisionTreeRegressor\n"", + ""from sklearn.svm import LinearSVR\n"", + ""from sklearn.ensemble import GradientBoostingRegressor, ExtraTreesRegressor\n"", + ""from sklearn.decomposition import PCA\n"", + ""from sklearn.pipeline import make_pipeline, make_union\n"", + ""from sklearn.neighbors import KNeighborsRegressor\n"", + ""from sklearn.kernel_approximation import RBFSampler, Nystroem\n"", + ""from tpot.builtins import StackingEstimator, ZeroCount\n"", + ""from copy import copy\n"", + ""\n"", + ""\n"", + ""tpot2 = make_pipeline(\n"", + "" StackingEstimator(\n"", + "" estimator=LinearSVR(\n"", + "" C=1.0,\n"", + "" dual=True,\n"", + "" epsilon=0.01,\n"", + "" loss=\""epsilon_insensitive\"",\n"", + "" tol=0.001,)),\n"", + "" StackingEstimator(\n"", + "" estimator=ElasticNetCV(l1_ratio=0.6000000000000001, tol=0.01, cv=5)),\n"", + "" RobustScaler(),\n"", + "" StackingEstimator(estimator=RidgeCV()),\n"", + "" ExtraTreesRegressor(\n"", + "" bootstrap=True,\n"", + "" max_features=1.0,\n"", + "" min_samples_leaf=20,\n"", + "" min_samples_split=2,\n"", + "" n_estimators=100,)\n"", + "")\n"", + ""\n"", + ""tpot10 = make_pipeline(\n"", + "" StackingEstimator(estimator=ExtraTreesRegressor(\n"", + "" bootstrap=True, max_features=0.05, \n"", + "" min_samples_leaf=18, min_samples_split=10,\n"", + "" n_estimators=100)),\n"", + "" MaxAbsScaler(),\n"", + "" StackingEstimator(estimator=ExtraTreesRegressor(\n"", + "" bootstrap=True, max_features=0.05,\n"", + "" min_samples_leaf=18, min_samples_split=10, n_estimators=100)),\n"", + "" LassoLarsCV(normalize=True, cv=3)\n"", + "")\n"", + ""\n"", + ""tpot17 = make_pipeline(\n"", + "" make_union(\n"", + "" FunctionTransformer(copy, validate=True),\n"", + "" MaxAbsScaler()\n"", + "" ),\n"", + "" StackingEstimator(estimator=RidgeCV()),\n"", + "" ZeroCount(),\n"", + "" GradientBoostingRegressor(alpha=0.9, learning_rate=0.1, loss=\""lad\"",\n"", + "" max_depth=3, max_features=0.9000000000000001,\n"", + "" min_samples_leaf=20, min_samples_split=8,\n"", + "" n_estimators=100, subsample=0.55)\n"", + "")\n"", + ""\n"", + ""\n"", + ""# Trained on PathCare data\n"", + ""tpot_06_12 = make_pipeline(\n"", + "" SelectPercentile(score_func=f_regression, percentile=56),\n"", + "" MinMaxScaler(),\n"", + "" RBFSampler(gamma=0.75),\n"", + "" MinMaxScaler(),\n"", + "" PCA(iterated_power=2, svd_solver=\""randomized\""),\n"", + "" PCA(iterated_power=2, svd_solver=\""randomized\""),\n"", + "" KNeighborsRegressor(n_neighbors=96, p=1, weights=\""distance\"")\n"", + "")\n"", + ""\n"", + ""# Trained on PathCare data\n"", + ""tpot_06_12_02 = make_pipeline(\n"", + "" make_union(\n"", + "" FunctionTransformer(copy),\n"", + "" make_union(\n"", + "" make_pipeline(\n"", + "" Normalizer(norm=\""l1\""),\n"", + "" Nystroem(gamma=0.65, kernel=\""sigmoid\"", n_components=3),\n"", + "" SelectFwe(score_func=f_regression, alpha=0.006)\n"", + "" ),\n"", + "" make_union(\n"", + "" FunctionTransformer(copy),\n"", + "" FunctionTransformer(copy)\n"", + "" )\n"", + "" )\n"", + "" ),\n"", + "" StackingEstimator(estimator=LinearSVR(C=0.0001, dual=True,\n"", + "" epsilon=0.0001,\n"", + "" loss=\""epsilon_insensitive\"",\n"", + "" tol=1e-05)),\n"", + "" MinMaxScaler(),\n"", + "" SelectFwe(score_func=f_regression, alpha=0.047),\n"", + "" Nystroem(gamma=0.9, kernel=\""polynomial\"", n_components=6),\n"", + "" ZeroCount(),\n"", + "" Nystroem(gamma=0.9500000000000001, kernel=\""linear\"", n_components=7),\n"", + "" KNeighborsRegressor(n_neighbors=99, p=1, weights=\""distance\"")\n"", + "")\n"", + ""\n"", + ""# Trained on PathCare data\n"", + ""tpot_06_12_03 = make_pipeline(\n"", + "" StandardScaler(),\n"", + "" SelectFwe(score_func=f_regression, alpha=0.047),\n"", + "" MinMaxScaler(),\n"", + "" Nystroem(gamma=0.5, kernel=\""poly\"", n_components=5),\n"", + "" StackingEstimator(estimator=DecisionTreeRegressor(\n"", + "" max_depth=2, min_samples_leaf=12, min_samples_split=5)),\n"", + "" MaxAbsScaler(),\n"", + "" SelectFwe(score_func=f_regression, alpha=0.007),\n"", + "" KNeighborsRegressor(n_neighbors=100, p=1, weights=\""distance\"")\n"", + "")\n"", + ""\n"", + ""# Trained on PathCare data (sqrted)\n"", + ""tpot_06_13_02 = make_pipeline(\n"", + "" make_union(\n"", + "" FunctionTransformer(copy),\n"", + "" FunctionTransformer(copy)\n"", + "" ),\n"", + "" SelectPercentile(score_func=f_regression, percentile=49),\n"", + "" MinMaxScaler(),\n"", + "" RBFSampler(gamma=0.45),\n"", + "" StackingEstimator(estimator=KNeighborsRegressor(\n"", + "" n_neighbors=43, p=1, weights=\""distance\"")),\n"", + "" MaxAbsScaler(),\n"", + "" KNeighborsRegressor(n_neighbors=97, p=1, weights=\""distance\"")\n"", + "")\n"", + ""\n"", + ""# Trained on PathCare data (sqrted + not-LITE)\n"", + ""tpot_06_13_01 = make_pipeline(\n"", + "" SelectFwe(score_func=f_regression, alpha=0.011),\n"", + "" StackingEstimator(estimator=ElasticNetCV(\n"", + "" l1_ratio=0.7000000000000001, tol=0.01)),\n"", + "" MaxAbsScaler(),\n"", + "" Nystroem(gamma=0.2, kernel=\""linear\"", n_components=3),\n"", + "" StandardScaler(),\n"", + "" KNeighborsRegressor(n_neighbors=100, p=1, weights=\""distance\"")\n"", + "")\n"", + ""\n"", + ""ests.append(Estimator(tpot2, 'TPOT2'))\n"", + ""ests.append(Estimator(tpot10, 'TPOT10'))\n"", + ""ests.append(Estimator(tpot17, 'TPOT17'))\n"", + ""ests.append(Estimator(tpot_06_12, 'TPOT_06_12'))\n"", + ""ests.append(Estimator(tpot_06_12_02, 'TPOT_06_12_02'))\n"", + ""ests.append(Estimator(tpot_06_12_03, 'TPOT_06_12_03'))\n"", + ""ests.append(Estimator(tpot_06_13_01, 'TPOT_06_13_01'))\n"", + ""ests.append(Estimator(tpot_06_13_02, 'TPOT_06_13_02'))"" + ], + ""execution_count"": 0, + ""outputs"": [] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": { + ""id"": ""r3kiUm3f-2g9"", + ""colab_type"": ""text"" + }, + ""source"": [ + ""We now evaluate on both datasets for 100 resamplings"" + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""dho8RRIM-vbo"", + ""colab_type"": ""code"", + ""outputId"": ""0c75e43b-10a8-45b4-cc4b-3dff15416a45"", + ""colab"": { + ""base_uri"": ""https://localhost:8080/"", + ""height"": 1000 + } + }, + ""source"": [ + ""iwpc_results = evaluate_estimators(\n"", + "" ests,\n"", + "" iwpc,\n"", + "" target_column='Therapeutic Dose of Warfarin' #@param {type:\""string\""}\n"", + "" ,scale=True\n"", + "" ,resamples = 100 #@param {type:\""slider\"", min:5, max:200, step:1}\n"", + "" ,test_size=0.2\n"", + "" ,squaring = True #@param [\""True\"", \""False\""] {type:\""raw\""}\n"", + "" ,technique = 'mccv' #@param [\""'bootstrap'\"", \""'mccv'\""] {type:\""raw\""}\n"", + "" ,parallelism = 0.8 #@param {type:\""slider\"", min:0.1, max:1.0, step:0.05}\n"", + "")"" + ], + ""execution_count"": 0, + ""outputs"": [ + { + ""output_type"": ""stream"", + ""text"": [ + ""Using 6 / 8 CPU cores...\n"", + ""\n"", + ""LR...\n"", + "" PW20 MAE R2\n"", + ""------- ------- --------\n"", + ""45.9869 8.58826 0.456811\n"", + ""\n"", + ""SVR...\n"", + "" PW20 MAE R2\n"", + ""------- ------- -------\n"", + ""46.5648 8.58056 0.45762\n"", + ""\n"", + ""BRT...\n"", + "" PW20 MAE R2\n"", + ""------- ------- --------\n"", + ""45.3229 8.74937 0.439686\n"", + ""\n"", + ""SV...\n"", + "" PW20 MAE R2\n"", + ""------- ------ --------\n"", + ""46.4108 8.5779 0.458557\n"", + ""\n"", + ""RR...\n"", + "" PW20 MAE R2\n"", + ""------- ------- --------\n"", + ""45.9556 8.56863 0.460308\n"", + ""\n"", + ""GBT...\n"", + "" PW20 MAE R2\n"", + ""------- ------- --------\n"", + ""46.3098 8.67208 0.433544\n"", + ""\n"", + ""NN...\n"", + "" PW20 MAE R2\n"", + ""------- ------- --------\n"", + ""43.1192 9.35923 0.348166\n"", + ""\n"", + ""Stacked_SV...\n"", + "" PW20 MAE R2\n"", + ""------- ------- --------\n"", + ""46.3177 8.55151 0.462209\n"", + ""\n"", + ""Stacked_RR...\n"", + "" PW20 MAE R2\n"", + ""------- ------- --------\n"", + ""46.0122 8.63365 0.449706\n"", + ""\n"", + ""TPOT2...\n"", + "" PW20 MAE R2\n"", + ""------- ------- --------\n"", + ""46.0836 8.56056 0.462155\n"", + ""\n"", + ""TPOT10...\n"", + "" PW20 MAE R2\n"", + ""------- ------- --------\n"", + ""46.0322 8.61302 0.455258\n"", + ""\n"", + ""TPOT17...\n"", + "" PW20 MAE R2\n"", + ""------- ------- -------\n"", + ""46.0287 8.58789 0.46266\n"", + ""\n"", + ""TPOT_06_12...\n"", + "" PW20 MAE R2\n"", + ""------- ------- --------\n"", + ""43.0853 9.38276 0.353099\n"", + ""\n"", + ""TPOT_06_12_02...\n"", + "" PW20 MAE R2\n"", + ""------- ------- --------\n"", + ""41.4413 9.58791 0.347148\n"", + ""\n"", + ""TPOT_06_12_03...\n"", + "" PW20 MAE R2\n"", + ""------- ------- --------\n"", + ""40.5352 9.96042 0.295653\n"", + ""\n"", + ""TPOT_06_13_01...\n"", + "" PW20 MAE R2\n"", + ""------- ------- --------\n"", + ""41.7485 9.64267 0.339352\n"", + ""\n"", + ""TPOT_06_13_02...\n"", + "" PW20 MAE R2\n"", + ""------- ------- --------\n"", + ""42.8198 9.43025 0.357831\n"", + ""\n"", + ""\n"", + "" PW20 MAE R2\n"", + ""Estimator \n"", + ""BRT 45.322889 8.749370 0.439686\n"", + ""GBT 46.309835 8.672075 0.433544\n"", + ""LR 45.986945 8.588259 0.456811\n"", + ""NN 43.119234 9.359231 0.348166\n"", + ""RR 45.955614 8.568633 0.460308\n"", + ""SV 46.410792 8.577904 0.458557\n"", + ""SVR 46.564839 8.580557 0.457620\n"", + ""Stacked_RR 46.012185 8.633652 0.449706\n"", + ""Stacked_SV 46.317668 8.551510 0.462209\n"", + ""TPOT10 46.032202 8.613020 0.455258\n"", + ""TPOT17 46.028721 8.587887 0.462660\n"", + ""TPOT2 46.083551 8.560564 0.462155\n"", + ""TPOT_06_12 43.085292 9.382765 0.353099\n"", + ""TPOT_06_12_02 41.441253 9.587909 0.347148\n"", + ""TPOT_06_12_03 40.535248 9.960425 0.295653\n"", + ""TPOT_06_13_01 41.748477 9.642666 0.339352\n"", + ""TPOT_06_13_02 42.819843 9.430250 0.357831\n"", + ""\n"" + ], + ""name"": ""stdout"" + } + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""O2jU2b4I_Cmt"", + ""colab_type"": ""code"", + ""outputId"": ""dd2e8cff-40cf-4ae2-e078-d515c0bd7e00"", + ""colab"": { + ""base_uri"": ""https://localhost:8080/"", + ""height"": 1000 + } + }, + ""source"": [ + ""path_results = evaluate_estimators(\n"", + "" ests,\n"", + "" path,\n"", + "" target_column='takenDoseWeek' #@param {type:\""string\""}\n"", + "" ,scale=True\n"", + "" ,resamples = 100 #@param {type:\""slider\"", min:5, max:200, step:1}\n"", + "" ,test_size=0.2\n"", + "" ,squaring = True #@param [\""True\"", \""False\""] {type:\""raw\""}\n"", + "" ,technique = 'mccv' #@param [\""'bootstrap'\"", \""'mccv'\""] {type:\""raw\""}\n"", + "" ,parallelism = 0.8 #@param {type:\""slider\"", min:0.1, max:1.0, step:0.05}\n"", + "")"" + ], + ""execution_count"": 0, + ""outputs"": [ + { + ""output_type"": ""stream"", + ""text"": [ + ""Using 6 / 8 CPU cores...\n"", + ""\n"", + ""LR...\n"", + "" PW20 MAE R2\n"", + ""------- ------- ---------\n"", + ""34.0832 10.9774 0.0984202\n"", + ""\n"", + ""SVR...\n"", + "" PW20 MAE R2\n"", + ""------- ------ --------\n"", + ""34.4649 10.953 0.113318\n"", + ""\n"", + ""BRT...\n"", + "" PW20 MAE R2\n"", + ""------- ------- --------\n"", + ""33.6054 10.9925 0.103892\n"", + ""\n"", + ""SV...\n"", + "" PW20 MAE R2\n"", + ""------- ------- --------\n"", + ""34.4032 10.9317 0.109285\n"", + ""\n"", + ""RR...\n"", + "" PW20 MAE R2\n"", + ""------ ------- ---------\n"", + ""33.987 10.9782 0.0985855\n"", + ""\n"", + ""GBT...\n"", + "" PW20 MAE R2\n"", + ""------ ------- -------\n"", + ""33.347 10.9889 0.10857\n"", + ""\n"", + ""NN...\n"", + "" PW20 MAE R2\n"", + ""------ ------- ---------\n"", + ""33.787 11.0686 0.0985458\n"", + ""\n"", + ""Stacked_SV...\n"", + "" PW20 MAE R2\n"", + ""------ ------- --------\n"", + ""34.453 10.9302 0.115666\n"", + ""\n"", + ""Stacked_RR...\n"", + "" PW20 MAE R2\n"", + ""------- ------- --------\n"", + ""33.8346 10.9491 0.108191\n"", + ""\n"", + ""TPOT2...\n"", + "" PW20 MAE R2\n"", + ""------- ------ -------\n"", + ""33.5319 11.026 0.10202\n"", + ""\n"", + ""TPOT10...\n"", + "" PW20 MAE R2\n"", + ""------- ------- ---------\n"", + ""33.6497 11.0533 0.0994934\n"", + ""\n"", + ""TPOT17...\n"", + "" PW20 MAE R2\n"", + ""------- ------- --------\n"", + ""33.9103 11.0094 0.108598\n"", + ""\n"", + ""TPOT_06_12...\n"", + "" PW20 MAE R2\n"", + ""------- ------- ---------\n"", + ""32.8573 11.2887 0.0591357\n"", + ""\n"", + ""TPOT_06_12_02...\n"", + "" PW20 MAE R2\n"", + ""------- ------- -----------\n"", + ""32.3243 11.6268 -0.00442402\n"", + ""\n"", + ""TPOT_06_12_03...\n"", + "" PW20 MAE R2\n"", + ""------- ------- ---------\n"", + ""32.3697 11.3545 0.0554659\n"", + ""\n"", + ""TPOT_06_13_01...\n"", + "" PW20 MAE R2\n"", + ""------ ------- ---------\n"", + ""32.533 11.3888 0.0485352\n"", + ""\n"", + ""TPOT_06_13_02...\n"", + "" PW20 MAE R2\n"", + ""------- ------- --------\n"", + ""32.6703 11.3338 0.051609\n"", + ""\n"", + ""\n"", + "" PW20 MAE R2\n"", + ""Estimator \n"", + ""BRT 33.605405 10.992519 0.103892\n"", + ""GBT 33.347027 10.988919 0.108570\n"", + ""LR 34.083243 10.977448 0.098420\n"", + ""NN 33.787027 11.068602 0.098546\n"", + ""RR 33.987027 10.978191 0.098586\n"", + ""SV 34.403243 10.931652 0.109285\n"", + ""SVR 34.464865 10.953009 0.113318\n"", + ""Stacked_RR 33.834595 10.949130 0.108191\n"", + ""Stacked_SV 34.452973 10.930239 0.115666\n"", + ""TPOT10 33.649730 11.053257 0.099493\n"", + ""TPOT17 33.910270 11.009393 0.108598\n"", + ""TPOT2 33.531892 11.026032 0.102020\n"", + ""TPOT_06_12 32.857297 11.288727 0.059136\n"", + ""TPOT_06_12_02 32.324324 11.626783 -0.004424\n"", + ""TPOT_06_12_03 32.369730 11.354488 0.055466\n"", + ""TPOT_06_13_01 32.532973 11.388772 0.048535\n"", + ""TPOT_06_13_02 32.670270 11.333786 0.051609\n"", + ""\n"" + ], + ""name"": ""stdout"" + } + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""zOe-jkpYHBBd"", + ""colab_type"": ""code"", + ""colab"": {} + }, + ""source"": [ + ""from warfit_learn.metrics import confidence_interval\n"", + ""from scipy.stats import norm\n"", + ""\n"", + ""def format_summary(df_res):\n"", + "" df_summary = df_res.groupby(['Estimator']).mean()\n"", + "" df_summary.reset_index(inplace=True)\n"", + "" for alg in df_res['Estimator'].unique():\n"", + "" for metric in ['PW20', 'MAE', 'R2']:\n"", + "" lo, hi = confidence_interval(\n"", + "" df_res[metric][df_res['Estimator'] == alg].values,\n"", + "" )\n"", + "" mean = df_res[metric][df_res['Estimator'] == alg].mean()\n"", + "" \n"", + "" for v in [mean, lo, hi]:\n"", + "" if not -10000 < v < 10000:\n"", + "" mean, lo, hi = np.nan, np.nan, np.nan\n"", + "" \n"", + "" conf = f\""{mean:.2f} ({lo:.2f}–{hi:.2f})\""\n"", + "" df_summary[metric][df_summary['Estimator'] == alg] = conf\n"", + "" \n"", + "" return df_summary\n"" + ], + ""execution_count"": 0, + ""outputs"": [] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""gPCn79-uIeoy"", + ""colab_type"": ""code"", + ""colab"": {} + }, + ""source"": [ + ""iwpc_formatted = format_summary(iwpc_results).drop('R2', axis=1)\n"", + ""path_formatted = format_summary(path_results).drop('R2', axis=1)\n"", + ""df_final = pd.concat([\n"", + "" iwpc_formatted,\n"", + "" path_formatted.drop('Estimator', axis=1)\n"", + "" ], axis=1, keys=['IWPC', 'PathCare'])\n"" + ], + ""execution_count"": 0, + ""outputs"": [] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""9stvGLHRku_8"", + ""colab_type"": ""code"", + ""outputId"": ""edf07a8c-24d8-4232-c7e0-8f81a5808f4a"", + ""colab"": { + ""base_uri"": ""https://localhost:8080/"", + ""height"": 607 + } + }, + ""source"": [ + ""df_final"" + ], + ""execution_count"": 0, + ""outputs"": [ + { + ""output_type"": ""execute_result"", + ""data"": { + ""text/plain"": [ + "" IWPC \\\n"", + "" Estimator PW20 MAE \n"", + ""0 BRT 45.32 (45.04–45.60) 8.75 (8.70–8.80) \n"", + ""1 GBT 46.31 (46.02–46.60) 8.67 (8.63–8.71) \n"", + ""2 LR 45.99 (45.75–46.23) 8.59 (8.54–8.64) \n"", + ""3 NN 43.12 (42.86–43.38) 9.36 (9.31–9.40) \n"", + ""4 RR 45.96 (45.70–46.21) 8.57 (8.52–8.61) \n"", + ""5 SV 46.41 (46.16–46.67) 8.58 (8.53–8.62) \n"", + ""6 SVR 46.56 (46.34–46.79) 8.58 (8.53–8.63) \n"", + ""7 Stacked_RR 46.01 (45.74–46.28) 8.63 (8.58–8.68) \n"", + ""8 Stacked_SV 46.32 (46.06–46.57) 8.55 (8.51–8.59) \n"", + ""9 TPOT10 46.03 (45.76–46.30) 8.61 (8.57–8.66) \n"", + ""10 TPOT17 46.03 (45.75–46.30) 8.59 (8.54–8.64) \n"", + ""11 TPOT2 46.08 (45.81–46.35) 8.56 (8.52–8.60) \n"", + ""12 TPOT_06_12 43.09 (42.83–43.34) 9.38 (9.33–9.43) \n"", + ""13 TPOT_06_12_02 41.44 (41.11–41.77) 9.59 (9.53–9.65) \n"", + ""14 TPOT_06_12_03 40.54 (40.15–40.92) 9.96 (9.88–10.04) \n"", + ""15 TPOT_06_13_01 41.75 (41.39–42.11) 9.64 (9.56–9.72) \n"", + ""16 TPOT_06_13_02 42.82 (42.56–43.08) 9.43 (9.38–9.48) \n"", + ""\n"", + "" PathCare \n"", + "" PW20 MAE \n"", + ""0 33.61 (33.32–33.89) 10.99 (10.93–11.05) \n"", + ""1 33.35 (33.03–33.66) 10.99 (10.92–11.06) \n"", + ""2 34.08 (33.76–34.40) 10.98 (10.91–11.04) \n"", + ""3 33.79 (33.48–34.09) 11.07 (11.01–11.13) \n"", + ""4 33.99 (33.67–34.30) 10.98 (10.92–11.04) \n"", + ""5 34.40 (34.16–34.65) 10.93 (10.87–10.99) \n"", + ""6 34.46 (34.16–34.77) 10.95 (10.89–11.01) \n"", + ""7 33.83 (33.55–34.12) 10.95 (10.89–11.01) \n"", + ""8 34.45 (34.16–34.75) 10.93 (10.87–10.99) \n"", + ""9 33.65 (33.37–33.93) 11.05 (11.00–11.11) \n"", + ""10 33.91 (33.65–34.17) 11.01 (10.95–11.07) \n"", + ""11 33.53 (33.28–33.78) 11.03 (10.96–11.09) \n"", + ""12 32.86 (32.58–33.14) 11.29 (11.23–11.35) \n"", + ""13 32.32 (32.03–32.62) 11.63 (11.56–11.69) \n"", + ""14 32.37 (32.08–32.66) 11.35 (11.29–11.42) \n"", + ""15 32.53 (32.25–32.82) 11.39 (11.33–11.45) \n"", + ""16 32.67 (32.37–32.97) 11.33 (11.27–11.40) "" + ], + ""text/html"": [ + ""
\n"", + ""\n"", + ""\n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + ""
IWPCPathCare
EstimatorPW20MAEPW20MAE
0BRT45.32 (45.04–45.60)8.75 (8.70–8.80)33.61 (33.32–33.89)10.99 (10.93–11.05)
1GBT46.31 (46.02–46.60)8.67 (8.63–8.71)33.35 (33.03–33.66)10.99 (10.92–11.06)
2LR45.99 (45.75–46.23)8.59 (8.54–8.64)34.08 (33.76–34.40)10.98 (10.91–11.04)
3NN43.12 (42.86–43.38)9.36 (9.31–9.40)33.79 (33.48–34.09)11.07 (11.01–11.13)
4RR45.96 (45.70–46.21)8.57 (8.52–8.61)33.99 (33.67–34.30)10.98 (10.92–11.04)
5SV46.41 (46.16–46.67)8.58 (8.53–8.62)34.40 (34.16–34.65)10.93 (10.87–10.99)
6SVR46.56 (46.34–46.79)8.58 (8.53–8.63)34.46 (34.16–34.77)10.95 (10.89–11.01)
7Stacked_RR46.01 (45.74–46.28)8.63 (8.58–8.68)33.83 (33.55–34.12)10.95 (10.89–11.01)
8Stacked_SV46.32 (46.06–46.57)8.55 (8.51–8.59)34.45 (34.16–34.75)10.93 (10.87–10.99)
9TPOT1046.03 (45.76–46.30)8.61 (8.57–8.66)33.65 (33.37–33.93)11.05 (11.00–11.11)
10TPOT1746.03 (45.75–46.30)8.59 (8.54–8.64)33.91 (33.65–34.17)11.01 (10.95–11.07)
11TPOT246.08 (45.81–46.35)8.56 (8.52–8.60)33.53 (33.28–33.78)11.03 (10.96–11.09)
12TPOT_06_1243.09 (42.83–43.34)9.38 (9.33–9.43)32.86 (32.58–33.14)11.29 (11.23–11.35)
13TPOT_06_12_0241.44 (41.11–41.77)9.59 (9.53–9.65)32.32 (32.03–32.62)11.63 (11.56–11.69)
14TPOT_06_12_0340.54 (40.15–40.92)9.96 (9.88–10.04)32.37 (32.08–32.66)11.35 (11.29–11.42)
15TPOT_06_13_0141.75 (41.39–42.11)9.64 (9.56–9.72)32.53 (32.25–32.82)11.39 (11.33–11.45)
16TPOT_06_13_0242.82 (42.56–43.08)9.43 (9.38–9.48)32.67 (32.37–32.97)11.33 (11.27–11.40)
\n"", + ""
"" + ] + }, + ""metadata"": { + ""tags"": [] + }, + ""execution_count"": 55 + } + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""mEvN6NWaH3La"", + ""colab_type"": ""code"", + ""outputId"": ""cd081a30-5a02-4ac1-9d99-8d00ea561e48"", + ""colab"": { + ""base_uri"": ""https://localhost:8080/"", + ""height"": 442 + } + }, + ""source"": [ + ""print(df_final.to_latex(index=False, bold_rows=True, na_rep='-'))"" + ], + ""execution_count"": 0, + ""outputs"": [ + { + ""output_type"": ""stream"", + ""text"": [ + ""\\begin{tabular}{lllll}\n"", + ""\\toprule\n"", + "" IWPC & \\multicolumn{2}{l}{PathCare} \\\\\n"", + "" Estimator & PW20 & MAE & PW20 & MAE \\\\\n"", + ""\\midrule\n"", + "" BRT & 45.32 (45.04–45.60) & 8.75 (8.70–8.80) & 33.61 (33.32–33.89) & 10.99 (10.93–11.05) \\\\\n"", + "" GBT & 46.31 (46.02–46.60) & 8.67 (8.63–8.71) & 33.35 (33.03–33.66) & 10.99 (10.92–11.06) \\\\\n"", + "" LR & 45.99 (45.75–46.23) & 8.59 (8.54–8.64) & 34.08 (33.76–34.40) & 10.98 (10.91–11.04) \\\\\n"", + "" NN & 43.12 (42.86–43.38) & 9.36 (9.31–9.40) & 33.79 (33.48–34.09) & 11.07 (11.01–11.13) \\\\\n"", + "" RR & 45.96 (45.70–46.21) & 8.57 (8.52–8.61) & 33.99 (33.67–34.30) & 10.98 (10.92–11.04) \\\\\n"", + "" SV & 46.41 (46.16–46.67) & 8.58 (8.53–8.62) & 34.40 (34.16–34.65) & 10.93 (10.87–10.99) \\\\\n"", + "" SVR & 46.56 (46.34–46.79) & 8.58 (8.53–8.63) & 34.46 (34.16–34.77) & 10.95 (10.89–11.01) \\\\\n"", + "" Stacked\\_RR & 46.01 (45.74–46.28) & 8.63 (8.58–8.68) & 33.83 (33.55–34.12) & 10.95 (10.89–11.01) \\\\\n"", + "" Stacked\\_SV & 46.32 (46.06–46.57) & 8.55 (8.51–8.59) & 34.45 (34.16–34.75) & 10.93 (10.87–10.99) \\\\\n"", + "" TPOT10 & 46.03 (45.76–46.30) & 8.61 (8.57–8.66) & 33.65 (33.37–33.93) & 11.05 (11.00–11.11) \\\\\n"", + "" TPOT17 & 46.03 (45.75–46.30) & 8.59 (8.54–8.64) & 33.91 (33.65–34.17) & 11.01 (10.95–11.07) \\\\\n"", + "" TPOT2 & 46.08 (45.81–46.35) & 8.56 (8.52–8.60) & 33.53 (33.28–33.78) & 11.03 (10.96–11.09) \\\\\n"", + "" TPOT\\_06\\_12 & 43.09 (42.83–43.34) & 9.38 (9.33–9.43) & 32.86 (32.58–33.14) & 11.29 (11.23–11.35) \\\\\n"", + "" TPOT\\_06\\_12\\_02 & 41.44 (41.11–41.77) & 9.59 (9.53–9.65) & 32.32 (32.03–32.62) & 11.63 (11.56–11.69) \\\\\n"", + "" TPOT\\_06\\_12\\_03 & 40.54 (40.15–40.92) & 9.96 (9.88–10.04) & 32.37 (32.08–32.66) & 11.35 (11.29–11.42) \\\\\n"", + "" TPOT\\_06\\_13\\_01 & 41.75 (41.39–42.11) & 9.64 (9.56–9.72) & 32.53 (32.25–32.82) & 11.39 (11.33–11.45) \\\\\n"", + "" TPOT\\_06\\_13\\_02 & 42.82 (42.56–43.08) & 9.43 (9.38–9.48) & 32.67 (32.37–32.97) & 11.33 (11.27–11.40) \\\\\n"", + ""\\bottomrule\n"", + ""\\end{tabular}\n"", + ""\n"" + ], + ""name"": ""stdout"" + } + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": { + ""id"": ""a-Dhm7zWKIX6"", + ""colab_type"": ""text"" + }, + ""source"": [ + ""Export the raw results for later analysis."" + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""AxGp3DzlHuYA"", + ""colab_type"": ""code"", + ""colab"": {} + }, + ""source"": [ + ""iwpc_results.to_csv('iwpc_results.csv')\n"", + ""path_results.to_csv('path_results.csv')"" + ], + ""execution_count"": 0, + ""outputs"": [] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": { + ""id"": ""g2l23BW_trnk"", + ""colab_type"": ""text"" + }, + ""source"": [ + ""**Copyright (C) 2019 Gianluca Truda**\n"", + ""\n"", + ""This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see https://www.gnu.org/licenses/.\n"", + ""\n"" + ] + } + ] +}","Unknown" +"Pharmacogenetics","gianlucatruda/warfit-learn","docs/warfit_learn_tutorial.ipynb",".ipynb","27206","645","{ + ""nbformat"": 4, + ""nbformat_minor"": 0, + ""metadata"": { + ""colab"": { + ""name"": ""warfit_learn_tutorial.ipynb"", + ""version"": ""0.3.2"", + ""provenance"": [], + ""collapsed_sections"": [] + }, + ""kernelspec"": { + ""name"": ""python3"", + ""display_name"": ""Python 3"" + } + }, + ""cells"": [ + { + ""cell_type"": ""markdown"", + ""metadata"": { + ""id"": ""_cDz6dPgvWut"", + ""colab_type"": ""text"" + }, + ""source"": [ + ""# Getting started with [warfit-learn](https://github.com/gianlucatruda/warfit-learn)\n"", + ""\n"", + ""A toolkit for reproducible research in warfarin dose estimation."" + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""dwe3Zxg9vJPs"", + ""colab_type"": ""code"", + ""colab"": {} + }, + ""source"": [ + ""%matplotlib inline"" + ], + ""execution_count"": 0, + ""outputs"": [] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": { + ""id"": ""xmazkiQ1v3Mw"", + ""colab_type"": ""text"" + }, + ""source"": [ + ""First we will install warfit-learn from PyPi using `pip`, then import a few basic supporting libaries."" + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""3u6VU8rnqfC6"", + ""colab_type"": ""code"", + ""colab"": {} + }, + ""source"": [ + ""pip install warfit-learn"" + ], + ""execution_count"": 0, + ""outputs"": [] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""zzJ08lZyrQEJ"", + ""colab_type"": ""code"", + ""colab"": {} + }, + ""source"": [ + ""import sklearn\n"", + ""import pandas as pd\n"", + ""import numpy as np"" + ], + ""execution_count"": 0, + ""outputs"": [] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": { + ""id"": ""uojkZ3GzvnK2"", + ""colab_type"": ""text"" + }, + ""source"": [ + ""## Loading and preparing the IWPC dataset"" + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""un9K3n_brl3o"", + ""colab_type"": ""code"", + ""colab"": { + ""base_uri"": ""https://localhost:8080/"", + ""height"": 34 + }, + ""outputId"": ""94c6e6e2-0ad0-417d-c874-8336a353c275"" + }, + ""source"": [ + ""from warfit_learn import datasets, preprocessing\n"", + ""\n"", + ""raw_iwpc = datasets.load_iwpc()\n"", + ""data = preprocessing.prepare_iwpc(raw_iwpc)\n"", + ""data.shape"" + ], + ""execution_count"": 26, + ""outputs"": [ + { + ""output_type"": ""execute_result"", + ""data"": { + ""text/plain"": [ + ""(5741, 32)"" + ] + }, + ""metadata"": { + ""tags"": [] + }, + ""execution_count"": 26 + } + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": { + ""id"": ""pvJP86ZGwLGE"", + ""colab_type"": ""text"" + }, + ""source"": [ + ""## Creating models"" + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": { + ""id"": ""ew3ixoO9wU-x"", + ""colab_type"": ""text"" + }, + ""source"": [ + ""First, we import two regression estimators from [scikit-learn](https://github.com/gianlucatruda/warfit-learn), which is fully supported by warfit-learn.\n"", + ""\n"", + ""We then instantiate a list of these estimators and give them descriptive labels of our choosing:\n"", + ""\n"", + ""1. `LR` for linear regression\n"", + ""2. `SVR` for support vector regression\n"", + ""\n"", + ""We can configure the estimators however we like and warfit-learn will execute them as instantiated. For instance, we may want to specify that the SVR estimator should use an `epsilon_insensitive` loss function.\n"", + ""\n"" + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""vgL7EFSKrbaW"", + ""colab_type"": ""code"", + ""colab"": {} + }, + ""source"": [ + ""from sklearn.linear_model import LinearRegression\n"", + ""from sklearn.svm import LinearSVR\n"", + ""\n"", + ""from warfit_learn.estimators import Estimator\n"", + ""\n"", + ""my_models = [\n"", + "" Estimator(LinearRegression(), 'LR'),\n"", + "" Estimator(LinearSVR(loss='epsilon_insensitive'), 'SVR'),\n"", + ""]"" + ], + ""execution_count"": 0, + ""outputs"": [] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": { + ""id"": ""C_KD9XOmxuAP"", + ""colab_type"": ""text"" + }, + ""source"": [ + ""# Evaluating models"" + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": { + ""id"": ""qaVkxZgTx3VD"", + ""colab_type"": ""text"" + }, + ""source"": [ + ""We will now evaluate our collection of models (estimators) using the `evaluate_esimators()` function from `warfit_learn.evaluation`. \n"", + ""\n"", + ""We provide it with the list of our estimators and the cleaned and formatted IWPC dataset from earlier. \n"", + ""\n"", + ""By specifying `parallelism=0.5` we are using 50% of our CPU capacity. We have set `resamples=10` so that each of our estimators is evaluated 10 times. "" + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""xQNojrrXs19Z"", + ""colab_type"": ""code"", + ""colab"": { + ""base_uri"": ""https://localhost:8080/"", + ""height"": 323 + }, + ""outputId"": ""2f3aedc1-8854-4e2f-8f94-681208b0e079"" + }, + ""source"": [ + ""from warfit_learn.evaluation import evaluate_estimators\n"", + ""\n"", + ""results = evaluate_estimators(\n"", + "" my_models,\n"", + "" data,\n"", + "" parallelism=0.5,\n"", + "" resamples=10,\n"", + "")"" + ], + ""execution_count"": 33, + ""outputs"": [ + { + ""output_type"": ""stream"", + ""text"": [ + ""Using 1 / 2 CPU cores...\n"", + ""\n"", + ""LR...\n"", + "" PW20 MAE R2\n"", + ""------- ------- --------\n"", + ""45.4047 8.70827 0.436191\n"", + ""\n"", + ""SVR...\n"", + "" PW20 MAE R2\n"", + ""------- ------- --------\n"", + ""45.6049 8.76897 0.448331\n"", + ""\n"", + ""\n"", + "" PW20 MAE R2\n"", + ""Estimator \n"", + ""LR 45.404700 8.708271 0.436191\n"", + ""SVR 45.604874 8.768972 0.448331\n"", + ""\n"" + ], + ""name"": ""stdout"" + } + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": { + ""id"": ""S7g4lnXiynfa"", + ""colab_type"": ""text"" + }, + ""source"": [ + ""As expected we now have a dataframe of results for each of the 20 trials we ran.\n"", + ""\n"", + ""Note that the data is shuffled and split into training- and validation- sets for each trial, so we get different results each time. "" + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""-vcCxC4eyjEs"", + ""colab_type"": ""code"", + ""colab"": { + ""base_uri"": ""https://localhost:8080/"", + ""height"": 669 + }, + ""outputId"": ""a752b964-c1c4-4f24-f0e3-c114f0fd2198"" + }, + ""source"": [ + ""results"" + ], + ""execution_count"": 34, + ""outputs"": [ + { + ""output_type"": ""execute_result"", + ""data"": { + ""text/html"": [ + ""
\n"", + ""\n"", + ""\n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + ""
EstimatorPW20MAER2
0LR46.0400358.6083960.433467
1LR44.6475208.7463290.435183
2LR44.4734558.6872670.401249
3LR48.3899048.4266580.496300
4LR44.3864238.5598720.466298
5LR46.0400358.8702540.389101
6LR43.9512629.0195820.437109
7LR45.1697138.5876340.439606
8LR46.3011318.8441590.463413
9LR44.6475208.7325550.400180
0SVR46.4751968.9459140.440443
1SVR44.7345528.7597660.426778
2SVR45.3437778.4418720.455176
3SVR44.5604879.0991850.409133
4SVR44.9956488.8197330.458935
5SVR45.2567458.6252100.448845
6SVR45.5178428.9242600.472657
7SVR43.6031338.8886180.441083
8SVR47.1714538.4921680.495334
9SVR48.3899048.6929950.434922
\n"", + ""
"" + ], + ""text/plain"": [ + "" Estimator PW20 MAE R2\n"", + ""0 LR 46.040035 8.608396 0.433467\n"", + ""1 LR 44.647520 8.746329 0.435183\n"", + ""2 LR 44.473455 8.687267 0.401249\n"", + ""3 LR 48.389904 8.426658 0.496300\n"", + ""4 LR 44.386423 8.559872 0.466298\n"", + ""5 LR 46.040035 8.870254 0.389101\n"", + ""6 LR 43.951262 9.019582 0.437109\n"", + ""7 LR 45.169713 8.587634 0.439606\n"", + ""8 LR 46.301131 8.844159 0.463413\n"", + ""9 LR 44.647520 8.732555 0.400180\n"", + ""0 SVR 46.475196 8.945914 0.440443\n"", + ""1 SVR 44.734552 8.759766 0.426778\n"", + ""2 SVR 45.343777 8.441872 0.455176\n"", + ""3 SVR 44.560487 9.099185 0.409133\n"", + ""4 SVR 44.995648 8.819733 0.458935\n"", + ""5 SVR 45.256745 8.625210 0.448845\n"", + ""6 SVR 45.517842 8.924260 0.472657\n"", + ""7 SVR 43.603133 8.888618 0.441083\n"", + ""8 SVR 47.171453 8.492168 0.495334\n"", + ""9 SVR 48.389904 8.692995 0.434922"" + ] + }, + ""metadata"": { + ""tags"": [] + }, + ""execution_count"": 34 + } + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": { + ""id"": ""dfP28hc2y5wj"", + ""colab_type"": ""text"" + }, + ""source"": [ + ""We can summarise these results easily by grouping them on the `Estimator` column and specifying that we want them to be aggregated by `mean` value. We could also specify the `max` or `min` value, or apply any other function of our choice."" + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""V5l5sdFhtbj0"", + ""colab_type"": ""code"", + ""colab"": { + ""base_uri"": ""https://localhost:8080/"", + ""height"": 142 + }, + ""outputId"": ""6f0480cb-5abe-4467-c1a8-ce268914c070"" + }, + ""source"": [ + ""summary = results.groupby('Estimator').apply(np.mean)\n"", + ""summary"" + ], + ""execution_count"": 35, + ""outputs"": [ + { + ""output_type"": ""execute_result"", + ""data"": { + ""text/html"": [ + ""
\n"", + ""\n"", + ""\n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + "" \n"", + ""
PW20MAER2
Estimator
LR45.4047008.7082710.436191
SVR45.6048748.7689720.448331
\n"", + ""
"" + ], + ""text/plain"": [ + "" PW20 MAE R2\n"", + ""Estimator \n"", + ""LR 45.404700 8.708271 0.436191\n"", + ""SVR 45.604874 8.768972 0.448331"" + ] + }, + ""metadata"": { + ""tags"": [] + }, + ""execution_count"": 35 + } + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": { + ""id"": ""0EwdQ4YizQQQ"", + ""colab_type"": ""text"" + }, + ""source"": [ + ""Becuase of warfit-learn's seamless integration with the Python scientific stack, Pandas, and scikit-learn, producing plots of our results is easy."" + ] + }, + { + ""cell_type"": ""code"", + ""metadata"": { + ""id"": ""eEJLjrhHucdC"", + ""colab_type"": ""code"", + ""colab"": { + ""base_uri"": ""https://localhost:8080/"", + ""height"": 310 + }, + ""outputId"": ""1504268d-b95f-4de5-de89-be12c3a09680"" + }, + ""source"": [ + ""summary[['PW20', 'MAE']].plot(kind='bar')"" + ], + ""execution_count"": 36, + ""outputs"": [ + { + ""output_type"": ""execute_result"", + ""data"": { + ""text/plain"": [ + """" + ] + }, + ""metadata"": { + ""tags"": [] + }, + ""execution_count"": 36 + }, + { + ""output_type"": ""display_data"", + ""data"": { + ""image/png"": ""iVBORw0KGgoAAAANSUhEUgAAAXQAAAEUCAYAAAA7l80JAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDMuMC4zLCBo\ndHRwOi8vbWF0cGxvdGxpYi5vcmcvnQurowAAEoVJREFUeJzt3X+Q13WdwPHnq108UHQ3AR1lyUXz\nrjywVUkUrEGr09NSHJ1cQmXMG0fvbkzUSTubkZqrdDqj5uZmPH80YCUemZNGaedpZnerEniGKNdp\niraIChuENBKSr/tjv3ALgrvsfne/u+99PmaY3c/n+/l+vy+Y9cnHN5/v9xuZiSRp6HtPrQeQJFWH\nQZekQhh0SSqEQZekQhh0SSqEQZekQhh0SSqEQZekQhh0SSpE/UA+2dixY7O5uXkgn1KShrzly5ev\nz8xx3R03oEFvbm5m2bJlA/mUkjTkRcRLPTnOJRdJKoRBl6RCGHRJKsSArqFL0rt56623aG9vZ8uW\nLbUepSZGjhxJU1MTI0aM6NX9DbqkQaO9vZ3999+f5uZmIqLW4wyozKSjo4P29nYmTpzYq8dwyUXS\noLFlyxbGjBkz7GIOEBGMGTOmT/93YtAlDSrDMebb9fX3btAlqRCuoUsatJqv/XFVH2/1DWd0e0xd\nXR2TJ09m27ZtfPCDH2ThwoVcd911HHbYYVxxxRUAnHrqqUyYMIHbbrsNgKuuuorx48dzyimncNll\nl7Fp0ybq6uq47rrrOO+88wB48cUXaW1tpaOjg+OOO47vfOc77LPPPlX9/Rl0aQipduD6S0/COViN\nGjWKp556CoDZs2dz8803M336dBYvXswVV1zB22+/zfr169m0adOO+7S1tTF//nz23Xdf7rjjDo48\n8kheeeUVjjvuOE499VQaGxu55pprmDt3Lq2trVx66aXcfvvtXHbZZVWd3aDvhv/RSAL4yEc+wooV\nK2htbWXu3LkAPPPMM0yaNIm1a9eyYcMG9t13X1atWsWxxx670xn3oYceykEHHcS6detoaGjg4Ycf\n5s477wRgzpw5zJs3z6BL0kDYtm0b999/P6eddhqHHnoo9fX1vPzyy7S1tXHiiSeyZs0aHnvsMRoa\nGpg8efI7lk+WLl3K1q1bOeKII+jo6KCxsZH6+s7kNjU1sWbNmqrPbNAlqYs333yTlpYWoPMM/eKL\nLwZg2rRptLW10dbWxpVXXsmaNWtoa2ujoaGB6dOn7/QYa9eu5YILLmDhwoW85z0Dd+2JQZekLrqu\noXc1ffp02traePrpp5k0aRITJkzgpptu4oADDuCiiy7acdymTZs444wz+MpXvsIJJ5wAwJgxY9i4\ncSPbtm2jvr6e9vZ2xo8fX/XZvWxRknpg2rRpLFmyhAMPPJC6ujoOPPBANm7cyGOPPca0adMA2Lp1\nK2effTYXXngh55577o77RgQnn3wyd999NwALFy7krLPOqvqMnqFLGrQG0z/8T548mfXr1/OZz3xm\np32bN29m7NixACxevJhHH32Ujo4OFixYAMCCBQtoaWnhxhtvpLW1lS9+8Yscc8wxO5ZyqsmgS1IX\nmzdv3u3+urq6nS5VBHZEe7vzzz+f888/f7f3P/zww1m6dGlVZtwTl1wkqRAGXZIKYdAlqRAGXZIK\nYdAlqRAGXZIK4WWLkgaveQ1Vfrzfd3tIRDB79my++93vAp3v6XLIIYcwdepUlixZsuO4mTNn8uqr\nr/L444///8PPm8ett97KuHHjdux75JFHaGxsrOJvYs8MuiR1sd9++7Fy5UrefPNNRo0axYMPPviO\nl+lv3LiR5cuXM3r0aF544QUOP/zwHbfNnTuXq6++eqDHBlxykaR3OP300/nxjzvfRnvRokXMmjVr\np9vvuecePvWpT9Ha2spdd91VixF3y6BL0i62h3rLli2sWLGCqVOn7nT79sjPmjWLRYsW7XTb/Pnz\naWlpoaWlhZNPPnkgx3bJRZJ2dfTRR7N69WoWLVrE6aefvtNtr732Gs899xwnnXQSEcGIESNYuXIl\nkyZNAlxykaRB58wzz+Tqq69+x3LL4sWL2bBhAxMnTqS5uXlH+AcDgy5Ju/HZz36W66+/nsmTJ++0\nf9GiRTzwwAOsXr2a1atXs3z58kGzju6Si6TBqweXGfaXpqYmLr/88p32rV69mpdeemnHB1cATJw4\nkYaGBp544gmgcw19+yWPAD/84Q9pbm4ekJl7HPSIqAOWAWsy85MRMRG4CxgDLAcuyMyt/TOmJA2M\n3b197owZM5gxYwbAbj8L9MknnwRg6tSpzJs3rz/He1d7s+TyOWBVl+0bgfmZ+X5gA1D9d2uXJPVY\nj4IeEU3AGcBtle0ATgHurhyyEJjZHwNKknqmp2fo3wQ+D7xd2R4DbMzMbZXtdmC3n3gaEZdExLKI\nWLZu3bo+DSupfJlZ6xFqpq+/926DHhGfBF7PzOW9eYLMvCUzp2TmlK7vbyBJuxo5ciQdHR3DMuqZ\nSUdHByNHjuz1Y/TkH0WnA2dGxOnASOAA4FtAY0TUV87Sm4B3/kuBJO2FpqYm2tvbGa7/Nz9y5Eia\nmpp6ff9ug56ZXwC+ABARM4CrM3N2RHwfOJfOK13mAPf2egpJAkaMGMHEiRNrPcaQ1ZcXFl0DXBkR\nz9O5pn57dUaSJPXGXr2wKDMfAR6pfP8CcHz1R5Ik9YYv/ZekQhh0SSqEQZekQhh0SSqEQZekQhh0\nSSqEQZekQhh0SSqEQZekQhh0SSqEQZekQhh0SSqEQZekQhh0SSqEQZekQhh0SSqEQZekQhh0SSqE\nQZekQhh0SSqEQZekQhh0SSqEQZekQhh0SSqEQZekQhh0SSqEQZekQhh0SSqEQZekQhh0SSqEQZek\nQhh0SSqEQZekQhh0SSqEQZekQhh0SSpEt0GPiJERsTQifhURz0TElyr7J0bEExHxfET8W0Ts0//j\nSpL2pCdn6H8ETsnMDwEtwGkRcQJwIzA/M98PbAAu7r8xJUnd6Tbo2WlzZXNE5VcCpwB3V/YvBGb2\ny4SSpB7p0Rp6RNRFxFPA68CDwG+AjZm5rXJIOzC+f0aUJPVEj4KemX/KzBagCTge+EBPnyAiLomI\nZRGxbN26db0cU5LUnb26yiUzNwI/A04EGiOivnJTE7BmD/e5JTOnZOaUcePG9WlYSdKe9eQql3ER\n0Vj5fhTwCWAVnWE/t3LYHODe/hpSktS9+u4P4RBgYUTU0fkXwOLMXBIRzwJ3RcQ/Av8N3N6Pc0qS\nutFt0DNzBXDMbva/QOd6uiRpEPCVopJUCIMuSYUw6JJUCIMuSYUw6JJUCIMuSYUw6JJUCIMuSYUw\n6JJUCIMuSYUw6JJUCIMuSYUw6JJUCIMuSYUw6JJUCIMuSYUw6JJUCIMuSYUw6JJUCIMuSYUw6JJU\nCIMuSYUw6JJUCIMuSYUw6JJUCIMuSYUw6JJUCIMuSYUw6JJUCIMuSYUw6JJUCIMuSYUw6JJUCIMu\nSYUw6JJUCIMuSYXoNugRMSEifhYRz0bEMxHxucr+AyPiwYh4rvL1vf0/riRpT3pyhr4NuCozjwJO\nAP4uIo4CrgUeyswjgYcq25KkGuk26Jm5NjOfrHz/BrAKGA+cBSysHLYQmNlfQ0qSurdXa+gR0Qwc\nAzwBHJyZays3vQocXNXJJEl7pcdBj4jRwA+AKzJzU9fbMjOB3MP9LomIZRGxbN26dX0aVpK0Zz0K\nekSMoDPm38vMeyq7X4uIQyq3HwK8vrv7ZuYtmTklM6eMGzeuGjNLknajJ1e5BHA7sCozv9HlpvuA\nOZXv5wD3Vn88SVJP1ffgmOnABcDTEfFUZd8/ADcAiyPiYuAl4NP9M6IkqSe6DXpm/icQe7j5Y9Ud\nR5LUW75SVJIKYdAlqRAGXZIKYdAlqRAGXZIKYdAlqRAGXZIKYdAlqRAGXZIKYdAlqRAGXZIKYdAl\nqRAGXZIKYdAlqRAGXZIKYdAlqRAGXZIKYdAlqRAGXZIKYdAlqRAGXZIKYdAlqRAGXZIKYdAlqRAG\nXZIKYdAlqRAGXZIKYdAlqRAGXZIKYdAlqRAGXZIKYdAlqRAGXZIKYdAlqRAGXZIKYdAlqRAGXZIK\n0W3QI+LbEfF6RKzssu/AiHgwIp6rfH1v/44pSepOT87QFwCn7bLvWuChzDwSeKiyLUmqoW6DnpmP\nAr/bZfdZwMLK9wuBmVWeS5K0l3q7hn5wZq6tfP8qcPCeDoyISyJiWUQsW7duXS+fTpLUnT7/o2hm\nJpDvcvstmTklM6eMGzeur08nSdqD3gb9tYg4BKDy9fXqjSRJ6o3eBv0+YE7l+znAvdUZR5LUWz25\nbHER8BjwFxHRHhEXAzcAn4iI54CPV7YlSTVU390BmTlrDzd9rMqzSJL6oNugaxCb11DrCbo37/e1\nnkC1MBR+NqG4n09f+i9JhTDoklQIgy5JhTDoklQIgy5JhTDoklQIgy5JhTDoklQIgy5JhTDoklQI\ngy5JhTDoklQIgy5JhTDoklQIgy5JhTDoklQIgy5JhTDoklQIgy5JhTDoklQIgy5JhTDoklQIgy5J\nhTDoklQIgy5JhTDoklQIgy5JhTDoklQIgy5JhTDoklQIgy5JhTDoklQIgy5JhTDoklQIgy5JhehT\n0CPitIj4dUQ8HxHXVmsoSdLe63XQI6IO+Bfgr4GjgFkRcVS1BpMk7Z2+nKEfDzyfmS9k5lbgLuCs\n6owlSdpbfQn6eOC3XbbbK/skSTVQ399PEBGXAJdUNjdHxK/7+zmHi4CxwPpaz/GuvhS1nkA1MCR+\nNmEo/Xwe1pOD+hL0NcCELttNlX07ycxbgFv68Dzag4hYlplTaj2HtCt/NmujL0suvwSOjIiJEbEP\n0ArcV52xJEl7q9dn6Jm5LSL+HvgpUAd8OzOfqdpkkqS90qc19Mz8CfCTKs2ivedSlgYrfzZrIDKz\n1jNIkqrAl/5LUiEMuiQVwqBLUiEMuqR+ERGNEXFdrecYTgz6EBIRdRExtsv2PhFxSUSsquVcGt4i\nYkJE3BIRSyLibyJiv4i4Cfhf4KBazzecGPQhIiJagd8BKyLi5xHxV8ALdL7b5eyaDqfh7g7gFeCf\ngb8ElgGHAkdn5udqOdhw42WLQ0RErARmZubzEXEs8Bhwbmb+qMajaZiLiF9l5oe6bLcD78vMt2s4\n1rDU72/OparZmpnPA2TmkxHxnDHXYBER7wW2v9NVB9AQEQGQmb+r2WDDjEEfOg6KiCu7bDd23c7M\nb9RgJgmgAXhyl33btxM4fGDHGb5cchkiIuL6d7k5M/PLAzaMpEHJoBcgIq7IzG/Weg4NTxHxLPA9\nYFFmvlDreYYzr3Ipw5XdHyL1m1nAaODBiFgaEXMj4tBaDzUceYZegIj4bWZO6P5IqX9FxAnAecA5\nwG+AOzPz1tpONXwY9AJExMuZ+b5azyFtFxEzgPnAUZn5ZzUeZ9jwKpchIiLeoPOKgXfcBIwa4HGk\nd4iID9O5/HIO8CLwr8D3azrUMGPQh4jM3L/WM0i7ExFfBT4NbADuAqZnZnttpxqeDLqkvtoCXJSZ\nvwCIiAsj4hzgJWCeLywaOF7lIqmvZgLPAETER4Eb6Hx/l9/jR9ENKM/QJfXVe7qchZ8H3JKZPwB+\nEBFP1XCuYcczdEl9VR8R208OPwY83PW2GswzbPmHLamvFgE/j4j1wJvA9rX099O57KIB4nXokvqs\n8oKiQ4B/z8w/VPb9OTA6M3d94y71E4MuSYVwDV2SCmHQJakQBl1DRkT8KSKe6vLr2nc5dmZEHNVl\n+8sR8fEqzNAYEX/b18eR+oNr6BoyImJzZo7u4bELgCWZeXeVZ2iuPO6kvbhPfWZuq+Yc0u54hq4h\nLyJuiIhnI2JFRPxTREwDzgS+XjmTPyIiFkTEuZXjV0fE1yq3LYuIYyPipxHxm4i4tHLM6Ih4KCKe\njIinI+KsytPdABxRue/Xo9PXI2Jl5bjzKvefERG/iIj7gGdr8MeiYcjr0DWUjNrllYdfA/4DOBv4\nQGZmRDRm5sZKSHecoVc+r7irlzOzJSLmAwuA6cBIYCVwM53vT3J2Zm6KiLHA45XHvBaYlJktlcc9\nB2gBPgSMBX4ZEY9WnuPYyrEvVvePQdo9g66h5M3tId2u8grFLcDtEbEEWNLDx7qv8vVpOq+VfgN4\nIyL+GBGNwB+Ar1bem+RtYDxw8G4e5yQ6P3rtT8BrEfFz4MPAJmCpMddAcslFQ1plbfp44G7gk8AD\nPbzrHytf3+7y/fbtemA2MA44rvKXyGt0nsHvjT/s5fFSnxh0DWkRMRpoyMyfAHPpXPoAeAPoy3vI\nNwCvZ+ZbEXEycNgeHvcXwHkRURcR44CPAkv78LxSr7nkoqFk1zX0B4BvAfdGxEg6P71p+wdm3wXc\nGhGXA+f24rm+B/woIp4GlgH/A5CZHRHxXxGxErgf+DxwIvArOj9R6vOZ+WpEfKAXzyn1iZctSlIh\nXHKRpEIYdEkqhEGXpEIYdEkqhEGXpEIYdEkqhEGXpEIYdEkqxP8BpweUtIfUF5gAAAAASUVORK5C\nYII=\n"", + ""text/plain"": [ + ""
"" + ] + }, + ""metadata"": { + ""tags"": [] + } + } + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": { + ""id"": ""452zYvipvqIg"", + ""colab_type"": ""text"" + }, + ""source"": [ + ""**Copyright (C) 2019 Gianluca Truda**\n"", + ""\n"", + ""This program is free software: you can redistribute it and/or modify\n"", + ""it under the terms of the GNU General Public License as published by\n"", + ""the Free Software Foundation, either version 3 of the License, or\n"", + ""(at your option) any later version.\n"", + ""\n"", + ""This program is distributed in the hope that it will be useful,\n"", + ""but WITHOUT ANY WARRANTY; without even the implied warranty of\n"", + ""MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"", + ""GNU General Public License for more details.\n"", + ""\n"", + ""You should have received a copy of the GNU General Public License\n"", + ""along with this program. If not, see ."" + ] + } + ] +}","Unknown" +"Pharmacogenetics","OHDSI/StudyProtocols","deploy.sh",".sh","838","34","#!/bin/bash +set -o errexit -o nounset +addToDrat(){ + PKG_REPO=$PWD + + cd ..; mkdir drat; cd drat + + ## Set up Repo parameters + git init + git config user.name ""Marc A. Suchard"" + git config user.email ""msuchard@ucla.edu"" + git config --global push.default simple + + ## Get drat repo + git remote add upstream ""https://$GH_TOKEN@github.com/OHDSI/drat.git"" + git fetch upstream 2>err.txt + git checkout gh-pages + + ## Link to local R packages + echo 'R_LIBS=~/Rlib' > .Renviron + + Rscript -e ""drat::insertPackage('$PKG_REPO/$PKG_TARBALL_KA', \ + repodir = '.', \ + commit='Travis update: $PKG_TARBALL_KA build $TRAVIS_BUILD_NUMBER')"" + git push + + Rscript -e ""drat::insertPackage('$PKG_REPO/$PKG_TARBALL_AR', \ + repodir = '.', \ + commit='Travis update: $PKG_TARBALL_AR build $TRAVIS_BUILD_NUMBER')"" + git push + +} +addToDrat +","Shell" +"Pharmacogenetics","OHDSI/StudyProtocols","Study 1 - Treatment Pathways/R Version/HelperFunctions.R",".R","1869","38","renderStudySpecificSql <- function(studyName, minCellCount, cdmSchema, resultsSchema, sourceName, dbms){ + if (studyName == ""HTN""){ + TxList <- '21600381,21601461,21601560,21601664,21601744,21601782' + DxList <- '316866' + ExcludeDxList <- '444094' + } else if (studyName == ""T2DM""){ + TxList <- '21600712,21500148' + DxList <- '201820' + ExcludeDxList <- '444094,35506621' + } else if (studyName == ""Depression""){ + TxList <- '21604686, 21500526' + DxList <- '440383' + ExcludeDxList <- '444094,432876,435783' + } + + inputFile <- ""TxPath parameterized.sql"" + outputFile <- paste(""TxPath autoTranslate "", dbms,"" "", studyName, "".sql"",sep="""") + + parameterizedSql <- readSql(inputFile) + renderedSql <- renderSql(parameterizedSql, cdmSchema=cdmSchema, resultsSchema=resultsSchema, studyName = studyName, sourceName=sourceName, txlist=TxList, dxlist=DxList, excludedxlist=ExcludeDxList, smallcellcount = minCellCount)$sql + translatedSql <- translateSql(renderedSql, sourceDialect = ""sql server"", targetDialect = dbms)$sql + writeSql(translatedSql,outputFile) + writeLines(paste(""Created file '"",outputFile,""'"",sep="""")) + return(outputFile) + } + + extractAndWriteToFile <- function(connection, tableName, resultsSchema, sourceName, studyName, dbms){ + parameterizedSql <- ""SELECT * FROM @resultsSchema.dbo.@studyName_@sourceName_@tableName"" + renderedSql <- renderSql(parameterizedSql, cdmSchema=cdmSchema, resultsSchema=resultsSchema, studyName=studyName, sourceName=sourceName, tableName=tableName)$sql + translatedSql <- translateSql(renderedSql, sourceDialect = ""sql server"", targetDialect = dbms)$sql + data <- querySql(connection, translatedSql) + outputFile <- paste(studyName,""_"",sourceName,""_"",tableName,"".csv"",sep='') + write.csv(data,file=outputFile) + writeLines(paste(""Created file '"",outputFile,""'"",sep="""")) + } + + + ","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Study 1 - Treatment Pathways/R Version/MainAnalysis.R",".R","3584","86","########################################################### +# R script for creating SQL files (and sending the SQL # +# commands to the server) for the treatment pattern # +# studies for these diseases: # +# - Hypertension (HTN) # +# - Type 2 Diabetes (T2DM) # +# - Depression # +# # +# Requires: R and Java 1.6 or higher # +########################################################### + +# Install necessary packages if needed +install.packages(""devtools"") +library(devtools) +install_github(""ohdsi/SqlRender"") +install_github(""ohdsi/DatabaseConnector"") + +# Load libraries +library(SqlRender) +library(DatabaseConnector) + +########################################################### +# Parameters: Please change these to the correct values: # +########################################################### + +folder = ""F:/Documents/OHDSI/StudyProtocols/Study 1 - Treatment Pathways/R Version"" # Folder containing the R and SQL files, use forward slashes +minCellCount = 1 # the smallest allowable cell count, 1 means all counts are allowed +cdmSchema = ""cdm_schema"" +resultsSchema = ""resuts_schema"" +sourceName = ""source_name"" +dbms = ""sql server"" # Should be ""sql server"", ""oracle"", ""postgresql"" or ""redshift"" + +# If you want to use R to run the SQL and extract the results tables, please create a connectionDetails +# object. See ?createConnectionDetails for details on how to configure for your DBMS. + + + +user <- NULL +pw <- NULL +server <- ""server_name"" +port <- NULL + +connectionDetails <- createConnectionDetails(dbms=dbms, + server=server, + user=user, + password=pw, + schema=cdmSchema, + port=port) + + +########################################################### +# End of parameters. Make no changes after this # +########################################################### + +setwd(folder) + +source(""HelperFunctions.R"") + +# Create the parameterized SQL files: +htnSqlFile <- renderStudySpecificSql(""HTN"",minCellCount,cdmSchema,resultsSchema,sourceName,dbms) +t2dmSqlFile <- renderStudySpecificSql(""T2DM"",minCellCount,cdmSchema,resultsSchema,sourceName,dbms) +depSqlFile <- renderStudySpecificSql(""Depression"",minCellCount,cdmSchema,resultsSchema,sourceName,dbms) + +# Execute the SQL: +conn <- connect(connectionDetails) +executeSql(conn,readSql(htnSqlFile)) +executeSql(conn,readSql(t2dmSqlFile)) +executeSql(conn,readSql(depSqlFile)) + +# Extract tables to CSV files: +extractAndWriteToFile(conn, ""summary"", resultsSchema, sourceName, ""HTN"", dbms) +extractAndWriteToFile(conn, ""person_cnt"", resultsSchema, sourceName, ""HTN"", dbms) +extractAndWriteToFile(conn, ""seq_cnt"", resultsSchema, sourceName, ""HTN"", dbms) + +extractAndWriteToFile(conn, ""summary"", resultsSchema, sourceName, ""T2DM"", dbms) +extractAndWriteToFile(conn, ""person_cnt"", resultsSchema, sourceName, ""T2DM"", dbms) +extractAndWriteToFile(conn, ""seq_cnt"", resultsSchema, sourceName, ""T2DM"", dbms) + +extractAndWriteToFile(conn, ""summary"", resultsSchema, sourceName, ""Depression"", dbms) +extractAndWriteToFile(conn, ""person_cnt"", resultsSchema, sourceName, ""Depression"", dbms) +extractAndWriteToFile(conn, ""seq_cnt"", resultsSchema, sourceName, ""Depression"", dbms) + +dbDisconnect(conn) + + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","ExistingStrokeRiskExternalValidation/R/main.R",".R","2684","62","main <- function(connectionDetails, + databaseName, + cdmDatabaseSchema, + cohortDatabaseSchema, + outputLocation, + cohortTable, + removeLessThanN = F, + N=10, + getTable1=F){ + + + names <- createCohorts(connectionDetails, + cdmDatabaseSchema=cdmDatabaseSchema, + cohortDatabaseSchema=cohortDatabaseSchema, + cohortTable=cohortTable) + + + for(i in 2:5){ + if(getTable1){ + table1 <- getTable1(connectionDetails, + cdmDatabaseSchema=cdmDatabaseSchema, + cohortDatabaseSchema=cohortDatabaseSchema, + cohortTable= cohortTable, + targetId=names$cohortId[1], + outcomeId=names$cohortId[i]) + } else{ + table1 <- NULL + } + + + results <- applyExistingstrokeModels(connectionDetails=connectionDetails, + cdmDatabaseSchema=cdmDatabaseSchema, + cohortDatabaseSchema=cohortDatabaseSchema, + cohortTable= cohortTable, + targetId=names$cohortId[1], + outcomeId=names$cohortId[i]) + for(n in 1:length(results)){ + resultLoc <- PatientLevelPrediction::standardOutput(result = results[[n]], + table1=table1, + outputLocation = outputLocation , + studyName = names(results)[n], + databaseName = databaseName, + cohortName = names$cohortName[1], + outcomeName = names$cohortName[i] ) + + PatientLevelPrediction::packageResults(mainFolder=resultLoc, + includeROCplot= T, + includeCalibrationPlot = T, + includePRPlot = T, + includeTable1 = T, + includeThresholdSummary =T, + includeDemographicSummary = T, + includeCalibrationSummary = T, + includePredictionDistribution =T, + includeCovariateSummary = F, + removeLessThanN = removeLessThanN, + N = N) + } + } + return(T) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","ExistingStrokeRiskExternalValidation/R/helpers.R",".R","15805","328","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of Existing Stroke Risk External Valiation study +# +# 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. + + +#' Create and summarise the target and outcome cohorts +#' +#' @details +#' This will create the risk prediciton cohorts and then count the table sizes +#' +#' @param connectioDetails The connections details for connecting to the CDM +#' @param cdmDatabaseSchema The schema holding the CDM data +#' @param cohortDatabaseSchema The schema holding the cohort table +#' @param cohortTable The name of the cohort table +#' @param targetId The cohort definition id of the target population +#' @param outcomeIds The cohort definition ids of the outcomes +#' +#' @return +#' A summary of the cohort counts +#' +#' @export +createCohorts <- function(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable, + targetId, + outcomeIds){ + + cohortDetails <- NULL + if(!missing(outcomeIds)){ + if(length(unique(outcomeIds))!=4){ + stop('Need to enter four outcome ids') + } + if(length(targetId)!=1){ + stop('Need to enter one target id') + } + + cohortDetails <- data.frame(cohortName=c('Females newly diagnosed with atrial fibrilation aged 65 to 95', + 'Stroke definition 1 Broad stroke Inpatient', + 'Stroke definition 2 Broad stroke', + 'Stroke definition 3 Haemorrhagic stroke', + 'Stroke definition 4 Ischaemic stroke'), + cohortId = c(targetId, outcomeIds)) + + } + + connection <- DatabaseConnector::connect(connectionDetails) + + #checking whether cohort table exists and creating if not.. + # create the cohort table if it doesnt exist + existTab <- toupper(cohortTable)%in%toupper(DatabaseConnector::getTableNames(connection, cohortDatabaseSchema)) + if(!existTab){ + sql <- SqlRender::loadRenderTranslateSql(""createTable.sql"", + packageName = ""ExistingStrokeRiskExternalValidation"", + dbms = attr(connection, ""dbms""), + target_database_schema = cohortDatabaseSchema, + target_cohort_table = cohortTable) + DatabaseConnector::executeSql(connection, sql) + } + + if(is.null(cohortDetails)){ + result <- PatientLevelPrediction::createCohort(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + package = 'ExistingStrokeRiskExternalValidation') + } else { + result <- PatientLevelPrediction::createCohort(cohortDetails = cohortDetails, + connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + package = 'ExistingStrokeRiskExternalValidation') + } + + print(result) + + return(result) +} + +#' Creates the target population and outcome summary characteristics +#' +#' @details +#' This will create the patient characteristic table +#' +#' @param connectioDetails The connections details for connecting to the CDM +#' @param cdmDatabaseSchema The schema holding the CDM data +#' @param cohortDatabaseSchema The schema holding the cohort table +#' @param cohortTable The name of the cohort table +#' @param targetId The cohort definition id of the target population +#' @param outcomeId The cohort definition id of the outcome +#' @param tempCohortTable The name of the temporary table used to hold the cohort +#' +#' @return +#' A dataframe with the characteristics +#' +#' @export +getTable1 <- function(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable, + targetId, + outcomeId, + tempCohortTable='#temp_cohort'){ + + covariateSettings <- FeatureExtraction::createCovariateSettings(useDemographicsGender = T) + + plpData <- PatientLevelPrediction::getPlpData(connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortId = targetId, outcomeIds = outcomeId, + cohortDatabaseSchema = cohortDatabaseSchema, + outcomeDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + outcomeTable = cohortTable, + covariateSettings=covariateSettings) + + population <- PatientLevelPrediction::createStudyPopulation(plpData = plpData, + outcomeId = outcomeId, + binary = T, + includeAllOutcomes = T, + requireTimeAtRisk = T, + minTimeAtRisk = 364, + riskWindowStart = 1, + riskWindowEnd = 365, + removeSubjectsWithPriorOutcome = T) + + table1 <- PatientLevelPrediction::getPlpTable(cdmDatabaseSchema = cdmDatabaseSchema, + longTermStartDays = -9999, + population=population, + connectionDetails=connectionDetails, + cohortTable=tempCohortTable) + + return(table1) +} + +#' Applies the five existing stroke prediction models +#' +#' @details +#' This will run and evaluate five existing stroke risk prediction models +#' +#' @param connectioDetails The connections details for connecting to the CDM +#' @param cdmDatabaseSchema The schema holding the CDM data +#' @param cohortDatabaseSchema The schema holding the cohort table +#' @param cohortTable The name of the cohort table +#' @param targetId The cohort definition id of the target population +#' @param outcomeId The cohort definition id of the outcome +#' +#' @return +#' A list with the performance and plots +#' +#' @export +applyExistingstrokeModels <- function(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable, + targetId, + outcomeId){ + + writeLines('Implementing Astria stroke risk model...') + astria <- PredictionComparison::atriaStrokeModel(connectionDetails, cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + outcomeDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + outcomeTable = cohortTable, + cohortId = targetId, outcomeId = outcomeId, + removePriorOutcome=T, + riskWindowStart = 1, + riskWindowEnd = 365, + requireTimeAtRisk = T, + minTimeAtRisk = 364, includeAllOutcomes = T) + + writeLines('Implementing Qstroke stroke risk model...') + qstroke <- PredictionComparison::qstrokeModel(connectionDetails, cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + outcomeDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + outcomeTable = cohortTable, + cohortId = targetId, outcomeId = outcomeId, + removePriorOutcome=T, + riskWindowStart = 1, + riskWindowEnd = 365, + requireTimeAtRisk = T, + minTimeAtRisk = 364, includeAllOutcomes = T) + + writeLines('Implementing Framington stroke risk model...') + framington <- PredictionComparison::framinghamModel(connectionDetails, cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + outcomeDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + outcomeTable = cohortTable, + cohortId = targetId, outcomeId = outcomeId, + removePriorOutcome=T, + riskWindowStart = 1, + riskWindowEnd = 365, + requireTimeAtRisk = T, + minTimeAtRisk = 364, includeAllOutcomes = T) + + writeLines('Implementing chads2 stroke risk model...') + chads2 <- PredictionComparison::chads2Model(connectionDetails, cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + outcomeDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + outcomeTable = cohortTable, + cohortId = targetId, outcomeId = outcomeId, + removePriorOutcome=T, + riskWindowStart = 1, + riskWindowEnd = 365, + requireTimeAtRisk = T, + minTimeAtRisk = 364, includeAllOutcomes = T) + + writeLines('Implementing chads2vas stroke risk model...') + chads2vas <- PredictionComparison::chads2vasModel(connectionDetails, cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + outcomeDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + outcomeTable = cohortTable, + cohortId = targetId, outcomeId = outcomeId, + removePriorOutcome=T, + riskWindowStart = 1, + riskWindowEnd = 365, + requireTimeAtRisk = T, + minTimeAtRisk = 364, includeAllOutcomes = T) + +# format the results... [TODO...] + results <- list(astria=astria, + qstroke=qstroke, + framington=framington, + chads2=chads2, + chads2vas=chads2vas) + + return(results) +} + +#' Submit the study results to the study coordinating center +#' +#' @details +#' This will upload the file \code{StudyResults.zip} to the study coordinating center using Amazon S3. +#' This requires an active internet connection. +#' +#' @param exportFolder The path to the folder containing the \code{StudyResults.zip} file. +#' @param dbName Database name used in the zipName +#' @param key The key string as provided by the study coordinator +#' @param secret The secret string as provided by the study coordinator +#' +#' @return +#' TRUE if the upload was successful. +#' +#' @export +submitResults <- function(exportFolder,dbName, key, secret) { + zipName <- file.path(exportFolder, paste0(dbName,""-StudyResults.zip"")) + folderName <- file.path(exportFolder, paste0(dbName,""-StudyResults"")) + if (!dir.exists(folderName)) { + dir.create(folderName, recursive = T) + } + + # move all zipped files into folder + files <- list.files(exportFolder) + files <- files[grep('.zip', files)] + for(file in files){ + file.copy(file.path(exportFolder,file), file.path(folderName), recursive=TRUE) + } + + if(file.exists(file.path(exportFolder, 'predictionDetails.txt'))){ + file.copy(file.path(exportFolder, 'predictionDetails.txt'), file.path(folderName), recursive=TRUE) + } + + # compress complete folder + OhdsiSharing::compressFolder(folderName, zipName) + # delete temp folder + unlink(folderName, recursive = T) + + if (!file.exists(zipName)) { + stop(paste(""Cannot find file"", zipName)) + } + PatientLevelPrediction::submitResults(exportFolder = file.path(exportFolder, paste0(dbName,""-StudyResults.zip"")), + key = key, secret = secret) + + +} + + +#' View the coefficients of the models in this study and the concept ids used to define them +#' +#' +#' @details +#' This will print the models and return a data.frame with the models +#' +#' +#' @return +#' A data.frame of the models +#' +#' @export +viewModels <- function(){ + conceptSets <- system.file(""extdata"", ""existingStrokeModels_concepts.csv"", package = ""PredictionComparison"") + conceptSets <- read.csv(conceptSets) + + existingBleedModels <- system.file(""extdata"", ""existingStrokeModels_modelTable.csv"", package = ""PredictionComparison"") + existingBleedModels <- read.csv(existingBleedModels) + + modelNames <- system.file(""extdata"", ""existingStrokeModels_models.csv"", package = ""PredictionComparison"") + modelNames <- read.csv(modelNames) + + + models <- merge(modelNames,merge(existingBleedModels[,c('modelId','modelCovariateId','Name','Time','coefficientValue')], + conceptSets[,c('modelCovariateId','ConceptId','AnalysisId')])) + models <- models[,c('name','Name','Time','coefficientValue','ConceptId','AnalysisId')] + colnames(models)[1:2] <- c('Model','Covariate') + models[,1] <- as.character(models[,1]) + models[,2] <- as.character(models[,2]) + models <- rbind(models, c('Chads2','FeatureExtraction covariate','',0,0,0)) + models <- rbind(models, c('Chads2Vas','FeatureExtraction covariate','',0,0,0)) + + View(models) + return(models) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","ExistingStrokeRiskExternalValidation/extras/main.R",".R","1846","41","#file to run study +options(fftempdir = 'T:/fftemp') +dbms <- ""pdw"" +user <- NULL +pw <- NULL +server <- Sys.getenv('server') +port <- Sys.getenv('port') +connectionDetails <- DatabaseConnector::createConnectionDetails(dbms = dbms, + server = server, + user = user, + password = pw, + port = port) +createCohorts(connectionDetails, + cdmDatabaseschema=Sys.getenv('mdcr_cdm'), + cohortDatabaseschema='cohortDatabase.dbo', + cohortTable='stroke_cohort', + targetId=1, + outcomeId=2) + +table1 <- getTable1(connectionDetails, + cdmDatabaseschema=Sys.getenv('mdcr_cdm'), + cohortDatabaseschema='cohortDatabase.dbo', + cohortTable='stroke_cohort', + targetId=1, + outcomeId=2) + +results <- applyExistingstrokeModels(connectionDetails=connectionDetails, + cdmDatabaseSchema=Sys.getenv('mdcr_cdm'), + cohortDatabaseSchema=""cohortDatabase.dbo"", + cohortTable=""stroke_cohort"", + targetId=1, + outcomeId=2) + +packageResults(results, table1=NULL, saveFolder=file.path(getwd(), + 'testing_stroke_study'), + dbName='mdcr') + +submitResults(exportFolder=file.path(getwd(), + 'testing_stroke_study'), + dbName='mdcr', key, secret) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","TxPathways12mo/R/HelperFunctions.R",".R","2178","47"," +#' @importFrom SqlRender renderSql +#' @keywords internal +renderStudySpecificSql <- function(studyName, minCellCount, cdmSchema, resultsSchema, sourceName, dbms){ + if (studyName == ""HTN12mo""){ + TxList <- '21600381,21601461,21601560,21601664,21601744,21601782' + DxList <- '316866' + ExcludeDxList <- '444094' + } else if (studyName == ""DM12mo""){ + TxList <- '21600712,21500148' + DxList <- '201820' + ExcludeDxList <- '444094,35506621' + } else if (studyName == ""Dep12mo""){ + TxList <- '21604686, 21500526' + DxList <- '440383' + ExcludeDxList <- '444094,432876,435783' + } + + inputFile <- system.file(paste(""sql/"",""sql_server"",sep=""""), + ""TxPath_parameterized.sql"", + package=""OhdsiStudy2"") + # inputFile <- ""TxPath_parameterized.sql"" + + outputFile <- paste(""TxPath_autoTranslate_"", dbms,""_"", studyName, "".sql"",sep="""") + + parameterizedSql <- SqlRender::readSql(inputFile) + renderedSql <- SqlRender::renderSql(parameterizedSql, cdmSchema=cdmSchema, resultsSchema=resultsSchema, studyName = studyName, sourceName=sourceName, txlist=TxList, dxlist=DxList, excludedxlist=ExcludeDxList, smallcellcount = minCellCount)$sql + translatedSql <- SqlRender::translateSql(renderedSql, sourceDialect = ""sql server"", targetDialect = dbms)$sql + SqlRender::writeSql(translatedSql,outputFile) + writeLines(paste(""Created file '"",outputFile,""'"",sep="""")) + return(outputFile) +} + +#' @importFrom DatabaseConnector querySql +#' @keywords internal +extractAndWriteToFile <- function(connection, tableName, cdmSchema, resultsSchema, sourceName, studyName, dbms){ + parameterizedSql <- ""SELECT * FROM @resultsSchema.dbo.@studyName_@sourceName_@tableName"" + renderedSql <- SqlRender::renderSql(parameterizedSql, cdmSchema=cdmSchema, resultsSchema=resultsSchema, studyName=studyName, sourceName=sourceName, tableName=tableName)$sql + translatedSql <- SqlRender::translateSql(renderedSql, sourceDialect = ""sql server"", targetDialect = dbms)$sql + data <- DatabaseConnector::querySql(connection, translatedSql) + outputFile <- paste(studyName,""_"",sourceName,""_"",tableName,"".csv"",sep='') + write.csv(data,file=outputFile) + writeLines(paste(""Created file '"",outputFile,""'"",sep="""")) +} + + + ","R" +"Pharmacogenetics","OHDSI/StudyProtocols","TxPathways12mo/R/MainAnalysis.R",".R","5991","149"," +#' @title Email results +#' +#' @details +#' This function emails the result CSV files to the study coordinator. +#' +#' @return +#' A list of files that were emailed. +#' +#' @param from Return email address +#' @param to Delivery email address (must be a gmail.com acccount) +#' @param subject Subject line of email +#' @param dataDescription A short description of the database +#' @param sourceName Short name that was be appeneded to results table name +#' @param folder The name of the local folder to place results; make sure to use forward slashes (/) +#' @param compress Use GZip compression on transmitted files +#' +#' @export +email <- function(from, + to = ""rijduke@gmail.com"", + subject = ""OHDSI Study 2 Results"", + dataDescription, + sourceName = ""source_name"", + folder = getwd(), + compress = TRUE) { + + if (missing(from)) stop(""Must provide return address"") + if (missing(dataDescription)) stop(""Must provide a data description"") + + suffix <- c(""_person_cnt.csv"", ""_seq_cnt.csv"", ""_summary.csv"") + prefix <- c(""Dep12mo_"", ""HTN12mo_"", ""DM12mo_"") + + files <- unlist(lapply(prefix, paste, + paste(sourceName, suffix, sep =""""), + sep ="""")) + absolutePaths <- paste(folder, files, sep=""/"") + + if (compress) { + + sapply(absolutePaths, function(name) { + newName = paste(name, "".gz"", sep="""") + tmp <- read.csv(file = name) + newFile <- gzfile(newName, ""w"") + write.csv(tmp, newFile) + writeLines(paste(""Compressed to file '"",newName,""'"",sep="""")) + close(newFile) + }) + absolutePaths <- paste(absolutePaths, "".gz"", sep="""") + } + + result <- mailR::send.mail(from = from, + to = to, + subject = subject, + body = paste(""\n"", dataDescription, ""\n"", + sep = """"), + smtp = list(host.name = ""aspmx.l.google.com"", + port = 25), + attach.files = absolutePaths, + authenticate = FALSE, + send = TRUE) + if (result$isSendPartial()) { + stop(""Error in sending email"") + } else { + writeLines(""Emailed the following files:\n"") + writeLines(paste(absolutePaths, collapse=""\n"")) + writeLines(paste(""\nto:"", to)) + } +} + +#' @title Execute OHDSI Study 2 +#' +#' @details +#' This function executes OHDSI Study 2 -- Treatment Pathways Study +#' Protocol 12 months. This is a study of treatment pathways in hypertension, +#' diabetes and depression during the first 12 months after diagnosis. +#' Detailed information and protocol are available on the OHDSI Wiki. +#' +#' @return +#' Study results are placed in CSV format files in specified local folder. + +#' @param dbms The type of DBMS running on the server. Valid values are +#' \itemize{ +#' \item{""mysql"" for MySQL} +#' \item{""oracle"" for Oracle} +#' \item{""postgresql"" for PostgreSQL} +#' \item{""redshift"" for Amazon Redshift} +#' \item{""sql server"" for Microsoft SQL Server} +#' } +#' @param user The user name used to access the server. +#' @param password The password for that user +#' @param server The name of the server +#' @param port (optional) The port on the server to connect to +#' @param cdmSchema Schema name where your patient-level data in OMOP CDM format resides +#' @param resultsSchema Schema where you'd like the results tables to be created (requires user to have create/write access) +#' @param minCellCount The smallest allowable cell count, 1 means all counts are allowed +#' @param sourceName Short name that will be appeneded to results table name +#' @param folder The name of the local folder to place results; make sure to use forward slashes (/) +#' +#' @importFrom DBI dbDisconnect +#' @export +execute <- function(dbms, user, password, server, + port = NULL, + cdmSchema, resultsSchema, + minCellCount = 1, + sourceName = ""source_name"", + folder = getwd()) { + + connectionDetails <- DatabaseConnector::createConnectionDetails(dbms=dbms, + server=server, + user=user, + password=password, + schema=cdmSchema, + port=port) + + + ########################################################### + # End of parameters. Make no changes after this # + ########################################################### + + setwd(folder) + + # Create the parameterized SQL files: + htnSqlFile <- renderStudySpecificSql(""HTN12mo"",minCellCount,cdmSchema,resultsSchema,sourceName,dbms) + t2dmSqlFile <- renderStudySpecificSql(""DM12mo"",minCellCount,cdmSchema,resultsSchema,sourceName,dbms) + depSqlFile <- renderStudySpecificSql(""Dep12mo"",minCellCount,cdmSchema,resultsSchema,sourceName,dbms) + + # Execute the SQL: + conn <- DatabaseConnector::connect(connectionDetails) + DatabaseConnector::executeSql(conn,SqlRender::readSql(htnSqlFile)) + DatabaseConnector::executeSql(conn,SqlRender::readSql(t2dmSqlFile)) + DatabaseConnector::executeSql(conn,SqlRender::readSql(depSqlFile)) + + # Extract tables to CSV files: + extractAndWriteToFile(conn, ""summary"", cdmSchema, resultsSchema, sourceName, ""HTN12mo"", dbms) + extractAndWriteToFile(conn, ""person_cnt"", cdmSchema, resultsSchema, sourceName, ""HTN12mo"", dbms) + extractAndWriteToFile(conn, ""seq_cnt"", cdmSchema, resultsSchema, sourceName, ""HTN12mo"", dbms) + + extractAndWriteToFile(conn, ""summary"", cdmSchema, resultsSchema, sourceName, ""DM12mo"", dbms) + extractAndWriteToFile(conn, ""person_cnt"", cdmSchema, resultsSchema, sourceName, ""DM12mo"", dbms) + extractAndWriteToFile(conn, ""seq_cnt"", cdmSchema, resultsSchema, sourceName, ""DM12mo"", dbms) + + extractAndWriteToFile(conn, ""summary"", cdmSchema, resultsSchema, sourceName, ""Dep12mo"", dbms) + extractAndWriteToFile(conn, ""person_cnt"", cdmSchema, resultsSchema, sourceName, ""Dep12mo"", dbms) + extractAndWriteToFile(conn, ""seq_cnt"", cdmSchema, resultsSchema, sourceName, ""Dep12mo"", dbms) + + DBI::dbDisconnect(conn) + +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CelecoxibVsNsNSAIDs/R/EmpiricalCalibration.R",".R","3049","62","# Copyright 2015 Observational Health Data Sciences and Informatics +# +# This file is part of CelecoxibVsNsNSAIDs +# +# 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. + + +#' Perform empirical calibration +#' +#' @details +#' Performs empricical calibration using the negative control outcomes, and computes +#' the calibrated p-values +#' +#' @param outputFolder The path to the output folder containing the results. +#' +#' @export +doEmpiricalCalibration <- function(outputFolder) { + outcomeReference <- readRDS(file.path(outputFolder, ""outcomeModelReference.rds"")) + analysisSummary <- CohortMethod::summarizeAnalyses(outcomeReference) + cmAnalysisList <- CohortMethod::loadCmAnalysisList(file.path(outputFolder, ""cmAnalysisList.txt"")) + # Add analysis description: + for (i in 1:length(cmAnalysisList)) { + analysisSummary$description[analysisSummary$analysisId == cmAnalysisList[[i]]$analysisId] <- cmAnalysisList[[i]]$description + } + + negControlCohortIds <- unique(analysisSummary$outcomeId[analysisSummary$outcomeId > 100]) + # Calibrate p-values: + for (analysisId in unique(analysisSummary$analysisId)) { + negControlSubset <- analysisSummary[analysisSummary$analysisId == analysisId & analysisSummary$outcomeId %in% + negControlCohortIds, ] + negControlSubset <- negControlSubset[!is.na(negControlSubset$logRr) & negControlSubset$logRr != + 0, ] + if (nrow(negControlSubset) > 10) { + null <- EmpiricalCalibration::fitMcmcNull(negControlSubset$logRr, negControlSubset$seLogRr) + subset <- analysisSummary[analysisSummary$analysisId == analysisId, ] + calibratedP <- EmpiricalCalibration::calibrateP(null, subset$logRr, subset$seLogRr) + subset$calibratedP <- calibratedP$p + subset$calibratedP_lb95ci <- calibratedP$lb95ci + subset$calibratedP_ub95ci <- calibratedP$ub95ci + mcmc <- attr(null, ""mcmc"") + subset$null_mean <- mean(mcmc$chain[, 1]) + subset$null_sd <- 1/sqrt(mean(mcmc$chain[, 2])) + analysisSummary$calibratedP[analysisSummary$analysisId == analysisId] <- subset$calibratedP + analysisSummary$calibratedP_lb95ci[analysisSummary$analysisId == analysisId] <- subset$calibratedP_lb95ci + analysisSummary$calibratedP_ub95ci[analysisSummary$analysisId == analysisId] <- subset$calibratedP_ub95ci + analysisSummary$null_mean[analysisSummary$analysisId == analysisId] <- subset$null_mean + analysisSummary$null_sd[analysisSummary$analysisId == analysisId] <- subset$null_sd + } + } + write.csv(analysisSummary, file.path(outputFolder, ""Results.csv""), row.names = FALSE) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CelecoxibVsNsNSAIDs/R/PackageMaintenance.R",".R","2209","48","# Copyright 2015 Observational Health Data Sciences and Informatics +# +# This file is part of CelecoxibVsNsNSAIDs +# +# 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. + +.formatAndCheckCode <- function() { + OhdsiRTools::formatRFolder() + OhdsiRTools::checkUsagePackage(""CelecoxibVsNsNSAIDs"") +} + +.createManualAndVignettes <- function() { + shell(""rm extras/CelecoxibVsNsNSAIDs.pdf"") + shell(""R CMD Rd2pdf ./ --output=extras/CelecoxibVsNsNSAIDs.pdf"") +} + +.insertCohortDefinitions <- function() { + OhdsiRTools::insertCirceDefinitionInPackage(293, ""Treatment"") + OhdsiRTools::insertCirceDefinitionInPackage(489, ""Comparator"") + OhdsiRTools::insertCirceDefinitionInPackage(280, ""MyocardialInfarction"") + OhdsiRTools::insertCirceDefinitionInPackage(289, ""MiAndIschemicDeath"") + OhdsiRTools::insertCirceDefinitionInPackage(288, ""GiHemorrhage"") + OhdsiRTools::insertCirceDefinitionInPackage(282, ""Angioedema"") + OhdsiRTools::insertCirceDefinitionInPackage(417, ""AcuteRenalFailure"") + OhdsiRTools::insertCirceDefinitionInPackage(416, ""DrugInducedLiverInjury"") + OhdsiRTools::insertCirceDefinitionInPackage(418, ""HeartFailure"") +} + +.createAnalysisDetails <- function() { + connectionDetails <- DatabaseConnector::createConnectionDetails(dbms = ""pdw"", + server = ""JRDUSAPSCTL01"", + user = NULL, + password = NULL, + port = 17001) + cdmDatabaseSchema <- ""cdm_truven_mdcd_v5.dbo"" + createAnalysesDetails(connectionDetails, cdmDatabaseSchema, ""inst/settings/"") +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CelecoxibVsNsNSAIDs/R/Main.R",".R","5734","127","# Copyright 2015 Observational Health Data Sciences and Informatics +# +# This file is part of CelecoxibVsNsNSAIDs +# +# 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. + +#' @title +#' Execute OHDSI Celecoxib versus non-selective NSAIDs study +#' +#' @details +#' This function executes the OHDSI Celecoxib versus non-selective NSAIDs study. +#' +#' @return +#' TODO +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param workDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param studyCohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param cdmVersion Version of the CDM. Can be ""4"" or ""5"" +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' +#' @examples +#' \dontrun{ +#' connectionDetails <- createConnectionDetails(dbms = ""postgresql"", +#' user = ""joe"", +#' password = ""secret"", +#' server = ""myserver"") +#' +#' execute(connectionDetails, +#' cdmDatabaseSchema = ""cdm_data"", +#' workDatabaseSchema = ""results"", +#' oracleTempSchema = NULL, +#' outputFolder = ""c:/temp/study_results"", +#' cdmVersion = ""5"") +#' +#' } +#' +#' @export +execute <- function(connectionDetails, + cdmDatabaseSchema, + workDatabaseSchema = cdmDatabaseSchema, + studyCohortTable = ""ohdsi_celecoxib_nsnsaids"", + oracleTempSchema = NULL, + cdmVersion = 5, + outputFolder, + createCohorts = TRUE, + runAnalyses = TRUE, + empiricalCalibration = TRUE, + packageResultsForSharing = TRUE) { + + if (cdmVersion == 4) { + stop(""CDM version 4 not supported"") + } + + if (!file.exists(outputFolder)) + dir.create(outputFolder) + + if (createCohorts) { + writeLines(""Creating exposure and outcome cohorts"") + createCohorts(connectionDetails, + cdmDatabaseSchema, + workDatabaseSchema, + studyCohortTable, + oracleTempSchema, + cdmVersion, + outputFolder) + } + + if (runAnalyses) { + writeLines(""Running analyses"") + cmAnalysisListFile <- system.file(""settings"", ""cmAnalysisList.txt"", package = ""CelecoxibVsNsNSAIDs"") + cmAnalysisList <- CohortMethod::loadCmAnalysisList(cmAnalysisListFile) + drugComparatorOutcomesListFile <- system.file(""settings"", ""drugComparatorOutcomesList.txt"", package = ""CelecoxibVsNsNSAIDs"") + drugComparatorOutcomesList <- CohortMethod::loadDrugComparatorOutcomesList(drugComparatorOutcomesListFile) + CohortMethod::runCmAnalyses(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + exposureDatabaseSchema = workDatabaseSchema, + exposureTable = studyCohortTable, + outcomeDatabaseSchema = workDatabaseSchema, + outcomeTable = studyCohortTable, + outputFolder = outputFolder, + cmAnalysisList = cmAnalysisList, + cdmVersion = cdmVersion, + drugComparatorOutcomesList = drugComparatorOutcomesList, + getDbCohortMethodDataThreads = 1, + createPsThreads = 1, + psCvThreads = 10, + computeCovarBalThreads = 2, + trimMatchStratifyThreads = 10, + fitOutcomeModelThreads = 3, + outcomeCvThreads = 10) + # TODO: exposure multi-threading parameters + } + + if (empiricalCalibration) { + writeLines(""Performing empirical calibration"") + doEmpiricalCalibration(outputFolder = outputFolder) + } + + if (packageResultsForSharing) { + writeLines(""Packaging results"") + packageResults(outputFolder = outputFolder) + } +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CelecoxibVsNsNSAIDs/R/CreateCohorts.R",".R","12598","205","# Copyright 2015 Observational Health Data Sciences and Informatics +# +# This file is part of CelecoxibVsNsNSAIDs +# +# 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. + + +#' Create the exposure and outcome cohorts +#' +#' @details +#' This function will create the exposure and outcome cohorts following the definitions included in +#' this package. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param workDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param studyCohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param cdmVersion Version of the CDM. Can be ""4"" or ""5"" +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' +#' @export +createCohorts <- function(connectionDetails, + cdmDatabaseSchema, + workDatabaseSchema, + studyCohortTable = ""ohdsi_celecoxib_nsnsaids"", + oracleTempSchema, + cdmVersion = 5, + outputFolder) { + conn <- DatabaseConnector::connect(connectionDetails) + + # Create study cohort table structure: + sql <- ""IF OBJECT_ID('@work_database_schema.@study_cohort_table', 'U') IS NOT NULL\n DROP TABLE @work_database_schema.@study_cohort_table;\n CREATE TABLE @work_database_schema.@study_cohort_table (cohort_definition_id INT, subject_id BIGINT, cohort_start_date DATE, cohort_end_date DATE);"" + sql <- SqlRender::renderSql(sql, + work_database_schema = workDatabaseSchema, + study_cohort_table = studyCohortTable)$sql + sql <- SqlRender::translateSql(sql, targetDialect = connectionDetails$dbms)$sql + DatabaseConnector::executeSql(conn, sql, progressBar = FALSE, reportOverallTime = FALSE) + + writeLines(""- Creating treatment cohort"") + sql <- SqlRender::loadRenderTranslateSql(""Treatment.sql"", + ""CelecoxibVsNsNSAIDs"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable, + cohort_definition_id = 1) + DatabaseConnector::executeSql(conn, sql) + + writeLines(""- Creating comparator cohort"") + sql <- SqlRender::loadRenderTranslateSql(""Comparator.sql"", + ""CelecoxibVsNsNSAIDs"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable, + cohort_definition_id = 2) + DatabaseConnector::executeSql(conn, sql) + + writeLines(""- Creating myocardial infarction cohort"") + sql <- SqlRender::loadRenderTranslateSql(""MyocardialInfarction.sql"", + ""CelecoxibVsNsNSAIDs"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable, + cohort_definition_id = 10) + DatabaseConnector::executeSql(conn, sql) + + writeLines(""- Creating myocardial infarction and ischemic death cohort"") + sql <- SqlRender::loadRenderTranslateSql(""MiAndIschemicDeath.sql"", + ""CelecoxibVsNsNSAIDs"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable, + cohort_definition_id = 11) + DatabaseConnector::executeSql(conn, sql) + + writeLines(""- Creating gastrointestinal hemorrhage cohort"") + sql <- SqlRender::loadRenderTranslateSql(""GiHemorrhage.sql"", + ""CelecoxibVsNsNSAIDs"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable, + cohort_definition_id = 12) + DatabaseConnector::executeSql(conn, sql) + + writeLines(""- Creating angioedema cohort"") + sql <- SqlRender::loadRenderTranslateSql(""Angioedema.sql"", + ""CelecoxibVsNsNSAIDs"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable, + cohort_definition_id = 13) + DatabaseConnector::executeSql(conn, sql) + + writeLines(""- Creating acute renal failure cohort"") + sql <- SqlRender::loadRenderTranslateSql(""AcuteRenalFailure.sql"", + ""CelecoxibVsNsNSAIDs"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable, + cohort_definition_id = 14) + DatabaseConnector::executeSql(conn, sql) + + writeLines(""- Creating drug induced liver injury cohort"") + sql <- SqlRender::loadRenderTranslateSql(""DrugInducedLiverInjury.sql"", + ""CelecoxibVsNsNSAIDs"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable, + cohort_definition_id = 15) + DatabaseConnector::executeSql(conn, sql) + + writeLines(""- Creating heart failure cohort"") + sql <- SqlRender::loadRenderTranslateSql(""HeartFailure.sql"", + ""CelecoxibVsNsNSAIDs"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable, + cohort_definition_id = 16) + DatabaseConnector::executeSql(conn, sql) + + writeLines(""- Creating negative control outcome cohort"") + sql <- SqlRender::loadRenderTranslateSql(""NegativeControls.sql"", + ""CelecoxibVsNsNSAIDs"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable) + DatabaseConnector::executeSql(conn, sql) + + # Check number of subjects per cohort: + sql <- ""SELECT cohort_definition_id, COUNT(*) AS count FROM @work_database_schema.@study_cohort_table GROUP BY cohort_definition_id"" + sql <- SqlRender::renderSql(sql, + work_database_schema = workDatabaseSchema, + study_cohort_table = studyCohortTable)$sql + sql <- SqlRender::translateSql(sql, targetDialect = connectionDetails$dbms)$sql + counts <- DatabaseConnector::querySql(conn, sql) + names(counts) <- SqlRender::snakeCaseToCamelCase(names(counts)) + counts <- addOutcomeNames(counts, ""cohortDefinitionId"") + write.csv(counts, file.path(outputFolder, ""CohortCounts.csv"")) + print(counts) + + RJDBC::dbDisconnect(conn) +} + +#' Add names to a data frame with outcome IDs +#' +#' @param data The data frame to add the outcome names to +#' @param outcomeIdColumnName The name of the column in the data frame that holds the outcome IDs. +#' +#' @export +addOutcomeNames <- function(data, outcomeIdColumnName = ""outcomeId"") { + idToName <- data.frame(outcomeId = c(1, 2, 10, 11, 12, 13, 14, 15, 16), + cohortName = c(""Treatment"", + ""Comparator"", + ""Myocardial infarction"", + ""Myocardial infarction and ischemic death"", + ""Gastrointestinal hemorrhage"", + ""Angioedema"", + ""Acute renal failure"", + ""Drug induced liver injury"", + ""Heart failure"")) + names(idToName)[1] <- outcomeIdColumnName + data <- merge(data, idToName, all.x = TRUE) + return(data) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CelecoxibVsNsNSAIDs/R/TestCode.R",".R","1632","46",".testCode <- function() { + # library(CelecoxibVsNsNSAIDs) + options(fftempdir = ""s:/FFtemp"") + + dbms <- ""pdw"" + user <- NULL + pw <- NULL + server <- ""JRDUSAPSCTL01"" + port <- 17001 + connectionDetails <- DatabaseConnector::createConnectionDetails(dbms = dbms, + server = server, + user = user, + password = pw, + port = port) + cdmDatabaseSchema <- ""cdm_truven_mdcd_v5.dbo"" + workDatabaseSchema <- ""scratch.dbo"" + studyCohortTable <- ""ohdsi_celecoxib_vs_nsnsaids"" + oracleTempSchema <- NULL + cdmVersion <- ""5"" + outputFolder <- ""S:/temp/CelecoxibVsNsNSAIDs_MDCD"" + + + cdmDatabaseSchema <- ""cdm_truven_ccae_v5.dbo"" + workDatabaseSchema <- ""scratch.dbo"" + studyCohortTable <- ""ohdsi_celecoxib_vs_nsnsaids_ccae"" + oracleTempSchema <- NULL + cdmVersion <- ""5"" + outputFolder <- ""S:/temp/CelecoxibVsNsNSAIDs_CCAE"" + + cdmDatabaseSchema <- ""cdm_truven_mdcr_v5.dbo"" + workDatabaseSchema <- ""scratch.dbo"" + studyCohortTable <- ""ohdsi_celecoxib_vs_nsnsaids_mdcr"" + oracleTempSchema <- NULL + cdmVersion <- ""5"" + outputFolder <- ""S:/temp/CelecoxibVsNsNSAIDs_MDCR"" + + execute(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + workDatabaseSchema = workDatabaseSchema, + studyCohortTable = studyCohortTable, + oracleTempSchema = oracleTempSchema, + cdmVersion = cdmVersion, + outputFolder = outputFolder) + +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CelecoxibVsNsNSAIDs/R/PackageResultsForSharing.R",".R","4617","91","# Copyright 2015 Observational Health Data Sciences and Informatics +# +# This file is part of CelecoxibVsNsNSAIDs +# +# 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. + +#' Package the results for sharing with OHDSI researchers +#' +#' @details +#' This function packages the results. +#' +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes (/) +#' +#' @export +packageResults <- function(outputFolder) { + exportFolder <- file.path(outputFolder, ""export"") + + if (!file.exists(exportFolder)) + dir.create(exportFolder) + + outcomeReference <- readRDS(file.path(outputFolder, ""outcomeModelReference.rds"")) + analysisSummary <- read.csv(file.path(outputFolder, ""Results.csv"")) + + ### Write main results table ### + write.csv(analysisSummary, file.path(exportFolder, ""Results.csv""), row.names = FALSE) + + ### Main propensity score plot ### + psFileName <- outcomeReference$sharedPsFile[outcomeReference$sharedPsFile != """"][1] + ps <- readRDS(psFileName) + CohortMethod::plotPs(ps, fileName = file.path(exportFolder, ""PS_pref_scale.png"")) + CohortMethod::plotPs(ps, scale = ""propensity"", fileName = file.path(exportFolder, ""PS.png"")) + + ### Covariate balance table ### + balFileName <- outcomeReference$covariateBalanceFile[outcomeReference$covariateBalanceFile != """"][1] + balance <- readRDS(balFileName) + + write.csv(balance, file.path(exportFolder, ""Balance.csv""), row.names = FALSE) + + ### Two covariate balance plots ### + CohortMethod::plotCovariateBalanceScatterPlot(balance, fileName = file.path(exportFolder, + ""Balance_scatterplot.png"")) + CohortMethod::plotCovariateBalanceOfTopVariables(balance, fileName = file.path(exportFolder, + ""Balance_topVars.png"")) + + ### Empiricial calibration plots ### + negControlCohortIds <- unique(analysisSummary$outcomeId[analysisSummary$outcomeId > 100]) + for (analysisId in unique(analysisSummary$analysisId)) { + negControlSubset <- analysisSummary[analysisSummary$analysisId == analysisId & analysisSummary$outcomeId %in% + negControlCohortIds, ] + negControlSubset <- negControlSubset[!is.na(negControlSubset$logRr) & negControlSubset$logRr != + 0, ] + posControlSubset <- analysisSummary[analysisSummary$analysisId == analysisId & !(analysisSummary$outcomeId %in% + negControlCohortIds), ] + posControlSubset <- posControlSubset[!is.na(posControlSubset$logRr) & posControlSubset$logRr != + 0, ] + + if (nrow(negControlSubset) > 10) { + EmpiricalCalibration::plotCalibrationEffect(negControlSubset$logRr, + negControlSubset$seLogRr, + posControlSubset$logRr, + posControlSubset$seLogRr, + fileName = file.path(exportFolder, paste(""CalEffect_a"", + analysisId, + "".png"", + sep = """"))) + EmpiricalCalibration::plotCalibration(negControlSubset$logRr, + negControlSubset$seLogRr, + useMcmc = TRUE, + fileName = file.path(exportFolder, paste(""Calibration_a"", + analysisId, + "".png"", + sep = """"))) + } + } + + ### Add all to zip file ### + zipName <- file.path(exportFolder, ""StudyResults.zip"") + OhdsiSharing::compressFolder(exportFolder, zipName) + writeLines(paste(""\nStudy results are ready for sharing at:"", zipName)) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CelecoxibVsNsNSAIDs/R/CreateStudyAnalysesDetails.R",".R","16712","310","# Copyright 2015 Observational Health Data Sciences and Informatics +# +# This file is part of CelecoxibVsNsNSAIDs +# +# 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. + +#' Create the analyses details +#' +#' @details +#' This function creates files specifying the analyses that will be performed. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' +#' @export +createAnalysesDetails <- function(connectionDetails, cdmDatabaseSchema, outputFolder) { + conn <- DatabaseConnector::connect(connectionDetails) + + # Get all NSAIDs: + sql <- ""SELECT concept_id FROM @cdmDatabaseSchema.concept_ancestor INNER JOIN @cdmDatabaseSchema.concept ON descendant_concept_id = concept_id WHERE ancestor_concept_id = 21603933"" + sql <- SqlRender::renderSql(sql, cdmDatabaseSchema = cdmDatabaseSchema)$sql + sql <- SqlRender::translateSql(sql, targetDialect = connectionDetails$dbms)$sql + nsaids <- DatabaseConnector::querySql(conn, sql) + nsaids <- nsaids$CONCEPT_ID + + RJDBC::dbDisconnect(conn) + + negativeControlIds <- c(22281, + 72418, + 72712, + 73302, + 74855, + 76737, + 77650, + 78804, + 79072, + 80509, + 81250, + 81336, + 133141, + 133228, + 133327, + 133551, + 134118, + 134222, + 134765, + 136937, + 137054, + 139099, + 140362, + 140641, + 141216, + 141825, + 192606, + 193326, + 193874, + 194702, + 194997, + 195212, + 195501, + 197036, + 198075, + 199876, + 201388, + 253796, + 261326, + 261880, + 315288, + 317305, + 317376, + 317585, + 317895, + 319845, + 373478, + 373766, + 374384, + 376132, + 376712, + 378160, + 378256, + 378424, + 379769, + 380395, + 380731, + 381581, + 432851, + 433163, + 433440, + 434309, + 434319, + 434626, + 434630, + 435140, + 436100, + 436740, + 437222, + 437409, + 437986, + 438134, + 438407, + 438872, + 439237, + 439840, + 440389, + 440424, + 440676, + 440695, + 440814, + 441267, + 441788, + 442274, + 443361, + 443605, + 443767, + 444130, + 444191, + 4018050, + 4028970, + 4029582, + 4029966, + 4044391, + 4047269, + 4047787, + 4052648, + 4083964, + 4085156, + 4087647, + 4092565, + 4095288, + 4096666, + 4112853, + 4114197, + 4114222, + 4129880, + 4130061, + 4131595, + 4131616, + 4132130, + 4132546, + 4140510, + 4146239, + 4147672, + 4153380, + 4153877, + 4163232, + 4164337, + 4171549, + 4171915, + 4172458, + 4174977, + 4186392, + 4195698, + 4207688, + 4209011, + 4215978, + 4218106, + 4223947, + 4224118, + 4242416, + 4256228, + 4262178, + 4270490, + 4285569, + 4286201, + 4288544, + 4289933, + 4295888, + 4297984, + 4305304, + 4307254, + 4322737, + 4339088, + 43020424, + 45768449) + + # 80180 = Osteoarthritis. Note that all descendant concepts will also be included + dcos <- CohortMethod::createDrugComparatorOutcomes(targetId = 1, + comparatorId = 2, + exclusionConceptIds = nsaids, + excludedCovariateConceptIds = nsaids, + indicationConceptIds = 80180, + outcomeIds = c(10:16, negativeControlIds)) + drugComparatorOutcomesList <- list(dcos) + + covarSettings <- PatientLevelPrediction::createCovariateSettings(useCovariateDemographics = TRUE, + useCovariateConditionOccurrence = TRUE, + useCovariateConditionOccurrence365d = TRUE, + useCovariateConditionOccurrence30d = TRUE, + useCovariateConditionOccurrenceInpt180d = TRUE, + useCovariateConditionEra = TRUE, + useCovariateConditionEraEver = TRUE, + useCovariateConditionEraOverlap = TRUE, + useCovariateConditionGroup = TRUE, + useCovariateDrugExposure = TRUE, + useCovariateDrugExposure365d = TRUE, + useCovariateDrugExposure30d = TRUE, + useCovariateDrugEra = TRUE, + useCovariateDrugEra365d = TRUE, + useCovariateDrugEra30d = TRUE, + useCovariateDrugEraEver = TRUE, + useCovariateDrugEraOverlap = TRUE, + useCovariateDrugGroup = TRUE, + useCovariateProcedureOccurrence = TRUE, + useCovariateProcedureOccurrence365d = TRUE, + useCovariateProcedureOccurrence30d = TRUE, + useCovariateProcedureGroup = TRUE, + useCovariateObservation = TRUE, + useCovariateObservation365d = TRUE, + useCovariateObservation30d = TRUE, + useCovariateObservationCount365d = TRUE, + useCovariateMeasurement365d = TRUE, + useCovariateMeasurement30d = TRUE, + useCovariateMeasurementCount365d = TRUE, + useCovariateMeasurementBelow = TRUE, + useCovariateMeasurementAbove = TRUE, + useCovariateConceptCounts = TRUE, + useCovariateRiskScores = TRUE, + useCovariateRiskScoresCharlson = TRUE, + useCovariateRiskScoresDCSI = TRUE, + useCovariateRiskScoresCHADS2 = TRUE, + useCovariateRiskScoresCHADS2VASc = TRUE, + useCovariateInteractionYear = FALSE, + useCovariateInteractionMonth = FALSE, + excludedCovariateConceptIds = c(), + deleteCovariatesSmallCount = 100) + + getDbCmDataArgs <- CohortMethod::createGetDbCohortMethodDataArgs(washoutWindow = 183, + indicationLookbackWindow = 183, + studyStartDate = """", + studyEndDate = """", + excludeDrugsFromCovariates = FALSE, + covariateSettings = covarSettings) + + fitOutcomeModelArgs1 <- CohortMethod::createFitOutcomeModelArgs(riskWindowStart = 0, + riskWindowEnd = 30, + addExposureDaysToEnd = TRUE, + useCovariates = FALSE, + modelType = ""cox"", + stratifiedCox = FALSE) + + cmAnalysis1 <- CohortMethod::createCmAnalysis(analysisId = 1, + description = ""No matching, simple outcome model"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + createPsArgs <- CohortMethod::createCreatePsArgs() # Using only defaults + + matchOnPsArgs <- CohortMethod::createMatchOnPsArgs(maxRatio = 100) + + fitOutcomeModelArgs2 <- CohortMethod::createFitOutcomeModelArgs(riskWindowStart = 0, + riskWindowEnd = 30, + addExposureDaysToEnd = TRUE, + useCovariates = FALSE, + modelType = ""cox"", + stratifiedCox = TRUE) + + cmAnalysis2 <- CohortMethod::createCmAnalysis(analysisId = 2, + description = ""Matching plus simple stratified outcome model"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createPs = TRUE, + createPsArgs = createPsArgs, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgs, + computeCovariateBalance = TRUE, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs2) + + fitOutcomeModelArgs3 <- CohortMethod::createFitOutcomeModelArgs(riskWindowStart = 0, + riskWindowEnd = 30, + addExposureDaysToEnd = TRUE, + useCovariates = TRUE, + modelType = ""cox"", + stratifiedCox = TRUE) + + cmAnalysis3 <- CohortMethod::createCmAnalysis(analysisId = 3, + description = ""Matching plus full outcome model"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createPs = TRUE, + createPsArgs = createPsArgs, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgs, + computeCovariateBalance = TRUE, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs3) + + cmAnalysisList <- list(cmAnalysis1, cmAnalysis2, cmAnalysis3) + + CohortMethod::saveCmAnalysisList(cmAnalysisList, file.path(outputFolder, ""cmAnalysisList.txt"")) + CohortMethod::saveDrugComparatorOutcomesList(drugComparatorOutcomesList, + file.path(outputFolder, + ""drugComparatorOutcomesList.txt"")) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CelecoxibVsNsNSAIDs/tests/testthat.R",".R","82","5","library(testthat) +library(CelecoxibVsNsNSAIDs) + +test_check(""CelecoxibVsNsNSAIDs"") +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","OpioidModels/R/helpers.R",".R","16091","334","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of OpioidModels package +# +# 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. + + +#' Creates the target and outcome cohorts +#' +#' @details +#' This will create the risk prediciton cohorts +#' +#' @param connectioDetails The connections details for connecting to the CDM +#' @param cdmDatabaseSchema The schema holding the CDM data +#' @param cohortDatabaseSchema The schema holding the cohort table +#' @param cohortTable The name of the cohort table +#' +#' @return +#' A summary of the cohort counts +#' +#' @export +createOpioidTables <- function(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable){ + + connection <- DatabaseConnector::connect(connectionDetails) + + #checking whether cohort table exists and creating if not.. + # create the cohort table if it doesnt exist + existTab <- toupper(cohortTable)%in%toupper(DatabaseConnector::getTableNames(connection, cohortDatabaseSchema)) + if(!existTab){ + sql <- SqlRender::loadRenderTranslateSql(""createTable.sql"", + packageName = ""OpioidModels"", + dbms = attr(connection, ""dbms""), + target_database_schema = cohortDatabaseSchema, + target_cohort_table = cohortTable) + DatabaseConnector::executeSql(connection, sql) + } + + result <- PatientLevelPrediction::createCohort(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + package = 'OpioidModels') + + + return(result) +} + + +#' Validates the opioid use disorder prediction models +#' +#' @details +#' This will run and evaluate a selected opioid use disorder prediction models +#' +#' @param model The model to apply ('simple','ccae','optum','mdcr','mdcd') +#' @param connectioDetails The connections details for connecting to the CDM +#' @param cdmDatabaseSchema The schema holding the CDM data +#' @param cohortDatabaseSchema The schema holding the cohort table +#' @param cohortTable The name of the cohort table +#' @param outcomeDatabaseSchema The schema holding the outcome table +#' @param outcomeTable The name of the outcome table +#' @param targetId The cohort definition id of the target population +#' @param outcomeId The cohort definition id of the outcome +#' @param oracleTempSchema The temp schema for oracle +#' +#' @return +#' A list with the performance and plots +#' +#' @export +validateOpioidModels <- function(model='simple', + connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable, + cohortId = 1, + outcomeDatabaseSchema, + outcomeTable, + outcomeId = 2, + oracleTempSchema=NULL){ + + if(!model%in%c('simple','ccae','optum','mdcr','mdcd')){ + stop('Incorrect model...') + } + if(missing(connectionDetails)){ + stop('Missing connectionDetails') + } + if(missing(cdmDatabaseSchema)){ + stop('Missing cdmDatabaseSchema') + } + if(missing(cohortDatabaseSchema)){ + stop('Missing cohortDatabaseSchema') + } + if(missing(cohortTable)){ + stop('Missing cohortTable') + } + if(missing(cohortId)){ + stop('Missing cohortId') + } + if(missing(outcomeDatabaseSchema)){ + stop('Missing outcomeDatabaseSchema') + } + if(missing(outcomeTable)){ + stop('Missing outcomeTable') + } + if(missing(outcomeId)){ + stop('Missing outcomeId') + } + + writeLines(paste0('Implementing ',model,' opioid risk model...')) + + if(model=='simple'){ + conceptSets <- system.file(""extdata"", ""opioid_concepts.csv"", package = ""OpioidModels"") + conceptSets <- read.csv(conceptSets) + + modelTable <- system.file(""extdata"", ""opioid_modelTable.csv"", package = ""OpioidModels"") + modelTable <- read.csv(modelTable) + modelTable <- modelTable[,c('modelId','modelCovariateId','coefficientValue')] + + covariateSettings <- FeatureExtraction::createCovariateSettings(useDemographicsAgeGroup = T, + useConditionOccurrenceLongTerm = T, + useConditionGroupEraLongTerm = T, + useProcedureOccurrenceShortTerm = T, + useObservationShortTerm = T, + shortTermStartDays = -30, + longTermStartDays = -9999) + + result <- PatientLevelPrediction::evaluateExistingModel(modelTable = modelTable, + covariateTable = conceptSets[,c('modelCovariateId','covariateId')], + interceptTable = NULL, + type = 'score', + covariateSettings = covariateSettings, + riskWindowStart = 1, + riskWindowEnd = 365, + requireTimeAtRisk = T, + minTimeAtRisk = 364, + includeAllOutcomes = T, + removeSubjectsWithPriorOutcome = T, + connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + cohortId = cohortId, + outcomeDatabaseSchema = outcomeDatabaseSchema, + outcomeTable = outcomeTable, + outcomeId = outcomeId, + calibrationPopulation=NULL) + + inputSetting <- list(connectionDetails=connectionDetails, + cdmDatabaseSchema=cdmDatabaseSchema, + cohortDatabaseSchema=cohortDatabaseSchema, + outcomeDatabaseSchema=outcomeDatabaseSchema, + cohortTable=cohortTable, + outcomeTable=outcomeTable, + cohortId=cohortId, + outcomeId=outcomeId, + oracleTempSchema=oracleTempSchema) + result <- list(model=list(model=model), + analysisRef ='000000', + inputSetting =inputSetting, + executionSummary = 'Not available', + prediction=result$prediction, + performanceEvaluation=result$performance) + class(result$model) <- 'plpModel' + attr(result$model, ""type"")<- 'existing model' + class(result) <- 'runPlp' + return(result) + + }else{ + #load model + plpResult <- PatientLevelPrediction::loadPlpResult(system.file('plp_models',model, package='OpioidModels')) + + # newData + newData <- PatientLevelPrediction::similarPlpData(plpModel = plpResult$model, + createCohorts = F, + newConnectionDetails = connectionDetails, + newCdmDatabaseSchema = cdmDatabaseSchema, + newCohortDatabaseSchema = cohortDatabaseSchema, + newCohortTable = cohortTable, + newCohortId = cohortId, + newOutcomeDatabaseSchema = outcomeDatabaseSchema, + newOutcomeTable = outcomeTable, + newOutcomeId = outcomeId, + sample = NULL, + createPopulation = T) + #apply model + results <- PatientLevelPrediction::applyModel(population = newData$population, + plpData = newData$plpData, + plpModel = plpResult$model, + calculatePerformance = T) + + } + + + return(results) +} + + + + +#' Apply the opioid use disorder prediction models +#' +#' @details +#' This will run a selected opioid use disorder prediction models +#' +#' @param model The model to apply ('simple','ccae','optum','mdcr','mdcd') +#' @param connectioDetails The connections details for connecting to the CDM +#' @param cdmDatabaseSchema The schema holding the CDM data +#' @param cohortDatabaseSchema The schema holding the cohort table +#' @param cohortTable The name of the cohort table +#' @param targetId The cohort definition id of the target population +#' @param oracleTempSchema The temp schema for oracle +#' +#' @return +#' The prediction on the cohort +#' +#' @export +applyOpioidModel <- function(model='simple', + connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable, + cohortId = 1, + oracleTempSchema=NULL){ + + if(!model%in%c('simple','ccae','optum','mdcr','mdcd')){ + stop('Incorrect model...') + } + if(missing(connectionDetails)){ + stop('Missing connectionDetails') + } + if(missing(cdmDatabaseSchema)){ + stop('Missing cdmDatabaseSchema') + } + if(missing(cohortDatabaseSchema)){ + stop('Missing cohortDatabaseSchema') + } + if(missing(cohortTable)){ + stop('Missing cohortTable') + } + if(missing(cohortId)){ + stop('Missing cohortId') + } + + writeLines(paste0('Applying ',model,' opioid risk model...')) + + if(model=='simple'){ + conceptSets <- system.file(""extdata"", ""opioid_concepts.csv"", package = ""OpioidModels"") + conceptSets <- read.csv(conceptSets) + + modelTable <- system.file(""extdata"", ""opioid_modelTable.csv"", package = ""OpioidModels"") + modelTable <- read.csv(modelTable) + modelTable <- modelTable[,c('modelId','modelCovariateId','coefficientValue')] + + covariateSettings <- FeatureExtraction::createCovariateSettings(useDemographicsAgeGroup = T, + useConditionOccurrenceLongTerm = T, + useConditionGroupEraLongTerm = T, + useProcedureOccurrenceShortTerm = T, + useObservationShortTerm = T, + shortTermStartDays = -30, + longTermStartDays = -9999) + + custCovs <- PatientLevelPrediction::createExistingModelSql(modelTable = modelTable, + modelNames = 'simple', + interceptTable = NULL, + covariateTable = conceptSets[,c('modelCovariateId','covariateId')], + type='score', + analysisId = 998, + covariateSettings = covariateSettings, + asFunctions=T) + createExistingmodelsCovariateSettings <- custCovs$createExistingmodelsCovariateSettings + getExistingmodelsCovariateSettings <- custCovs$getExistingmodelsCovariateSettings + assign(paste0('getExistingmodelsCovariateSettings'), custCovs$getExistingmodelsCovariateSettings + ,envir = globalenv()) + + plpData <- PatientLevelPrediction::getPlpData(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + cohortId = cohortId, + outcomeIds = -999, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + outcomeDatabaseSchema = cohortDatabaseSchema, + outcomeTable = cohortTable, + washoutPeriod = 0, + firstExposureOnly = F, + sampleSize = NULL, + covariateSettings = createExistingmodelsCovariateSettings()) + + result <- ff::as.ram(plpData$covariates) + + }else{ + #load model + plpResult <- PatientLevelPrediction::loadPlpResult(system.file('plp_models',model, package='OpioidModels')) + + # newData + plpData <- PatientLevelPrediction::similarPlpData(plpModel = plpResult$model, + createCohorts = F, + newConnectionDetails = connectionDetails, + newCdmDatabaseSchema = cdmDatabaseSchema, + newCohortDatabaseSchema = cohortDatabaseSchema, + newCohortTable = cohortTable, + newCohortId = cohortId, + newOutcomeDatabaseSchema = cohortDatabaseSchema, + newOutcomeTable = cohortTable, + newOutcomeId = -999, + sample = NULL, + createPopulation = F) + #apply model + result <- PatientLevelPrediction::applyModel(population = plpData$cohorts, + plpData = plpData, + plpModel = plpResult$model, + calculatePerformance = F) + + } + + + return(result) +} + + +flog.warn <- OhdsiRTools::logInfo +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AlendronateVsRaloxifene/inst/shiny/EvidenceExplorer/global.R",".R","1781","51","unlink(""s:/temp/log.txt"") +OhdsiRTools::addDefaultFileLogger(""s:/temp/log.txt"") + +# shinySettings <- list(studyFolder = 'S:/SkeletonStudy', blind = TRUE) +studyFolder <- shinySettings$studyFolder +blind <- shinySettings$blind +OhdsiRTools::logDebug(studyFolder) + +databases <- list.files(studyFolder, include.dirs = TRUE) + +loadEstimates <- function(database) { + fileName <- file.path(studyFolder, database, ""AllCalibratedEstimates.rds"") + dbEstimates <- readRDS(fileName) + dbEstimates$database <- database + return(dbEstimates) +} +estimates <- lapply(databases, loadEstimates) +estimates <- do.call(rbind, estimates) + +resultsControls <- estimates[!is.na(estimates$targetEffectSize), ] +resultsHois <- estimates[is.na(estimates$targetEffectSize), ] +if (blind) { + resultsHois$rr <- as.numeric(NA) + resultsHois$ci95lb <- as.numeric(NA) + resultsHois$ci95ub <- as.numeric(NA) + resultsHois$logRr <- as.numeric(NA) + resultsHois$seLogRr <- as.numeric(NA) + resultsHois$p <- as.numeric(NA) + resultsHois$calP <- as.numeric(NA) +} +resultsHois$comparison <- paste(resultsHois$targetName, resultsHois$comparatorName, sep = "" vs. "") +resultsHois$psStrategy <- ""Stratification"" + +comparisons <- unique(resultsHois$comparison) +comparisons <- comparisons[order(comparisons)] + +outcomes <- as.character(unique(resultsHois$outcomeName)) +analyses <- as.character(unique(resultsHois$description)) + +loadMdrrs <- function(database) { + fileName <- file.path(studyFolder, database, ""Mdrrs.csv"") + dbMdrrs <- read.csv(fileName) + dbMdrrs$database <- database + return(dbMdrrs) +} +mdrrs <- lapply(databases, loadMdrrs) +mdrrs <- do.call(rbind, mdrrs) +resultsHois <- merge(resultsHois, + mdrrs[, + c(""targetId"", ""comparatorId"", ""outcomeId"", ""analysisId"", ""database"", ""mdrr"")]) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AlendronateVsRaloxifene/inst/shiny/EvidenceExplorer/server.R",".R","22251","521","library(shiny) +library(DT) +library(ggplot2) +source(""functions.R"") + +mainColumns <- c(""description"", ""database"", ""rr"", ""ci95lb"", ""ci95ub"", ""p"", ""calP"") + +mainColumnNames <- c(""Analysis"", + ""Database"", + ""HR"", + ""CI95LB"", + ""CI95UB"", + ""P"", + ""Cal. P"") + +powerColumns <- c(""treated"", + ""comparator"", + ""treatedDays"", + ""comparatorDays"", + ""eventsTreated"", + ""eventsComparator"", + ""irTreated"", + ""irComparator"", + ""mdrr"") + +powerColumnNames <- c(""Target subjects"", + ""Comparator subjects"", + ""Target days"", + ""Comparator days"", + ""Target events"", + ""Comparator events"", + ""Target IR (per 1,000 PY)"", + ""Comparator IR (per 1,000 PY)"", + ""MDRR"") + +shinyServer(function(input, output) { + + tableSubset <- reactive({ + idx <- resultsHois$comparison == input$comparison & resultsHois$outcomeName == input$outcome & + resultsHois$description %in% input$analysis & resultsHois$database %in% input$db + resultsHois[idx, ] + }) + + selectedRow <- reactive({ + idx <- input$mainTable_rows_selected + if (is.null(idx)) { + return(NULL) + } else { + return(tableSubset()[idx, ]) + } + }) + + forestPlotSubset <- reactive({ + row <- selectedRow() + if (is.null(row)) { + return(NULL) + } else { + subset <- resultsHois[resultsHois$comparison == row$comparison & resultsHois$outcomeId == + row$outcomeId, ] + subset$dbOrder <- match(subset$database, databases) + subset$analysisOrder <- match(subset$description, analyses) + + subset <- subset[order(subset$dbOrder, subset$analysisOrder), ] + subset$rr[is.na(subset$seLogRr)] <- NA + subset$displayOrder <- nrow(subset):1 + return(subset) + } + }) + + output$rowIsSelected <- reactive({ + return(!is.null(selectedRow())) + }) + + outputOptions(output, ""rowIsSelected"", suspendWhenHidden = FALSE) + + balance <- reactive({ + row <- selectedRow() + if (is.null(row)) { + return(NULL) + } else { + fileName <- file.path(studyFolder, row$database, paste0(""balance_a"", + row$analysisId, + ""_t"", + row$targetId, + ""_c"", + row$comparatorId, + "".csv"")) + data <- read.csv(fileName) + data$absBeforeMatchingStdDiff <- abs(data$beforeMatchingStdDiff) + data$absAfterMatchingStdDiff <- abs(data$afterMatchingStdDiff) + return(data) + } + }) + + table1 <- reactive({ + row <- selectedRow() + if (is.null(row)) { + return(NULL) + } else { + fileName <- file.path(studyFolder, row$database, paste0(""table1_a"", + row$analysisId, + ""_t"", + row$targetId, + ""_c"", + row$comparatorId, + "".csv"")) + if (file.exists(fileName)) { + table1 <- read.csv(fileName, stringsAsFactors = FALSE) + return(table1) + } else { + return(NULL) + } + } + }) + + output$mainTable <- renderDataTable({ + table <- tableSubset()[, mainColumns] + if (nrow(table) == 0) + return(NULL) + table$rr[table$rr > 100] <- NA + table$rr <- formatC(table$rr, digits = 2, format = ""f"") + table$ci95lb <- formatC(table$ci95lb, digits = 2, format = ""f"") + table$ci95ub <- formatC(table$ci95ub, digits = 2, format = ""f"") + table$p <- formatC(table$p, digits = 2, format = ""f"") + table$calP <- formatC(table$calP, digits = 2, format = ""f"") + colnames(table) <- mainColumnNames + options <- list(pageLength = 15, + searching = FALSE, + lengthChange = TRUE, + ordering = TRUE, + paging = TRUE) + selection <- list(mode = ""single"", target = ""row"") + table <- datatable(table, + options = options, + selection = selection, + rownames = FALSE, + escape = FALSE, + class = ""stripe nowrap compact"") + return(table) + }) + + output$powerTableCaption <- renderUI({ + row <- selectedRow() + if (!is.null(row)) { + text <- ""Table 1a. Number of subjects, follow-up time (in days), number of outcome + events, and event incidence rate (IR) per 1,000 patient years (PY) in the target (%s) and + comparator (%s) group after %s, as well as the minimum detectable relative risk (MDRR). + Note that the IR does not account for any stratification."" + return(HTML(sprintf(text, row$targetName, row$comparatorName, tolower(row$psStrategy)))) + } else { + return(NULL) + } + }) + + output$powerTable <- renderTable({ + table <- selectedRow() + if (!is.null(table)) { + table$irTreated <- formatC(1000 * as.integer(table$eventsTreated)/(table$treatedDays/365.25), + digits = 2, + format = ""f"") + table$irComparator <- formatC(1000 * as.integer(table$eventsComparator)/(table$comparatorDays/365.25), + digits = 2, + format = ""f"") + + table$treated <- formatC(table$treated, big.mark = "","", format = ""d"") + table$comparator <- formatC(table$comparator, big.mark = "","", format = ""d"") + table$treatedDays <- formatC(table$treatedDays, big.mark = "","", format = ""d"") + table$comparatorDays <- formatC(table$comparatorDays, big.mark = "","", format = ""d"") + table$eventsTreated <- formatC(table$eventsTreated, big.mark = "","", format = ""d"") + table$eventsComparator <- formatC(table$eventsComparator, big.mark = "","", format = ""d"") + table$mdrr <- formatC(table$mdrr, digits = 2, format = ""f"") + table <- table[, powerColumns] + colnames(table) <- powerColumnNames + table$Events <- as.integer(table$`Target events`) + as.integer(table$`Comparator events`) + table$`Target events` <- NULL + table$`Comparator events` <- NULL + return(table) + } else { + return(table) + } + }) + + output$table1Caption <- renderUI({ + table1 <- table1() + if (!is.null(table1)) { + row <- selectedRow() + text <- ""Table 2. Select characteristics before and after %s, showing the (weighted) + percentage of subjects with the characteristics in the target (%s) and comparator (%s) group, as + well as the standardized difference of the means."" + return(HTML(sprintf(text, tolower(row$psStrategy), row$targetName, row$comparatorName))) + } else { + return(NULL) + } + }) + + output$table1Table <- renderDataTable({ + table1 <- table1() + if (!is.null(table1)) { + table1[, 1] <- gsub("" "", ""    "", table1[, 1]) + container <- htmltools::withTags(table(class = ""display"", + thead(tr(th(rowspan = 3, ""Characteristic""), + th(colspan = 3, class = ""dt-center"", paste(""Before"", ""stratification"")), + th(colspan = 3, class = ""dt-center"", paste(""After"", ""stratification""))), tr(lapply(table1[1, 2:ncol(table1)], th)), tr(lapply(table1[2, 2:ncol(table1)], th))))) + options <- list(columnDefs = list(list(className = ""dt-right"", targets = 1:6)), + searching = FALSE, + ordering = FALSE, + paging = FALSE, + bInfo = FALSE) + table1 <- datatable(table1[3:nrow(table1), + ], + options = options, + rownames = FALSE, + escape = FALSE, + container = container, + class = ""stripe nowrap compact"") + return(table1) + } else { + return(NULL) + } + }) + + output$psPlot <- renderPlot({ + row <- selectedRow() + if (!is.null(row)) { + fileName <- file.path(studyFolder, row$database, paste0(""preparedPsPlot_a"", + row$analysisId, + ""_t"", + row$targetId, + ""_c"", + row$comparatorId, + "".csv"")) + data <- read.csv(fileName) + data$GROUP <- row$targetName + data$GROUP[data$treatment == 0] <- row$comparatorName + data$GROUP <- factor(data$GROUP, levels = c(row$targetName, row$comparatorName)) + plot <- ggplot2::ggplot(data, ggplot2::aes(x = preferenceScore, + y = y, + color = GROUP, + group = GROUP, + fill = GROUP)) + + ggplot2::geom_area(position = ""identity"") + + ggplot2::scale_fill_manual(values = c(rgb(0.8, 0, 0, alpha = 0.5), + rgb(0, 0, 0.8, alpha = 0.5))) + + ggplot2::scale_color_manual(values = c(rgb(0.8, 0, 0, alpha = 0.5), + rgb(0, 0, 0.8, alpha = 0.5))) + + ggplot2::scale_x_continuous(""Preference score"", limits = c(0, 1)) + + ggplot2::scale_y_continuous(""Density"") + + ggplot2::theme(legend.title = ggplot2::element_blank(), + legend.position = ""top"", + legend.direction = ""horizontal"", + text = ggplot2::element_text(size = 15)) + return(plot) + } else { + return(NULL) + } + }) + + output$balancePlotCaption <- renderUI({ + bal <- balance() + if (!is.null(bal)) { + row <- selectedRow() + text <- ""Figure 2. Covariate balance before and after %s. Each dot represents + the standardizes difference of means for a single covariate before and after %s on the propensity + score. Move the mouse arrow over a dot for more details."" + return(HTML(sprintf(text, tolower(row$psStrategy), tolower(row$psStrategy)))) + } else { + return(NULL) + } + }) + + output$balancePlot <- renderPlot({ + bal <- balance() + if (!is.null(bal)) { + row <- selectedRow() + plotBalance(bal, + beforeLabel = paste(""Std. diff. before"", tolower(row$psStrategy)), + afterLabel = paste(""Std. diff. after"", tolower(row$psStrategy))) + } else { + return(NULL) + } + }) + + output$hoverInfoBalanceScatter <- renderUI({ + # Hover-over adapted from https://gitlab.com/snippets/16220 + bal <- balance() + if (is.null(bal)) + return(NULL) + row <- selectedRow() + hover <- input$plotHoverBalanceScatter + point <- nearPoints(bal, hover, threshold = 5, maxpoints = 1, addDist = TRUE) + if (nrow(point) == 0) + return(NULL) + + # calculate point position INSIDE the image as percent of total dimensions from left (horizontal) and + # from top (vertical) + left_pct <- (hover$x - hover$domain$left)/(hover$domain$right - hover$domain$left) + top_pct <- (hover$domain$top - hover$y)/(hover$domain$top - hover$domain$bottom) + + # calculate distance from left and bottom side of the picture in pixels + left_px <- hover$range$left + left_pct * (hover$range$right - hover$range$left) + top_px <- hover$range$top + top_pct * (hover$range$bottom - hover$range$top) + + # create style property fot tooltip background color is set so tooltip is a bit transparent z-index + # is set so we are sure are tooltip will be on top + style <- paste0(""position:absolute; z-index:100; background-color: rgba(245, 245, 245, 0.85); "", + ""left:"", + left_px - 251, + ""px; top:"", + top_px - 150, + ""px; width:500px;"") + + + # actual tooltip created as wellPanel + beforeMatchingStdDiff <- formatC(point$beforeMatchingStdDiff, digits = 2, format = ""f"") + afterMatchingStdDiff <- formatC(point$afterMatchingStdDiff, digits = 2, format = ""f"") + div(style = ""position: relative; width: 0; height: 0"", + wellPanel(style = style, p(HTML(paste0("" Covariate: "", + point$covariateName, + ""
"", + "" Std. diff before "", + tolower(row$psStrategy), + "": "", + beforeMatchingStdDiff, + ""
"", + "" Std. diff after "", + tolower(row$psStrategy), + "": "", + afterMatchingStdDiff))))) + }) + + output$negativeControlPlot <- renderPlot({ + row <- selectedRow() + if (!is.null(row)) { + ncs <- resultsControls[resultsControls$targetId == row$targetId & resultsControls$comparatorId == + row$comparatorId & resultsControls$analysisId == row$analysisId & resultsControls$database == + row$database & resultsControls$targetEffectSize == 1, ] + # null <- EmpiricalCalibration::fitMcmcNull(ncs$logRr, ncs$seLogRr) + fileName <- file.path(studyFolder, row$database, paste0(""null_a"", + row$analysisId, + ""_t"", + row$targetId, + ""_c"", + row$comparatorId, + "".rds"")) + if (file.exists(fileName)) { + null <- readRDS(fileName) + } else { + null <- NULL + } + + plot <- EmpiricalCalibration::plotCalibrationEffect(logRrNegatives = ncs$logRr, + seLogRrNegatives = ncs$seLogRr, + logRrPositives = row$logRr, + seLogRrPositives = row$seLogRr, + null = null, + xLabel = ""Hazard ratio"", + showCis = !is.null(null)) + plot <- plot + ggplot2::theme(text = ggplot2::element_text(size = 15)) + + return(plot) + } else { + return(NULL) + } + }) + + output$kaplanMeierPlot <- renderImage({ + row <- selectedRow() + if (is.null(row) || blind) { + return(NULL) + } else { + fileName <- file.path(studyFolder, row$database, paste0(""km_a"", + row$analysisId, + ""_t"", + row$targetId, + ""_c"", + row$comparatorId, + ""_o"", + row$outcomeId, + "".png"")) + if (file.exists(fileName)) { + outfile <- tempfile(fileext = "".png"") + file.copy(fileName, outfile) + # Return a list containing the filename + list(src = outfile, contentType = ""image/png"", width = ""100%"", alt = ""Kaplan Meier plot"") + } + } + }, deleteFile = TRUE) + + output$kmPlotCaption <- renderUI({ + bal <- balance() + if (!is.null(bal) && !blind) { + row <- selectedRow() + text <- ""Table 5. Kaplan Meier plot, showing survival as a function of time. This plot + is adjusted for the propensity score %s: The target curve (%s) shows the actual observed survival. The + comparator curve (%s) applies reweighting to approximate the counterfactual of what the target survival + would look like had the target cohort been exposed to the comparator instead. The shaded area denotes + the 95 percent confidence interval."" + return(HTML(sprintf(text, tolower(row$psStrategy), row$targetDrug, row$comparatorDrug))) + } else { + return(NULL) + } + }) + + output$forestPlot <- renderPlot({ + row <- selectedRow() + if (!is.null(row)) { + subset <- forestPlotSubset() + return(plotForest(subset, row)) + } + return(NULL) + }) + + output$hoverInfoForestPlot <- renderUI({ + # Hover-over adapted from https://gitlab.com/snippets/16220 + subset <- forestPlotSubset() + if (is.null(subset)) + return(NULL) + hover <- input$plotHoverForestPlot + point <- nearPoints(subset, hover, threshold = 5, maxpoints = 1, addDist = TRUE) + if (nrow(point) == 0) + return(NULL) + # calculate point position INSIDE the image as percent of total dimensions from left (horizontal) and + # from top (vertical) + left_pct <- (hover$x - hover$domain$left)/(hover$domain$right - hover$domain$left) + top_pct <- (hover$domain$top - hover$y)/(hover$domain$top - hover$domain$bottom) + + # calculate distance from left and bottom side of the picture in pixels + left_px <- hover$range$left + left_pct * (hover$range$right - hover$range$left) + top_px <- hover$range$top + top_pct * (hover$range$bottom - hover$range$top) + + # create style property fot tooltip background color is set so tooltip is a bit transparent z-index + # is set so we are sure are tooltip will be on top + style <- paste0(""position:absolute; z-index:100; background-color: rgba(245, 245, 245, 0.85); "", + ""left:100px; top:"", + top_px - 200, + ""px; width:500px;"") + + + # actual tooltip created as wellPanel + hr <- sprintf(""%.2f (%.2f - %.2f)"", point$rr, point$ci95lb, point$ci95ub) + div(style = ""position: relative; width: 0; height: 0"", + wellPanel(style = style, p(HTML(paste0("" Analysis: "", + point$description, + ""
"", + "" Database: "", + point$database, + ""
"", + "" Harard ratio (95% CI): "", + hr, + ""
""))))) + }) + + observeEvent(input$dbInfo, { + showModal(modalDialog(title = ""Data sources"", + easyClose = TRUE, + footer = NULL, + size = ""l"", + HTML(dbInfoHtml))) + }) + + observeEvent(input$comparisonsInfo, { + showModal(modalDialog(title = ""Comparisons"", + easyClose = TRUE, + footer = NULL, + size = ""l"", + HTML(comparisonsInfoHtml))) + }) + + observeEvent(input$outcomesInfo, { + showModal(modalDialog(title = ""Outcomes"", + easyClose = TRUE, + footer = NULL, + size = ""l"", + HTML(outcomesInfoHtml))) + }) + + observeEvent(input$cvdInfo, { + showModal(modalDialog(title = ""Established cardiovascular disease (CVD)"", + easyClose = TRUE, + footer = NULL, + size = ""l"", + HTML(cvdInfoHtml))) + }) + + observeEvent(input$priorExposureInfo, { + showModal(modalDialog(title = ""Prior exposure"", + easyClose = TRUE, + footer = NULL, + size = ""l"", + HTML(priorExposureInfoHtml))) + }) + + observeEvent(input$tarInfo, { + showModal(modalDialog(title = ""Time-at-risk"", + easyClose = TRUE, + footer = NULL, + size = ""l"", + HTML(tarInfoHtml))) + }) + + observeEvent(input$eventInfo, { + showModal(modalDialog(title = ""Time-at-risk"", + easyClose = TRUE, + footer = NULL, + size = ""l"", + HTML(eventInfoHtml))) + }) + + observeEvent(input$psInfo, { + showModal(modalDialog(title = ""Time-at-risk"", + easyClose = TRUE, + footer = NULL, + size = ""l"", + HTML(psInfoHtml))) + }) + + + + +}) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AlendronateVsRaloxifene/inst/shiny/EvidenceExplorer/functions.R",".R","4049","73","plotBalance <- function(balance, beforeLabel = ""Before matching"", afterLabel = ""After matching"") { + limits <- c(min(c(balance$absBeforeMatchingStdDiff, balance$absAfterMatchingStdDiff), + na.rm = TRUE), + max(c(balance$absBeforeMatchingStdDiff, balance$absAfterMatchingStdDiff), + na.rm = TRUE)) + plot <- ggplot2::ggplot(balance, + ggplot2::aes(x = absBeforeMatchingStdDiff, y = absAfterMatchingStdDiff)) + + ggplot2::geom_point(color = rgb(0, 0, 0.8, alpha = 0.3), shape = 16, size = 2) + + ggplot2::geom_abline(slope = 1, intercept = 0, linetype = ""dashed"") + + ggplot2::geom_hline(yintercept = 0) + + ggplot2::geom_vline(xintercept = 0) + + ggplot2::scale_x_continuous(beforeLabel, limits = limits) + + ggplot2::scale_y_continuous(afterLabel, limits = limits) + + ggplot2::theme(text = ggplot2::element_text(size = 15)) + return(plot) +} + +plotForest <- function(subset, row) { + comparatorName <- row$comparatorName + breaks <- c(0.1, 0.25, 0.5, 1, 2, 4, 6, 8, 10) + labels <- c(0.1, + paste(""0.25\nFavors"", row$targetName), + 0.5, + 1, + 2, + paste(""4\nFavors"", row$comparatorName), + 6, + 8, + 10) + col <- c(rgb(0, 0, 0.8, alpha = 1), rgb(0.8, 0.4, 0, alpha = 1)) + colFill <- c(rgb(0, 0, 1, alpha = 0.5), rgb(1, 0.4, 0, alpha = 0.5)) + highlight <- subset[subset$targetId == row$targetId & subset$comparatorId == row$comparatorId & subset$outcomeId == + row$outcomeId & subset$analysisId == row$analysisId & subset$database == row$database, ] + plot <- ggplot2::ggplot(subset, ggplot2::aes(x = rr, + y = displayOrder, + xmin = ci95lb, + xmax = ci95ub, + fill = description), environment = environment()) + + ggplot2::geom_vline(xintercept = breaks, colour = ""#AAAAAA"", lty = 1, size = 0.2) + + ggplot2::geom_vline(xintercept = 1, colour = ""#000000"", lty = 1, size = 0.5) + + ggplot2::geom_errorbarh(height = 0.2, size = 1, alpha = 0.7, aes(colour = description)) + + ggplot2::geom_point(shape = 16, size = 3, alpha = 0.7, aes(colour = description)) + + ggplot2::geom_errorbarh(height = 0.2, + alpha = 1, + size = 1, + color = rgb(0, 0, 0), + data = highlight, + show.legend = FALSE) + + ggplot2::geom_point(shape = 16, + size = 3, + color = rgb(0, 0, 0), + alpha = 1, + data = highlight, + show.legend = FALSE) + + ggplot2::coord_cartesian(xlim = c(0.1, 10)) + + ggplot2::scale_x_continuous(""Hazard ratio"", + trans = ""log10"", + breaks = breaks, + labels = labels) + + ggplot2::facet_grid(database ~ ., scales = ""free_y"", space = ""free"") + + ggplot2::labs(color = ""description"", fill = ""description"") + + ggplot2::theme(text = ggplot2::element_text(size = 15), + panel.grid.minor = ggplot2::element_blank(), + panel.background = ggplot2::element_rect(fill = ""#FAFAFA"", colour = NA), + panel.grid.major = ggplot2::element_line(colour = ""#EEEEEE""), + axis.ticks = ggplot2::element_blank(), + axis.title.y = ggplot2::element_blank(), + axis.title.x = ggplot2::element_blank(), + axis.text.y = ggplot2::element_blank(), + legend.position = ""top"") + return(plot) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AlendronateVsRaloxifene/inst/shiny/EvidenceExplorer/ui.R",".R","5109","72","library(shiny) +library(DT) + +shinyUI(fluidPage(style = 'width:1500px;', + titlePanel(paste(""Evidence Explorer"", if(blind){""*Blinded*""}else{""""})), + tags$head(tags$style(type=""text/css"", "" + #loadmessage { + position: fixed; + top: 0px; + left: 0px; + width: 100%; + padding: 5px 0px 5px 0px; + text-align: center; + font-weight: bold; + font-size: 100%; + color: #000000; + background-color: #ADD8E6; + z-index: 105; + } + "")), + conditionalPanel(condition=""$('html').hasClass('shiny-busy')"", + tags$div(""Procesing..."",id=""loadmessage"")), + + fluidRow( + column(3, + selectInput(""comparison"", ""Comparison:"", comparisons), + selectInput(""outcome"", ""Outcome:"", outcomes), + checkboxGroupInput(""analysis"", ""Analysis"", analyses, selected = analyses), + checkboxGroupInput(""db"", ""Database:"", databases, selected = databases) + ), + column(9, + dataTableOutput(""mainTable""), + conditionalPanel(""output.rowIsSelected == true"", + tabsetPanel(id = ""tabsetPanel"", + tabPanel(""Power"", + uiOutput(""powerTableCaption""), + tableOutput(""powerTable"")), + tabPanel(""Population characteristics"", + uiOutput(""table1Caption""), + dataTableOutput(""table1Table"")), + tabPanel(""Propensity scores"", + plotOutput(""psPlot""), + div(strong(""Figure 1.""),""Preference score distribution. The preference score is a transformation of the propensity score + that adjusts for differences in the sizes of the two treatment groups. A higher overlap indicates subjects in the + two groups were more similar in terms of their predicted probability of receiving one treatment over the other."")), + tabPanel(""Covariate balance"", + uiOutput(""hoverInfoBalanceScatter""), + plotOutput(""balancePlot"", + hover = hoverOpts(""plotHoverBalanceScatter"", delay = 100, delayType = ""debounce"")), + uiOutput(""balancePlotCaption"")), + tabPanel(""Systematic error"", + plotOutput(""negativeControlPlot""), + div(strong(""Figure 3.""),""Negative control estimates. Each blue dot represents the estimated hazard + ratio and standard error (related to the width of the confidence interval) of each of the negative + control outcomes. The yellow diamond indicated the outcome of interest. Estimates below the dashed + line have uncalibrated p < .05. Estimates in the orange area have calibrated p < .05. The red band + indicated the 95% credible interval around the boundary of the orange area. "")), + tabPanel(""Parameter sensitivity"", + uiOutput(""hoverInfoForestPlot""), + plotOutput(""forestPlot"", hover = hoverOpts(""plotHoverForestPlot"", delay = 100, delayType = ""debounce"")), + div(strong(""Figure 4.""),""Forest plot of effect estimates from all sensitivity analyses across databases and time-at-risk periods. Black indicates the estimate selected by the user."")), + tabPanel(""Kaplan-Meier"", + imageOutput(""kaplanMeierPlot"", height = 550), + uiOutput(""kmPlotCaption"")) + ) + ) + + ) + ) +) +) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AlendronateVsRaloxifene/R/Main.R",".R","8062","153","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of AlendronateVsRaloxifene +# +# 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. + +#' Execute the Study +#' +#' @details +#' This function executes the Alendronate Vs Raloxifene study +#' +#' The \code{createCohorts}, \code{synthesizePositiveControls}, \code{runAnalyses}, and \code{runDiagnostics} arguments +#' are intended to be used to run parts of the full study at a time, but none of the parts are considerd to be optional. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param cohortDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param cohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/). Do not use a folder on a network drive since this greatly impacts +#' performance. +#' @param createCohorts Create the cohortTable table with the exposure and outcome cohorts? +#' @param synthesizePositiveControls Should positive controls be synthesized? +#' @param runAnalyses Perform the cohort method analyses? +#' @param runDiagnostics Compute study diagnostics? +#' @param packageResults Should results be packaged for later sharing? +#' @param maxCores How many parallel cores should be used? If more cores are made available +#' this can speed up the analyses. +#' @param minCellCount The minimum number of subjects contributing to a count before it can be included +#' in packaged results. +#' +#' @examples +#' \dontrun{ +#' connectionDetails <- createConnectionDetails(dbms = ""postgresql"", +#' user = ""joe"", +#' password = ""secret"", +#' server = ""myserver"") +#' +#' execute(connectionDetails, +#' cdmDatabaseSchema = ""cdm_data"", +#' cohortDatabaseSchema = ""study_results"", +#' cohortTable = ""cohort"", +#' oracleTempSchema = NULL, +#' outputFolder = ""c:/temp/study_results"", +#' maxCores = 4) +#' } +#' +#' @export +execute <- function(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema = cdmDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = cohortDatabaseSchema, + outputFolder = outputFolder, + createCohorts = TRUE, + synthesizePositiveControls = TRUE, + runAnalyses = TRUE, + runDiagnostics = TRUE, + packageResults = TRUE, + maxCores = 4, + minCellCount= 5) { + if (!file.exists(outputFolder)) + dir.create(outputFolder, recursive = TRUE) + + OhdsiRTools::addDefaultFileLogger(file.path(outputFolder, ""log.txt"")) + + if (createCohorts) { + OhdsiRTools::logInfo(""Creating exposure and outcome cohorts"") + createCohorts(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder) + } + + if (synthesizePositiveControls) { + OhdsiRTools::logInfo(""Synthesizing positive controls"") + synthesizePositiveControls(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder, + maxCores = maxCores) + } + + if (runAnalyses) { + OhdsiRTools::logInfo(""Running analyses"") + cmOutputFolder <- file.path(outputFolder, ""cmOutput"") + if (!file.exists(cmOutputFolder)) + dir.create(cmOutputFolder) + cmAnalysisListFile <- system.file(""settings"", + ""cmAnalysisList.json"", + package = ""AlendronateVsRaloxifene"") + cmAnalysisList <- CohortMethod::loadCmAnalysisList(cmAnalysisListFile) + dcosList <- createTcos(outputFolder = outputFolder) + results <- CohortMethod::runCmAnalyses(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + exposureDatabaseSchema = cohortDatabaseSchema, + exposureTable = cohortTable, + outcomeDatabaseSchema = cohortDatabaseSchema, + outcomeTable = cohortTable, + outputFolder = cmOutputFolder, + oracleTempSchema = oracleTempSchema, + cmAnalysisList = cmAnalysisList, + drugComparatorOutcomesList = dcosList, + getDbCohortMethodDataThreads = min(3, maxCores), + createStudyPopThreads = min(3, maxCores), + createPsThreads = max(1, round(maxCores/10)), + psCvThreads = min(10, maxCores), + computeCovarBalThreads = min(3, maxCores), + trimMatchStratifyThreads = min(10, maxCores), + fitOutcomeModelThreads = max(1, round(maxCores/4)), + outcomeCvThreads = min(4, maxCores), + refitPsForEveryOutcome = FALSE) + } + if (runDiagnostics) { + OhdsiRTools::logInfo(""Running diagnostics"") + generateDiagnostics(outputFolder = outputFolder) + } + if (packageResults) { + OhdsiRTools::logInfo(""Packaging results"") + packageResults(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + outputFolder = outputFolder, + minCellCount = minCellCount) + } + + + invisible(NULL) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AlendronateVsRaloxifene/R/CreateTcos.R",".R","2239","41","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of AlendronateVsRaloxifene +# +# 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. + +createTcos <- function(outputFolder) { + pathToCsv <- system.file(""settings"", ""TcosOfInterest.csv"", package = ""AlendronateVsRaloxifene"") + tcosOfInterest <- read.csv(pathToCsv, stringsAsFactors = FALSE) + allControlsFile <- file.path(outputFolder, ""AllControls.csv"") + allControls <- read.csv(allControlsFile) + dcosList <- list() + tcs <- unique(rbind(tcosOfInterest[, c(""targetId"", ""comparatorId"")], + allControls[, c(""targetId"", ""comparatorId"")])) + for (i in 1:nrow(tcs)) { + targetId <- tcs$targetId[i] + comparatorId <- tcs$comparatorId[i] + outcomeIds <- as.character(tcosOfInterest$outcomeIds[tcosOfInterest$targetId == targetId & tcosOfInterest$comparatorId == comparatorId]) + outcomeIds <- as.numeric(strsplit(outcomeIds, split = "";"")[[1]]) + outcomeIds <- c(outcomeIds, allControls$outcomeId[allControls$targetId == targetId & allControls$comparatorId == comparatorId]) + excludeConceptIds <- as.character(tcosOfInterest$excludedCovariateConceptIds[tcosOfInterest$targetId == targetId & tcosOfInterest$comparatorId == comparatorId]) + excludeConceptIds <- as.numeric(strsplit(excludeConceptIds, split = "";"")[[1]]) + dcos <- CohortMethod::createDrugComparatorOutcomes(targetId = targetId, + comparatorId = comparatorId, + outcomeIds = outcomeIds, + excludedCovariateConceptIds = excludeConceptIds) + dcosList[[length(dcosList) + 1]] <- dcos + } + return(dcosList) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AlendronateVsRaloxifene/R/CreateCohorts.R",".R","3576","69","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of AlendronateVsRaloxifene +# +# 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. + +.createCohorts <- function(connection, + cdmDatabaseSchema, + vocabularyDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable, + oracleTempSchema, + outputFolder) { + + # Create study cohort table structure: + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""CreateCohortTable.sql"", + packageName = ""AlendronateVsRaloxifene"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + cohort_database_schema = cohortDatabaseSchema, + cohort_table = cohortTable) + DatabaseConnector::executeSql(connection, sql, progressBar = FALSE, reportOverallTime = FALSE) + + + + # Instantiate cohorts: + pathToCsv <- system.file(""settings"", ""CohortsToCreate.csv"", package = ""AlendronateVsRaloxifene"") + cohortsToCreate <- read.csv(pathToCsv) + for (i in 1:nrow(cohortsToCreate)) { + writeLines(paste(""Creating cohort:"", cohortsToCreate$name[i])) + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = paste0(cohortsToCreate$name[i], "".sql""), + packageName = ""AlendronateVsRaloxifene"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + vocabulary_database_schema = vocabularyDatabaseSchema, + + target_database_schema = cohortDatabaseSchema, + target_cohort_table = cohortTable, + target_cohort_id = cohortsToCreate$cohortId[i]) + DatabaseConnector::executeSql(connection, sql) + } + + # Fetch cohort counts: + sql <- ""SELECT cohort_definition_id, COUNT(*) AS count FROM @cohort_database_schema.@cohort_table GROUP BY cohort_definition_id"" + sql <- SqlRender::renderSql(sql, + cohort_database_schema = cohortDatabaseSchema, + cohort_table = cohortTable)$sql + sql <- SqlRender::translateSql(sql, targetDialect = attr(connection, ""dbms""))$sql + counts <- DatabaseConnector::querySql(connection, sql) + names(counts) <- SqlRender::snakeCaseToCamelCase(names(counts)) + counts <- merge(counts, data.frame(cohortDefinitionId = cohortsToCreate$cohortId, + cohortName = cohortsToCreate$name)) + write.csv(counts, file.path(outputFolder, ""CohortCounts.csv"")) + + +} + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AlendronateVsRaloxifene/R/SynthesizePositiveControls.R",".R","9201","143","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of AlendronateVsRaloxifene +# +# 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. + +#' Synthesize positive controls +#' +#' @details +#' This function will synthesize positve controls based on the negative controls. The simulated outcomes +#' will be added to the cohort table. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param cohortDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param cohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' @param maxCores How many parallel cores should be used? If more cores are made available +#' this can speed up the analyses. +#' +#' @export +synthesizePositiveControls <- function(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable, + oracleTempSchema, + outputFolder, + maxCores = 1) { + # Set to TRUE if you don't want to use synthetic positive controls in your study: + skipSynthesis <- FALSE + + if (!skipSynthesis) { + synthesisFolder <- file.path(outputFolder, ""positiveControlSynthesis"") + if (!file.exists(synthesisFolder)) + dir.create(synthesisFolder) + + synthesisSummaryFile <- file.path(outputFolder, ""SynthesisSummary.csv"") + if (!file.exists(synthesisSummaryFile)) { + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""AlendronateVsRaloxifene"") + negativeControls <- read.csv(pathToCsv) + exposureOutcomePairs <- data.frame(exposureId = negativeControls$targetId, + outcomeId = negativeControls$outcomeId) + exposureOutcomePairs <- unique(exposureOutcomePairs) + prior = Cyclops::createPrior(""laplace"", exclude = 0, useCrossValidation = TRUE) + control = Cyclops::createControl(cvType = ""auto"", + startingVariance = 0.01, + noiseLevel = ""quiet"", + cvRepetitions = 1, + threads = min(c(10, maxCores))) + covariateSettings <- FeatureExtraction::createCovariateSettings(useDemographicsAgeGroup = TRUE, + useDemographicsGender = TRUE, + useDemographicsIndexYear = TRUE, + useDemographicsIndexMonth = TRUE, + useConditionGroupEraLongTerm = TRUE, + useDrugGroupEraLongTerm = TRUE, + useProcedureOccurrenceLongTerm = TRUE, + useMeasurementLongTerm = TRUE, + useObservationLongTerm = TRUE, + useCharlsonIndex = TRUE, + useDcsi = TRUE, + useChads2Vasc = TRUE, + longTermStartDays = 365, + endDays = 0) + result <- MethodEvaluation::injectSignals(connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + exposureDatabaseSchema = cohortDatabaseSchema, + exposureTable = cohortTable, + outcomeDatabaseSchema = cohortDatabaseSchema, + outcomeTable = cohortTable, + outputDatabaseSchema = cohortDatabaseSchema, + outputTable = cohortTable, + createOutputTable = FALSE, + outputIdOffset = 10000, + exposureOutcomePairs = exposureOutcomePairs, + firstExposureOnly = TRUE, + firstOutcomeOnly = TRUE, + removePeopleWithPriorOutcomes = TRUE, + modelType = ""survival"", + washoutPeriod = 365, + riskWindowStart = 0, + riskWindowEnd = 9999, + addExposureDaysToEnd = FALSE, + effectSizes = c(1.5, 2, 4), + precision = 0.01, + prior = prior, + control = control, + maxSubjectsForModel = 250000, + minOutcomeCountForModel = 50, + minOutcomeCountForInjection = 25, + workFolder = synthesisFolder, + modelThreads = max(1, round(maxCores/8)), + generationThreads = min(6, maxCores), + covariateSettings = covariateSettings) + write.csv(result, synthesisSummaryFile, row.names = FALSE) + } + OhdsiRTools::logTrace(""Merging positive with negative controls "") + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""AlendronateVsRaloxifene"") + negativeControls <- read.csv(pathToCsv) + + synthesisSummary <- read.csv(synthesisSummaryFile) + synthesisSummary$targetId <- synthesisSummary$exposureId + synthesisSummary <- merge(synthesisSummary, negativeControls) + synthesisSummary <- synthesisSummary[synthesisSummary$trueEffectSize != 0, ] + synthesisSummary$outcomeName <- paste0(synthesisSummary$OutcomeName, "", RR="", synthesisSummary$targetEffectSize) + synthesisSummary$oldOutcomeId <- synthesisSummary$outcomeId + synthesisSummary$outcomeId <- synthesisSummary$newOutcomeId + } + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""AlendronateVsRaloxifene"") + negativeControls <- read.csv(pathToCsv) + negativeControls$targetEffectSize <- 1 + negativeControls$trueEffectSize <- 1 + negativeControls$trueEffectSizeFirstExposure <- 1 + negativeControls$oldOutcomeId <- negativeControls$outcomeId + if (skipSynthesis) { + allControls <- negativeControls + } else { + allControls <- rbind(negativeControls, synthesisSummary[, names(negativeControls)]) + } + write.csv(allControls, file.path(outputFolder, ""AllControls.csv""), row.names = FALSE) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AlendronateVsRaloxifene/R/CreateAllCohorts.R",".R","6243","117","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of AlendronateVsRaloxifene +# +# 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. + +#' Create the exposure and outcome cohorts +#' +#' @details +#' This function will create the exposure and outcome cohorts following the definitions included in +#' this package. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param cohortDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param cohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' +#' @export +createCohorts <- function(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable, + oracleTempSchema, + outputFolder) { + if (!file.exists(outputFolder)) + dir.create(outputFolder) + + conn <- DatabaseConnector::connect(connectionDetails) + + .createCohorts(connection = conn, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder) + + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""AlendronateVsRaloxifene"") + negativeControls <- read.csv(pathToCsv) + + OhdsiRTools::logInfo(""Creating negative control outcome cohorts"") + negativeControlOutcomes <- negativeControls[negativeControls$type == ""Outcome"", ] + sql <- SqlRender::loadRenderTranslateSql(""NegativeControlOutcomes.sql"", + ""AlendronateVsRaloxifene"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = cohortDatabaseSchema, + target_cohort_table = cohortTable, + outcome_ids = unique(negativeControlOutcomes$outcomeId)) + DatabaseConnector::executeSql(conn, sql) + + # Check number of subjects per cohort: + OhdsiRTools::logInfo(""Counting cohorts"") + sql <- SqlRender::loadRenderTranslateSql(""GetCounts.sql"", + ""AlendronateVsRaloxifene"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + work_database_schema = cohortDatabaseSchema, + study_cohort_table = cohortTable) + counts <- DatabaseConnector::querySql(conn, sql) + colnames(counts) <- SqlRender::snakeCaseToCamelCase(colnames(counts)) + counts <- addCohortNames(counts) + write.csv(counts, file.path(outputFolder, ""CohortCounts.csv""), row.names = FALSE) + + DatabaseConnector::disconnect(conn) +} + +addCohortNames <- function(data, IdColumnName = ""cohortDefinitionId"", nameColumnName = ""cohortName"") { + pathToCsv <- system.file(""settings"", ""CohortsToCreate.csv"", package = ""AlendronateVsRaloxifene"") + cohortsToCreate <- read.csv(pathToCsv) + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""AlendronateVsRaloxifene"") + negativeControls <- read.csv(pathToCsv) + + idToName <- data.frame(cohortId = c(cohortsToCreate$cohortId, + negativeControls$targetId, + negativeControls$comparatorId, + negativeControls$outcomeId), + cohortName = c(as.character(cohortsToCreate$name), + as.character(negativeControls$targetName), + as.character(negativeControls$comparatorName), + as.character(negativeControls$outcomeName))) + idToName <- idToName[order(idToName$cohortId), ] + idToName <- idToName[!duplicated(idToName$cohortId), ] + names(idToName)[1] <- IdColumnName + names(idToName)[2] <- nameColumnName + data <- merge(data, idToName, all.x = TRUE) + # Change order of columns: + idCol <- which(colnames(data) == IdColumnName) + if (idCol < ncol(data) - 1) { + data <- data[, c(1:idCol, ncol(data) , (idCol+1):(ncol(data)-1))] + } + return(data) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AlendronateVsRaloxifene/R/ShinyApps.R",".R","4326","98","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of AlendronateVsRaloxifene +# +# 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. + +#' Prepare results for the Evidence Explorer Shiny app. +#' +#' @param studyFolder The root folder containing the study results. The app expects each database to have a subfolder in this +#' folder, containing the packaged results. +#' +#' @export +prepareForEvidenceExplorer <- function(studyFolder) { + databases <- list.files(studyFolder, include.dirs = TRUE) + for (database in databases) { + OhdsiRTools::logInfo(""Prepraring results from database "", database) + fileName <- file.path(studyFolder, database, ""AllEstimates.csv"") + estimates <- read.csv(fileName, stringsAsFactors = FALSE) + tcas <- unique(estimates[, c(""targetId"", ""comparatorId"", ""analysisId"")]) + for (i in 1:nrow(tcas)) { + targetId <- tcas$targetId[i] + comparatorId <- tcas$comparatorId[i] + analysisId <- tcas$analysisId[i] + ncs <- estimates[estimates$targetId == targetId & + estimates$comparatorId == comparatorId & + estimates$analysisId == analysisId & + estimates$targetEffectSize == 1,] + null <- EmpiricalCalibration::fitMcmcNull(ncs$logRr, ncs$seLogRr) + fileName <- file.path(studyFolder, database, paste0(""null_a"",analysisId,""_t"",targetId,""_c"",comparatorId,"".rds"")) + saveRDS(null, fileName) + idx <- estimates$targetId == targetId & + estimates$comparatorId == comparatorId & + estimates$analysisId == analysisId + calP <- EmpiricalCalibration::calibrateP(null = null, + logRr = estimates$logRr[idx], + seLogRr = estimates$seLogRr[idx]) + estimates$calP[idx] <- calP$p + } + fileName <- file.path(studyFolder, database, ""AllCalibratedEstimates.rds"") + saveRDS(estimates, fileName) + } +} + + +#' Launch the SqlRender Developer Shiny app +#' +#' @param studyFolder The root folder containing the study results. The app expects each database to have a subfolder in this +#' folder, containing the packaged results. +#' @param blind Should the user be blinded to the main results? +#' @param launch.browser Should the app be launched in your default browser, or in a Shiny window. +#' Note: copying to clipboard will not work in a Shiny window. +#' +#' @details +#' Launches a Shiny app that allows the user to explore the evidence +#' +#' @export +launchEvidenceExplorer <- function(studyFolder, blind = TRUE, launch.browser = TRUE) { + ensure_installed(""DT"") + appDir <- system.file(""shiny"", ""EvidenceExplorer"", package = ""AlendronateVsRaloxifene"") + .GlobalEnv$shinySettings <- list(studyFolder = studyFolder, blind = blind) + on.exit(rm(shinySettings, envir=.GlobalEnv)) + shiny::runApp(appDir) +} + +# Borrowed from devtools: https://github.com/hadley/devtools/blob/ba7a5a4abd8258c52cb156e7b26bb4bf47a79f0b/R/utils.r#L44 +is_installed <- function (pkg, version = 0) { + installed_version <- tryCatch(utils::packageVersion(pkg), + error = function(e) NA) + !is.na(installed_version) && installed_version >= version +} + +# Borrowed and adapted from devtools: https://github.com/hadley/devtools/blob/ba7a5a4abd8258c52cb156e7b26bb4bf47a79f0b/R/utils.r#L74 +ensure_installed <- function(pkg) { + if (!is_installed(pkg)) { + msg <- paste0(sQuote(pkg), "" must be installed for this functionality."") + if (interactive()) { + message(msg, ""\nWould you like to install it?"") + if (menu(c(""Yes"", ""No"")) == 1) { + install.packages(pkg) + } else { + stop(msg, call. = FALSE) + } + } else { + stop(msg, call. = FALSE) + } + } +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AlendronateVsRaloxifene/R/SubmitResults.R",".R","2018","50","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of AlendronateVsRaloxifene +# +# 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. + +#' Submit the study results to the study coordinating center +#' +#' @details +#' This will upload the file \code{StudyResults.zip} to the study coordinating center using Amazon S3. +#' This requires an active internet connection. +#' +#' @param outputFolder Name of local folder where the results were generated; make sure to use forward slashes +#' (/). Do not use a folder on a network drive since this greatly impacts +#' performance. +#' @param key The key string as provided by the study coordinator +#' @param secret The secret string as provided by the study coordinator +#' +#' @return +#' TRUE if the upload was successful. +#' +#' @export +submitResults <- function(outputFolder, key, secret) { + zipName <- file.path(outputFolder, ""StudyResults.zip"") + if (!file.exists(zipName)) { + stop(paste(""Cannot find file"", zipName)) + } + writeLines(paste0(""Uploading file '"", zipName, ""' to study coordinating center"")) + result <- OhdsiSharing::putS3File(file = zipName, + bucket = ""ohdsi-study-skeleton"", + key = key, + secret = secret) + if (result) { + writeLines(""Upload complete"") + } else { + writeLines(""Upload failed. Please contact the study coordinator"") + } + invisible(result) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AlendronateVsRaloxifene/R/PackageResults.R",".R","10900","184","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of AlendronateVsRaloxifene +# +# 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. + +#' Package the results for sharing with OHDSI researchers +#' +#' @details +#' This function packages the results. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' @param minCellCount The minimum number of subjects contributing to a count before it can be included in the results. +#' +#' @export +packageResults <- function(connectionDetails, cdmDatabaseSchema, outputFolder, minCellCount = 5) { + exportFolder <- file.path(outputFolder, ""export"") + if (!file.exists(exportFolder)) + dir.create(exportFolder) + diagnosticsFolder <- file.path(outputFolder, ""diagnostics"") + cmOutputFolder <- file.path(outputFolder, ""cmOutput"") + + createMetaData(connectionDetails, cdmDatabaseSchema, exportFolder) + + # Copy MDRR, enforcing minCellCount ----------------------------------------------------------------- + fileName <- file.path(diagnosticsFolder, ""mdrrs.csv"") + mdrrs <- read.csv(fileName) + mdrrs$totalOutcomes[mdrrs$totalOutcomes < minCellCount] <- paste0(""<"", minCellCount) + mdrrs$targetPersons[mdrrs$targetPersons < minCellCount] <- paste0(""<"", minCellCount) + mdrrs$comparatorPersons[mdrrs$comparatorPersons < minCellCount] <- paste0(""<"", minCellCount) + fileName <- file.path(exportFolder, ""mdrrs.csv"") + write.csv(mdrrs, fileName, row.names = FALSE) + + # Copy balance files, dropping person counts -------------------------------------------------------- + files <- list.files(path = diagnosticsFolder, pattern = ""^balance.*csv$"") + for (file in files) { + balance <- read.csv(file.path(diagnosticsFolder, file)) + balance$beforeMatchingSumTreated <- NULL + balance$beforeMatchingSumComparator <- NULL + balance$afterMatchingSumTreated <- NULL + balance$afterMatchingSumComparator <- NULL + write.csv(balance, file.path(exportFolder, file), row.names = FALSE) + } + + # Copy prepared PS plots to export folder ---------------------------------------------------------- + files <- list.files(path = diagnosticsFolder, pattern = ""^preparedPsPlot.*csv$"", full.names = TRUE) + file.copy(from = files, to = exportFolder) + + # Copy tables 1 to export folder ------------------------------------------------------------------- + files <- list.files(path = diagnosticsFolder, pattern = ""^table1.*csv$"", full.names = TRUE) + file.copy(from = files, to = exportFolder) + + # All effect size estimates ------------------------------------------------------------------------ + reference <- readRDS(file.path(cmOutputFolder, ""outcomeModelReference.rds"")) + analysisSummary <- CohortMethod::summarizeAnalyses(reference) + analysisSummary <- addCohortNames(analysisSummary, ""outcomeId"", ""outcomeName"") + analysisSummary <- addCohortNames(analysisSummary, ""targetId"", ""targetName"") + analysisSummary <- addCohortNames(analysisSummary, ""comparatorId"", ""comparatorName"") + allControlsFile <- file.path(outputFolder, ""AllControls.csv"") + allControls <- read.csv(allControlsFile) + allControls$temp <- allControls$outcomeName + analysisSummary <- merge(analysisSummary, allControls[, c(""targetId"", ""comparatorId"", ""outcomeId"", ""oldOutcomeId"", ""temp"", ""targetEffectSize"", ""trueEffectSize"")], all.x = TRUE) + analysisSummary$outcomeName <- as.character(analysisSummary$outcomeName) + analysisSummary$temp <- as.character(analysisSummary$temp) + analysisSummary$outcomeName[!is.na(analysisSummary$temp)] <- analysisSummary$temp[!is.na(analysisSummary$temp)] + cmAnalysisList <- CohortMethod::loadCmAnalysisList(system.file(""settings"", ""cmAnalysisList.json"", package = ""AlendronateVsRaloxifene"")) + for (i in 1:length(cmAnalysisList)) { + analysisSummary$description[analysisSummary$analysisId == cmAnalysisList[[i]]$analysisId] <- cmAnalysisList[[i]]$description + } + analysisSummary$treated[analysisSummary$treated < minCellCount] <- paste0(""<"", minCellCount) + analysisSummary$comparator[analysisSummary$comparator < minCellCount] <- paste0(""<"", minCellCount) + analysisSummary$eventsTreated[analysisSummary$eventsTreated < minCellCount] <- paste0(""<"", minCellCount) + analysisSummary$eventsComparator[analysisSummary$eventsComparator < minCellCount] <- paste0(""<"", minCellCount) + write.csv(analysisSummary, file.path(exportFolder, ""AllEstimates.csv""), row.names = FALSE) + + pathToCsv <- system.file(""settings"", ""TcosOfInterest.csv"", package = ""AlendronateVsRaloxifene"") + tcosOfInterest <- read.csv(pathToCsv, stringsAsFactors = FALSE) + tcsOfInterest <- unique(tcosOfInterest[, c(""targetId"", ""comparatorId"")]) + for (i in 1:nrow(tcsOfInterest)) { + targetId <- tcsOfInterest$targetId[i] + comparatorId <- tcsOfInterest$comparatorId[i] + targetLabel <- tcosOfInterest$targetName[tcosOfInterest$targetId == targetId & tcosOfInterest$comparatorId == comparatorId][1] + comparatorLabel <- tcosOfInterest$comparatorName[tcosOfInterest$targetId == targetId & tcosOfInterest$comparatorId == comparatorId][1] + outcomeIds <- as.character(tcosOfInterest$outcomeIds[tcosOfInterest$targetId == targetId & tcosOfInterest$comparatorId == comparatorId]) + outcomeIds <- as.numeric(strsplit(outcomeIds, split = "";"")[[1]]) + for (analysisId in unique(reference$analysisId)) { + for (outcomeId in outcomeIds) { + strataFile <- reference$strataFile[reference$analysisId == analysisId & + reference$targetId == targetId & + reference$comparatorId == comparatorId & + reference$outcomeId == outcomeId] + if (strataFile == """") { + strataFile <- reference$studyPopFile[reference$analysisId == analysisId & + reference$targetId == targetId & + reference$comparatorId == comparatorId & + reference$outcomeId == outcomeId] + } + population <- readRDS(strataFile) + fileName <- file.path(exportFolder, paste0(""km_a"",analysisId,""_t"",targetId,""_c"",comparatorId, ""_o"", outcomeId, "".png"")) + CohortMethod::plotKaplanMeier(population = population, + treatmentLabel = targetLabel, + comparatorLabel = comparatorLabel, + fileName = fileName) + } + } + } + + # Attition tables ----------------------------------------------------------------------------------- + files <- list.files(path = diagnosticsFolder, pattern = ""^attritionTable.*csv$"") + for (file in files) { + attritionTable<- read.csv(file.path(diagnosticsFolder, file)) + attritionTable$treatedPersons[attritionTable$treatedPersons < minCellCount] <- paste0(""<"", minCellCount) + attritionTable$comparatorPersons[attritionTable$comparatorPersons < minCellCount] <- paste0(""<"", minCellCount) + attritionTable$treatedExposures[attritionTable$treatedExposures < minCellCount] <- paste0(""<"", minCellCount) + attritionTable$comparatorExposures[attritionTable$comparatorExposures < minCellCount] <- paste0(""<"", minCellCount) + write.csv(attritionTable, file.path(exportFolder, file), row.names = FALSE) + } + + # Cohort counts, enforcing minCellCount ------------------------------------------------------------- + fileName <- file.path(outputFolder, ""CohortCounts.csv"") + cohortCounts <- read.csv(fileName) + cohortCounts$cohortCount[cohortCounts$cohortCount < minCellCount] <- paste0(""<"", minCellCount) + cohortCounts$personCount[cohortCounts$personCount < minCellCount] <- paste0(""<"", minCellCount) + fileName <- file.path(exportFolder, ""CohortCounts.csv"") + write.csv(cohortCounts, fileName, row.names = FALSE) + + # Add all to zip file ------------------------------------------------------------------------------- + zipName <- file.path(exportFolder, ""StudyResults.zip"") + files <- list.files(exportFolder) + oldWd <- setwd(exportFolder) + on.exit(setwd(oldWd)) + zip::zip(zipfile = zipName, files = files, recurse = FALSE) + writeLines(paste(""\nStudy results are ready for sharing at:"", zipName)) +} + +#' Create metadata file +#' +#' @details +#' Creates a file containing metadata about the source data (taken from the cdm_source table) and R +#' package versions. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param exportFolder The name of the folder where the metadata file should be created. +#' +#' @export +createMetaData <- function(connectionDetails, cdmDatabaseSchema, exportFolder) { + conn <- DatabaseConnector::connect(connectionDetails) + sql <- ""SELECT * FROM @cdm_database_schema.cdm_source"" + sql <- SqlRender::renderSql(sql, cdm_database_schema = cdmDatabaseSchema)$sql + sql <- SqlRender::translateSql(sql, targetDialect = connectionDetails$dbms)$sql + cdmSource <- DatabaseConnector::querySql(conn, sql) + DatabaseConnector::disconnect(conn) + lines <- paste(names(cdmSource), cdmSource[1, ], sep = "": "") + + snapshot <- OhdsiRTools::takeEnvironmentSnapshot(""AlendronateVsRaloxifene"") + lines <- c(lines, """") + lines <- c(lines, ""Package versions:"") + lines <- c(lines, paste(snapshot$package, snapshot$version, sep = "": "")) + write(lines, file.path(exportFolder, ""MetaData.txt"")) + invisible(NULL) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AlendronateVsRaloxifene/R/FiguresAndTablesForPaper.R",".R","15143","257","# Need to revise !!! + +# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of AlendronateVsRaloxifene +# +# 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. + +#' Generate diagnostics +#' +#' @details +#' This function generates figures and tables. +#' +#' @param outputFolder Name of local folder where the results were generated; make sure to use forward slashes +#' (/). Do not use a folder on a network drive since this greatly impacts +#' performance. +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cohortDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param cohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' +#' @export +createFiguresAndTables <- function(outputFolder, + connectionDetails, + cohortDatabaseSchema, + cohortTable, + oracleTempSchema = oracleTempSchema) { + cmOutputFolder <- file.path(outputFolder, ""cmOutput"") + figuresAndTablesFolder <- file.path(outputFolder, ""figuresAndTables"") + if (!file.exists(figuresAndTablesFolder)) + dir.create(figuresAndTablesFolder) + + + reference <- readRDS(file.path(cmOutputFolder, ""outcomeModelReference.rds"")) + analysisSummary <- CohortMethod::summarizeAnalyses(reference) + + + # Break up outcomes into components -------------------------------------------------------------- + conn <- DatabaseConnector::connect(connectionDetails) + strataFile <- reference$strataFile[reference$analysisId == 1 & + reference$targetId == 1 & + reference$comparatorId == 2 & + reference$outcomeId == 21] + popPc <- readRDS(strataFile) + strataFile <- reference$strataFile[reference$analysisId == 1 & + reference$targetId == 3 & + reference$comparatorId == 4 & + reference$outcomeId == 21] + popBc <- readRDS(strataFile) + strataFile <- reference$strataFile[reference$analysisId == 1 & + reference$targetId == 5 & + reference$comparatorId == 6 & + reference$outcomeId == 21] + popOther <- readRDS(strataFile) + population <- rbind(popPc, popBc, popOther) + population <- population[population$outcomeCount > 0, ] + population$cohortStartDate <- population$cohortStartDate + population$daysToEvent + population <- population[, c(""subjectId"", ""cohortStartDate"", ""treatment"")] + colnames(population) <- SqlRender::camelCaseToSnakeCase(colnames(population)) + DatabaseConnector::insertTable(connection = conn, + tableName = ""#temp"", + data = population, + dropTableIfExists = TRUE, + createTable = TRUE, + tempTable = TRUE, + oracleTempSchema = oracleTempSchema) + sql <- ""SELECT dedupe.cohort_definition_id, + treatment, + COUNT(*) AS event_count + FROM (SELECT MAX(cohort.cohort_definition_id) AS cohort_definition_id, + treatment, + cohort.cohort_start_date, + cohort.subject_id + FROM #temp temp + INNER JOIN @cohort_database_schema.@cohort_table cohort + ON temp.subject_id = cohort.subject_id + AND temp.cohort_start_date = cohort.cohort_start_date + WHERE cohort.cohort_definition_id IN (22,23,24,25) + GROUP BY treatment, + cohort.cohort_start_date, + cohort.subject_id + ) dedupe + GROUP BY dedupe.cohort_definition_id, + treatment;"" + sql <- SqlRender::renderSql(sql = sql, + cohort_database_schema = cohortDatabaseSchema, + cohort_table = cohortTable)$sql + sql <- SqlRender::translateSql(sql = sql, targetDialect = connectionDetails$dbms, oracleTempSchema = oracleTempSchema)$sql + counts <- DatabaseConnector::querySql(conn, sql) + colnames(counts) <- SqlRender::snakeCaseToCamelCase(colnames(counts)) + counts <- addCohortNames(counts) + counts <- aggregate(eventCount ~ cohortName, counts, sum) + write.csv(counts, file.path(figuresAndTablesFolder, ""EventBreakout.csv""), row.names = FALSE) + + # MDRR across TCs ----------------------------------------------- + mdrrFiles <- list.files(file.path(outputFolder, ""diagnostics""), pattern = ""mdrr.*.csv"") + outcomeIds <- as.integer(gsub("".csv"", """", gsub(""^.*_o"", """", mdrrFiles))) + for (outcomeId in unique(outcomeIds)) { + mdrr <- lapply(mdrrFiles[outcomeIds == outcomeId], function(x) read.csv(file.path(outputFolder, ""diagnostics"", x))) + mdrr <- do.call(rbind, mdrr) + mdrr$file <- mdrrFiles[outcomeIds == outcomeId] + mdrr$targetId <- as.integer(gsub(""_.*$"", """", gsub(""mdrr_a1_t"", """", mdrr$file))) + ordered <- data.frame(targetId = c(1,7,9,11,13,3,15,17,5,19),2, + description = c(""All (prostate cancer)"", + ""-\t No other malignant diseases"", + ""-\t No osteonecrosis or osteomyelitis of the jaw"", + ""-\t No prior bisphosphonates"", + ""-\t Prior hormonal therapy"", + ""All (breast cancer)"", + ""-\t No other malignant diseases"", + ""-\t No prior bisphosphonates"", + ""All (advanced cancer or multiple myeloma)"", + ""-\t No prior bisphosphonates"")) + mdrr[match(mdrr$targetId, ordered$targetId), ] <- mdrr + mdrr$description <- ordered$description + mdrr$mdrr <- 1/mdrr$mdrr + mdrr <- mdrr[, c(""description"", ""targetPersons"", ""comparatorPersons"", ""totalOutcomes"", ""mdrr"")] + fileName <- file.path(figuresAndTablesFolder, paste0(""allMdrrs_o"", outcomeId, "".csv"")) + write.csv(mdrr, fileName, row.names = FALSE) + } + + # Study start date ------------------------------------------- + conn <- connect(connectionDetails) + sql <- ""SELECT MIN(cohort_start_date), cohort_definition_id FROM scratch.dbo.mschuemi_denosumab_optum WHERE cohort_definition_id IN (1, 3, 5) GROUP BY cohort_definition_id"" + print(querySql(conn, sql)) + + # Simplified null distribution ------------------------------------------- + negativeControls <- read.csv(system.file(""settings"", ""NegativeControls.csv"", package = ""AlendronateVsRaloxifene"")) + negativeControlOutcomeIds <- negativeControls$outcomeId[negativeControls$type == ""Outcome""] + + negControlSubset <- analysisSummary[analysisSummary$targetId %in% c(1,3,5) & + analysisSummary$comparatorId %in% c(2,4,6) & + analysisSummary$outcomeId %in% negativeControlOutcomeIds, ] + negControlSubset$label <- ""Prostate cancer"" + negControlSubset$label[negControlSubset$targetId == 3] <- ""Breast cancer"" + negControlSubset$label[negControlSubset$targetId == 5] <- ""Advanced cancer"" + fileName <- file.path(figuresAndTablesFolder, paste0(""simplifiedNullDistribution.png"")) + EvidenceSynthesis::plotEmpiricalNulls(logRr = negControlSubset$logRr, + seLogRr = negControlSubset$seLogRr, + labels = negControlSubset$label, + fileName = fileName) + + # PS distributions -------------------------------------------------------------- + psFile <- reference$sharedPsFile[reference$analysisId == 1 & + reference$targetId == 1 & + reference$comparatorId == 2 & + reference$outcomeId == 21] + ps <- readRDS(psFile) + psPc <- EvidenceSynthesis::preparePsPlot(ps) + psFile <- reference$sharedPsFile[reference$analysisId == 1 & + reference$targetId == 3 & + reference$comparatorId == 4 & + reference$outcomeId == 21] + ps <- readRDS(psFile) + psBc <- EvidenceSynthesis::preparePsPlot(ps) + psFile <- reference$sharedPsFile[reference$analysisId == 1 & + reference$targetId == 5 & + reference$comparatorId == 6 & + reference$outcomeId == 21] + ps <- readRDS(psFile) + psOther <- EvidenceSynthesis::preparePsPlot(ps) + ps <- list(psPc, psBc, psOther) + fileName <- file.path(figuresAndTablesFolder, paste0(""ps.png"")) + EvidenceSynthesis::plotPreparedPs(preparedPsPlots = ps, + labels = c(""Prostate cancer"", ""Breast cancer"", ""Advanced cancer""), + treatmentLabel = ""Denosumab"", + comparatorLabel = ""Zoledronic acid"", + fileName = fileName) + + # Balance -------------------------------------------------------------- + cmDataFile <- reference$cohortMethodDataFolder[reference$analysisId == 1 & + reference$targetId == 1 & + reference$comparatorId == 2 & + reference$outcomeId == 21] + strataFile <- reference$strataFile[reference$analysisId == 1 & + reference$targetId == 1 & + reference$comparatorId == 2 & + reference$outcomeId == 21] + cmData <- CohortMethod::loadCohortMethodData(cmDataFile) + strata <- readRDS(strataFile) + balPc <- CohortMethod::computeCovariateBalance(strata, cmData) + + cmDataFile <- reference$cohortMethodDataFolder[reference$analysisId == 1 & + reference$targetId == 3 & + reference$comparatorId == 4 & + reference$outcomeId == 21] + strataFile <- reference$strataFile[reference$analysisId == 1 & + reference$targetId == 3 & + reference$comparatorId == 4 & + reference$outcomeId == 21] + cmData <- CohortMethod::loadCohortMethodData(cmDataFile) + strata <- readRDS(strataFile) + balBc <- CohortMethod::computeCovariateBalance(strata, cmData) + cmDataFile <- reference$cohortMethodDataFolder[reference$analysisId == 1 & + reference$targetId == 5 & + reference$comparatorId == 6 & + reference$outcomeId == 21] + strataFile <- reference$strataFile[reference$analysisId == 1 & + reference$targetId == 5 & + reference$comparatorId == 6 & + reference$outcomeId == 21] + cmData <- CohortMethod::loadCohortMethodData(cmDataFile) + strata <- readRDS(strataFile) + balOther <- CohortMethod::computeCovariateBalance(strata, cmData) + bal <- list(balPc, balBc, balOther) + fileName <- file.path(figuresAndTablesFolder, paste0(""balance.png"")) + EvidenceSynthesis::plotCovariateBalances(balances = bal, + labels = c(""Prostate cancer"", ""Breast cancer"", ""Adv. cancer""), + beforeLabel = ""Before straticiation"", + afterLabel = ""After stratification"", + fileName = fileName) + fileName <- system.file(""settings"", ""Table1Specs.csv"", package = ""AlendronateVsRaloxifene"") + table1Specs <- read.csv(fileName) + table1 <- CohortMethod::createCmTable1(balance = balPc, + specifications = table1Specs, + beforeLabel = ""Before stratification"", + afterLabel = ""After stratification"", + targetLabel = ""Deno-sumab"", + comparatorLabel = ""Zole-dronic acid"", + percentDigits = 0) + write.csv(table1, file.path(figuresAndTablesFolder, ""Table1_PC.csv""), row.names = FALSE) + table1 <- CohortMethod::createCmTable1(balance = balBc, + specifications = table1Specs, + beforeLabel = ""Before stratification"", + afterLabel = ""After stratification"", + targetLabel = ""Deno-sumab"", + comparatorLabel = ""Zole-dronic acid"", + percentDigits = 0) + write.csv(table1, file.path(figuresAndTablesFolder, ""Table1_BC.csv""), row.names = FALSE) + table1 <- CohortMethod::createCmTable1(balance = balOther, + specifications = table1Specs, + beforeLabel = ""Before stratification"", + afterLabel = ""After stratification"", + targetLabel = ""Deno-sumab"", + comparatorLabel = ""Zole-dronic acid"", + percentDigits = 0) + write.csv(table1, file.path(figuresAndTablesFolder, ""Table1_Other.csv""), row.names = FALSE) + +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AlendronateVsRaloxifene/R/Diagnostics.R",".R","13404","213","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of AlendronateVsRaloxifene +# +# 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. + +#' Generate diagnostics +#' +#' @details +#' This function generates analyses diagnostics. Requires the study to be executed first. +#' +#' @param outputFolder Name of local folder where the results were generated; make sure to use forward slashes +#' (/). Do not use a folder on a network drive since this greatly impacts +#' performance. +#' +#' @export +generateDiagnostics <- function(outputFolder) { + packageName <- ""AlendronateVsRaloxifene"" + modelType <- ""cox"" # For MDRR computation + psStrategy <- ""stratification"" # For covariate balance labels + cmOutputFolder <- file.path(outputFolder, ""cmOutput"") + diagnosticsFolder <- file.path(outputFolder, ""diagnostics"") + if (!file.exists(diagnosticsFolder)) + dir.create(diagnosticsFolder) + + pathToCsv <- system.file(""settings"", ""TcosOfInterest.csv"", package = packageName) + tcosOfInterest <- read.csv(pathToCsv, stringsAsFactors = FALSE) + + reference <- readRDS(file.path(cmOutputFolder, ""outcomeModelReference.rds"")) + reference <- unique(reference) + analysisSummary <- CohortMethod::summarizeAnalyses(reference) + cmAnalysisList <- CohortMethod::loadCmAnalysisList(system.file(""settings"", ""cmAnalysisList.json"", package = packageName)) + for (i in 1:length(cmAnalysisList)) { + analysisSummary$description[analysisSummary$analysisId == cmAnalysisList[[i]]$analysisId] <- cmAnalysisList[[i]]$description + } + allControlsFile <- file.path(outputFolder, ""AllControls.csv"") + allControls <- read.csv(allControlsFile) + tcsOfInterest <- unique(tcosOfInterest[, c(""targetId"", ""comparatorId"")]) + mdrrs <- data.frame() + for (i in 1:nrow(tcsOfInterest)) { + targetId <- tcsOfInterest$targetId[i] + comparatorId <- tcsOfInterest$comparatorId[i] + targetLabel <- tcosOfInterest$targetName[tcosOfInterest$targetId == targetId & tcosOfInterest$comparatorId == comparatorId][1] + comparatorLabel <- tcosOfInterest$comparatorName[tcosOfInterest$targetId == targetId & tcosOfInterest$comparatorId == comparatorId][1] + outcomeIds <- as.character(tcosOfInterest$outcomeIds[tcosOfInterest$targetId == targetId & tcosOfInterest$comparatorId == comparatorId]) + outcomeIds <- as.numeric(strsplit(outcomeIds, split = "";"")[[1]]) + for (analysisId in unique(reference$analysisId)) { + controlSubset <- allControls[allControls$targetId == targetId & allControls$comparatorId == comparatorId, ] + controlSubset <- merge(controlSubset[, c(""targetId"", ""comparatorId"", ""outcomeId"", ""oldOutcomeId"", ""targetEffectSize"")], analysisSummary[analysisSummary$analysisId == analysisId, ]) + + # Outcome controls + label <- ""OutcomeControls"" + + negControlSubset <- controlSubset[controlSubset$targetEffectSize == 1, ] + + validNcs <- sum(!is.na(negControlSubset$seLogRr)) + if (validNcs >= 5) { + null <- EmpiricalCalibration::fitMcmcNull(negControlSubset$logRr, negControlSubset$seLogRr) + + fileName <- file.path(diagnosticsFolder, paste0(""nullDistribution_a"", analysisId, ""_t"", targetId, ""_c"", comparatorId, ""_"", label, "".png"")) + EmpiricalCalibration::plotCalibrationEffect(logRrNegatives = negControlSubset$logRr, + seLogRrNegatives = negControlSubset$seLogRr, + null = null, + showCis = TRUE, + fileName = fileName) + } else { + null <- NULL + } + if (sum(!is.na(controlSubset$seLogRr)) >= 5) { + fileName <- file.path(diagnosticsFolder, paste0(""trueAndObs_a"", analysisId, ""_t"", targetId, ""_c"", comparatorId, ""_"", label, "".png"")) + EmpiricalCalibration::plotTrueAndObserved(logRr = controlSubset$logRr, + seLogRr = controlSubset$seLogRr, + trueLogRr = log(controlSubset$targetEffectSize), + fileName = fileName) + } + validPcs <- sum(!is.na(controlSubset$seLogRr[controlSubset$targetEffectSize != 1])) + if (validPcs >= 10) { + model <- EmpiricalCalibration::fitSystematicErrorModel(controlSubset$logRr, controlSubset$seLogRr, log(controlSubset$targetEffectSize), estimateCovarianceMatrix = FALSE) + class(model) <- ""vector"" + fileName <- file.path(diagnosticsFolder, paste0(""systematicErrorModel_a"", analysisId, ""_t"", targetId, ""_c"", comparatorId, ""_"", label, "".csv"")) + write.csv(t(model), fileName, row.names = FALSE) + + fileName <- file.path(diagnosticsFolder, paste0(""ciCoverage_a"", analysisId, ""_t"", targetId, ""_c"", comparatorId, ""_"", label, "".png"")) + evaluation <- EmpiricalCalibration::evaluateCiCalibration(logRr = controlSubset$logRr, + seLogRr = controlSubset$seLogRr, + trueLogRr = log(controlSubset$targetEffectSize), + crossValidationGroup = controlSubset$oldOutcomeId) + EmpiricalCalibration::plotCiCoverage(evaluation = evaluation, + fileName = fileName) + } + + + for (outcomeId in outcomeIds) { + # Compute MDRR + strataFile <- reference$strataFile[reference$analysisId == analysisId & + reference$targetId == targetId & + reference$comparatorId == comparatorId & + reference$outcomeId == outcomeId] + if (strataFile == """") { + strataFile <- reference$studyPopFile[reference$analysisId == analysisId & + reference$targetId == targetId & + reference$comparatorId == comparatorId & + reference$outcomeId == outcomeId] + } + population <- readRDS(strataFile) + mdrr <- CohortMethod::computeMdrr(population, alpha = 0.05, power = 0.8, twoSided = TRUE, modelType = modelType) + mdrr$analysisId <- analysisId + mdrr$targetId <- targetId + mdrr$comparatorId <- comparatorId + mdrr$outcomeId <- outcomeId + mdrrs <- rbind(mdrrs, mdrr) + fileName <- file.path(diagnosticsFolder, paste0(""attritionDiagram_a"",analysisId,""_t"",targetId,""_c"",comparatorId, ""_o"", outcomeId, "".png"")) + CohortMethod::drawAttritionDiagram(population, treatmentLabel = targetLabel, comparatorLabel = comparatorLabel, fileName = fileName) + + fileName <- file.path(diagnosticsFolder, paste0(""attritionTable_a"",analysisId,""_t"",targetId,""_c"",comparatorId, ""_o"", outcomeId, "".csv"")) + attritionTable <- CohortMethod::getAttritionTable(population) + write.csv(attritionTable, fileName, row.names = FALSE) + + if (!is.null(null)) { + fileName <- file.path(diagnosticsFolder, paste0(""type1Error_a"",analysisId,""_t"",targetId,""_c"",comparatorId, ""_o"", outcomeId,""_"", label, "".png"")) + EmpiricalCalibration::plotExpectedType1Error(seLogRrPositives = mdrr$se, + null = null, + showCis = TRUE, + title = label, + fileName = fileName) + } + } + exampleRef <- reference[reference$analysisId == analysisId & + reference$targetId == targetId & + reference$comparatorId == comparatorId & + reference$outcomeId == outcomeIds[1], ] + ps <- readRDS(exampleRef$sharedPsFile) + if (nrow(ps) != 0) { + if (exampleRef$sharedPsFile == """") { + psAfterMatching <- readRDS(exampleRef$studyPopFile) + } else { + psAfterMatching <- readRDS(exampleRef$strataFile) + + fileName <- file.path(diagnosticsFolder, paste0(""psBeforeStratification_a"",analysisId,""_t"",targetId,""_c"",comparatorId,"".png"")) + psPlot <- CohortMethod::plotPs(data = ps, + treatmentLabel = targetLabel, + comparatorLabel = comparatorLabel, + fileName = fileName) + + + fileName <- file.path(diagnosticsFolder, paste0(""psAfterStratification_a"",analysisId,""_t"",targetId,""_c"",comparatorId,"".png"")) + psPlot <- CohortMethod::plotPs(data = psAfterMatching, + unfilteredData = ps, + treatmentLabel = targetLabel, + comparatorLabel = comparatorLabel, + fileName = fileName) + + prepapredPsPlot <- EvidenceSynthesis::preparePsPlot(data = psAfterMatching, + unfilteredData = ps) + fileName <- file.path(diagnosticsFolder, paste0(""preparedPsPlot_a"",analysisId,""_t"",targetId,""_c"",comparatorId,"".csv"")) + write.csv(prepapredPsPlot, fileName, row.names = FALSE) + + cmData <- CohortMethod::loadCohortMethodData(exampleRef$cohortMethodDataFolder) + + balance <- CohortMethod::computeCovariateBalance(psAfterMatching, cmData) + fileName = file.path(diagnosticsFolder, paste(""balance_a"",analysisId,""_t"",targetId,""_c"",comparatorId,"".csv"",sep="""")) + write.csv(balance, fileName, row.names = FALSE) + + fileName = file.path(diagnosticsFolder, paste(""balanceScatter_a"",analysisId,""_t"",targetId,""_c"",comparatorId,"".png"",sep="""")) + balanceScatterPlot <- CohortMethod::plotCovariateBalanceScatterPlot(balance = balance, + beforeLabel = paste(""Before"", psStrategy), + afterLabel = paste(""After"", psStrategy), + fileName = fileName) + + fileName = file.path(diagnosticsFolder, paste(""balanceTop_a"",analysisId,""_t"",targetId,""_c"",comparatorId,"".png"",sep="""")) + balanceTopPlot <- CohortMethod::plotCovariateBalanceOfTopVariables(balance = balance, + beforeLabel = paste(""Before"", psStrategy), + afterLabel = paste(""After"", psStrategy), + fileName = fileName) + } + fileName = file.path(diagnosticsFolder, paste(""table1_a"",analysisId,""_t"",targetId,""_c"",comparatorId,"".csv"",sep="""")) + table1 <- CohortMethod::createCmTable1(balance = balance, + beforeTargetPopSize = sum(cmData$cohorts$treatment == 1), + afterTargetPopSize = sum(psAfterMatching$treatment == 1), + beforeComparatorPopSize = sum(cmData$cohorts$treatment == 0), + afterComparatorPopSize = sum(psAfterMatching$treatment == 0), + targetLabel = targetLabel, + comparatorLabel = comparatorLabel, + beforeLabel = paste(""Before"", psStrategy), + afterLabel = paste(""After"", psStrategy)) + write.csv(table1, fileName, row.names = FALSE) + + fileName = file.path(diagnosticsFolder, paste(""followupDist_a"",analysisId,""_t"",targetId,""_c"",comparatorId, "".png"",sep="""")) + CohortMethod::plotFollowUpDistribution(psAfterMatching, + targetLabel = targetLabel, + comparatorLabel = comparatorLabel, + fileName = fileName) + } + } + } + mdrrs <- addCohortNames(mdrrs, ""targetId"", ""targetName"") + mdrrs <- addCohortNames(mdrrs, ""comparatorId"", ""comparatorName"") + mdrrs <- addCohortNames(mdrrs, ""outcomeId"", ""outcomeName"") + fileName <- file.path(diagnosticsFolder, ""mdrrs.csv"") + write.csv(mdrrs, fileName, row.names = FALSE) + +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AlendronateVsRaloxifene/R/Package.R",".R","872","27","# @file Package.R +# +# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of AlendronateVsRaloxifene +# +# 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. + +#' AlendronateVsRaloxifene +#' +#' @docType package +#' @name AlendronateVsRaloxifene +#' @importFrom stats aggregate +#' @importFrom utils read.csv write.csv +#' @import DatabaseConnector +NULL +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AlendronateVsRaloxifene/extras/PackageMaintenance.R",".R","2320","47","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of AlendronateVsRaloxifene +# +# 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. + +# Format and check code --------------------------------------------------- +OhdsiRTools::formatRFolder() +OhdsiRTools::checkUsagePackage(""AlendronateVsRaloxifene"") +OhdsiRTools::updateCopyrightYearFolder() + +# Create manual ----------------------------------------------------------- +shell(""rm extras/AlendronateVsRaloxifene.pdf"") +shell(""R CMD Rd2pdf ./ --output=extras/AlendronateVsRaloxifene.pdf"") + +# Create vignette --------------------------------------------------------- +rmarkdown::render(""vignettes/UsingSkeletonPackage.Rmd"", + output_file = ""../inst/doc/UsingSkeletonPackage.pdf"", + rmarkdown::pdf_document(latex_engine = ""pdflatex"", + toc = TRUE, + number_sections = TRUE)) + +# Insert cohort definitions from ATLAS into package ----------------------- +OhdsiRTools::insertCohortDefinitionSetInPackage(fileName = ""CohortsToCreate.csv"", + baseUrl = Sys.getenv(""baseUrl""), + insertTableSql = TRUE, + insertCohortCreationR = TRUE, + generateStats = FALSE, + packageName = ""AlendronateVsRaloxifene"") + +# Create analysis details ------------------------------------------------- +source(""extras/CreateStudyAnalysisDetails.R"") +createAnalysesDetails(""inst/settings/"") + +# Store environment in which the study was executed ----------------------- +OhdsiRTools::insertEnvironmentSnapshotInPackage(""AlendronateVsRaloxifene"") +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AlendronateVsRaloxifene/extras/CodeToRun.R",".R","1840","49","remove.packages(""AlendronateVsRaloxifene"") +setwd(""c:/Users/Administrator/Dropbox/"") +library(devtools) +install(""AlendronateVsRaloxifene"") + +library(AlendronateVsRaloxifene) + +# Optional: specify where the temporary files (used by the ff package) will be created: +options(fftempdir = ""e:/FFtemp"") + +# Maximum number of cores to be used: +maxCores <- 32 + +# The folder where the study intermediate and result files will be written: +outputFolder <- ""e:/temp/study"" + +# Details for connecting to the server: +connectionDetails <- DatabaseConnector::createConnectionDetails(dbms = ""sql server"", + server = ""localhost"", + user = ""joe"", + password = ""secret"") + +# The name of the database schema where the CDM data can be found: +cdmDatabaseSchema <- ""cdm_db.dbo"" + +# The name of the database schema and table where the study-specific cohorts will be instantiated: +cohortDatabaseSchema <- ""NHIS_CDM_RESULT_v2_2_0.dbo"" +cohortTable <- ""AlendronateVsRaloxifene"" + +# For Oracle: define a schema that can be used to emulate temp tables: +oracleTempSchema <- NULL + +execute(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder, + createCohorts = TRUE, + synthesizePositiveControls = TRUE, + runAnalyses = TRUE, + runDiagnostics = TRUE, + packageResults = TRUE, + maxCores = maxCores) + +prepareForEvidenceExplorer(studyFolder = ""e:/SkeletonStudy"") + +launchEvidenceExplorer(studyFolder = ""e:/SkeletonStudy"", blind = FALSE, launch.browser = FALSE) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AlendronateVsRaloxifene/extras/CreateStudyAnalysisDetails.R",".R","5572","87","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of TofaRep +# +# 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. + +createAnalysesDetails <- function(workFolder) { + covarSettings <- FeatureExtraction::createDefaultCovariateSettings(addDescendantsToExclude = TRUE) + + getDbCmDataArgs <- CohortMethod::createGetDbCohortMethodDataArgs(washoutPeriod = 365, + restrictToCommonPeriod = TRUE, + firstExposureOnly = FALSE, + removeDuplicateSubjects = TRUE, + studyStartDate = """", + studyEndDate = """", + excludeDrugsFromCovariates = FALSE, + covariateSettings = covarSettings) + + createStudyPopArgs1 <- CohortMethod::createCreateStudyPopulationArgs(removeSubjectsWithPriorOutcome = TRUE, + removeDuplicateSubjects = ""keep first"", + minDaysAtRisk = 0, + riskWindowStart = 90, + addExposureDaysToStart = FALSE, + riskWindowEnd = 9999, + addExposureDaysToEnd = FALSE) + + createStudyPopArgs2 <- CohortMethod::createCreateStudyPopulationArgs(removeSubjectsWithPriorOutcome = TRUE, + removeDuplicateSubjects = ""keep first"", + minDaysAtRisk = 0, + riskWindowStart = 90, + addExposureDaysToStart = FALSE, + riskWindowEnd = 0, + addExposureDaysToEnd = TRUE) + + + createPsArgs <- CohortMethod::createCreatePsArgs(control = Cyclops::createControl(cvType = ""auto"", + startingVariance = 0.01, + noiseLevel = ""quiet"", + tolerance = 2e-07, + cvRepetitions = 10)) + + stratifyByPsArgs <- CohortMethod::createStratifyByPsArgs(numberOfStrata = 5) + + fitOutcomeModelArgs <- CohortMethod::createFitOutcomeModelArgs(useCovariates = FALSE, + modelType = ""cox"", + stratified = TRUE) + + cmAnalysis1 <- CohortMethod::createCmAnalysis(analysisId = 1, + description = ""Main analysis: ITT"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = createStudyPopArgs1, + createPs = TRUE, + createPsArgs = createPsArgs, + stratifyByPs = TRUE, + stratifyByPsArgs = stratifyByPsArgs, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs) + + cmAnalysis2 <- CohortMethod::createCmAnalysis(analysisId = 2, + description = ""Sensitivity analysis: Per-protocol"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = createStudyPopArgs2, + createPs = TRUE, + createPsArgs = createPsArgs, + stratifyByPs = TRUE, + stratifyByPsArgs = stratifyByPsArgs, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs) + + + + cmAnalysisList <- list(cmAnalysis1, cmAnalysis2) + + CohortMethod::saveCmAnalysisList(cmAnalysisList, file.path(workFolder, ""cmAnalysisList.json"")) +} + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","plpLiveValidation/R/main.R",".R","2618","61","#' @export +execute <- function(connectionDetails, + databaseName, + cdmDatabaseSchema, + cohortDatabaseSchema, + oracleTempSchema, + cohortTable, + outputFolder, + createCohorts = T, + runValidation = T, + packageResults = T, + minCellCount = 5, + sampleSize=NULL){ + + if (!file.exists(outputFolder)) + dir.create(outputFolder, recursive = TRUE) + + ParallelLogger::addDefaultFileLogger(file.path(outputFolder, ""log.txt"")) + + if(createCohorts){ + ParallelLogger::logInfo(""Creating Cohorts"") + createCohorts(connectionDetails, + cdmDatabaseSchema=cdmDatabaseSchema, + cohortDatabaseSchema=cohortDatabaseSchema, + cohortTable=cohortTable, + outputFolder = outputFolder) + } + + if(runValidation){ + ParallelLogger::logInfo(""Validating Models"") + # for each model externally validate + analysesLocation <- system.file(""plp_models"", + package = ""plpLiveValidation"") + val <- PatientLevelPrediction::evaluateMultiplePlp(analysesLocation = analysesLocation, + outputLocation = outputFolder, + connectionDetails = connectionDetails, + validationSchemaTarget = cohortDatabaseSchema, + validationSchemaOutcome = cohortDatabaseSchema, + validationSchemaCdm = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + databaseNames = databaseName, + validationTableTarget = cohortTable, + validationTableOutcome = cohortTable, + sampleSize = sampleSize) + } + + # package the results: this creates a compressed file with sensitive details removed - ready to be reviewed and then + # submitted to the network study manager + + # results saved to outputFolder/databaseName + if (packageResults) { + ParallelLogger::logInfo(""Packaging results"") + packageResults(outputFolder = file.path(outputFolder,databaseName), + minCellCount = minCellCount) + } + + + invisible(NULL) + +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","plpLiveValidation/R/helpers.R",".R","11344","240","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of plpLiveValidation +# +# 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. + +#' Create the exposure and outcome cohorts +#' +#' @details +#' This function will create the exposure and outcome cohorts following the definitions included in +#' this package. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param cohortDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param cohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' +#' @export +createCohorts <- function(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable = ""cohort"", + oracleTempSchema, + outputFolder) { + if (!file.exists(outputFolder)) + dir.create(outputFolder) + + conn <- DatabaseConnector::connect(connectionDetails) + + .createCohorts(connection = conn, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder) + + # Check number of subjects per cohort: + ParallelLogger::logInfo(""Counting cohorts"") + sql <- SqlRender::loadRenderTranslateSql(""GetCounts.sql"", + ""plpLiveValidation"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + work_database_schema = cohortDatabaseSchema, + study_cohort_table = cohortTable) + counts <- DatabaseConnector::querySql(conn, sql) + colnames(counts) <- SqlRender::snakeCaseToCamelCase(colnames(counts)) + counts <- addCohortNames(counts) + write.csv(counts, file.path(outputFolder, ""CohortCounts.csv""), row.names = FALSE) + + DatabaseConnector::disconnect(conn) +} + +addCohortNames <- function(data, IdColumnName = ""cohortDefinitionId"", nameColumnName = ""cohortName"") { + pathToCsv <- system.file(""settings"", ""CohortsToCreate.csv"", package = ""plpLiveValidation"") + cohortsToCreate <- read.csv(pathToCsv) + + idToName <- data.frame(cohortId = c(cohortsToCreate$cohortId), + cohortName = c(as.character(cohortsToCreate$name))) + idToName <- idToName[order(idToName$cohortId), ] + idToName <- idToName[!duplicated(idToName$cohortId), ] + names(idToName)[1] <- IdColumnName + names(idToName)[2] <- nameColumnName + data <- merge(data, idToName, all.x = TRUE) + # Change order of columns: + idCol <- which(colnames(data) == IdColumnName) + if (idCol < ncol(data) - 1) { + data <- data[, c(1:idCol, ncol(data) , (idCol+1):(ncol(data)-1))] + } + return(data) +} + +.createCohorts <- function(connection, + cdmDatabaseSchema, + vocabularyDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable, + oracleTempSchema, + outputFolder) { + + # Create study cohort table structure: + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""CreateCohortTable.sql"", + packageName = ""plpLiveValidation"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + cohort_database_schema = cohortDatabaseSchema, + cohort_table = cohortTable) + DatabaseConnector::executeSql(connection, sql, progressBar = FALSE, reportOverallTime = FALSE) + + + + # Instantiate cohorts: + pathToCsv <- system.file(""settings"", ""CohortsToCreate.csv"", package = ""plpLiveValidation"") + cohortsToCreate <- read.csv(pathToCsv) + for (i in 1:nrow(cohortsToCreate)) { + writeLines(paste(""Creating cohort:"", cohortsToCreate$name[i])) + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = paste0(cohortsToCreate$name[i], "".sql""), + packageName = ""plpLiveValidation"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + vocabulary_database_schema = vocabularyDatabaseSchema, + + target_database_schema = cohortDatabaseSchema, + target_cohort_table = cohortTable, + target_cohort_id = cohortsToCreate$cohortId[i]) + DatabaseConnector::executeSql(connection, sql) + } +} + + +#' Creates the target population and outcome summary characteristics +#' +#' @details +#' This will create the patient characteristic table +#' +#' @param connectioDetails The connections details for connecting to the CDM +#' @param cdmDatabaseschema The schema holding the CDM data +#' @param cohortDatabaseschema The schema holding the cohort table +#' @param cohortTable The name of the cohort table +#' @param targetId The cohort definition id of the target population +#' @param outcomeId The cohort definition id of the outcome +#' @param tempCohortTable The name of the temporary table used to hold the cohort +#' +#' @return +#' A dataframe with the characteristics +#' +#' @export +getTable1 <- function(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable, + targetId, + outcomeId, + tempCohortTable='#temp_cohort'){ + + covariateSettings <- FeatureExtraction::createCovariateSettings(useDemographicsGender = T) + + plpData <- PatientLevelPrediction::getPlpData(connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortId = targetId, outcomeIds = outcomeId, + cohortDatabaseSchema = cohortDatabaseSchema, + outcomeDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + outcomeTable = cohortTable, + covariateSettings=covariateSettings) + + population <- PatientLevelPrediction::createStudyPopulation(plpData = plpData, + outcomeId = outcomeId, + binary = T, + includeAllOutcomes = T, + requireTimeAtRisk = T, + minTimeAtRisk = 364, + riskWindowStart = 1, + riskWindowEnd = 365, + removeSubjectsWithPriorOutcome = T) + + table1 <- PatientLevelPrediction::getPlpTable(cdmDatabaseSchema = cdmDatabaseSchema, + longTermStartDays = -9999, + population=population, + connectionDetails=connectionDetails, + cohortTable=tempCohortTable) + + return(table1) +} + +#========================== +# Example of implementing an exisitng model in the PredictionComparison repository +#========================== + +#' Checks the plp package is installed sufficiently for the network study and does other checks if needed +#' +#' @details +#' This will check that the network study dependancies work +#' +#' @param connectioDetails The connections details for connecting to the CDM +#' +#' @return +#' A number (a value other than 1 means an issue with the install) +#' +#' @export + +checkInstall <- function(connectionDetails=NULL){ + result <- checkPlpInstallation(connectionDetails=connectionDetails, + python=F) + return(result) +} + + + +transportPlpModels <- function(analysesDir, + minCellCount = 5, + databaseName = 'sharable name of development data', + outputDir +){ + if(missing(outputDir)){ + outputDir <- 'inst/plp_models' + } + + files <- dir(analysesDir, recursive = F, full.names = F) + files <- files[grep('Analysis_', files)] + filesIn <- file.path(analysesDir, files , 'plpResult') + filesOut <- file.path(outputDir, files, 'plpResult') + + for(i in 1:length(filesIn)){ + plpResult <- PatientLevelPrediction::loadPlpResult(filesIn[i]) + transportPlp(plpResult, + modelName= files[i], dataName=databaseName, + outputFolder = filesOut[i], + n=minCellCount, + includeEvaluationStatistics=T, + includeThresholdSummary=T, includeDemographicSummary=T, + includeCalibrationSummary =T, includePredictionDistribution=T, + includeCovariateSummary=T, save=T) + + } +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","plpLiveValidation/R/PackageResults.R",".R","3165","83","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of PredictionNetworkStudySkeleton +# +# 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. + +#' Package the results for sharing with OHDSI researchers +#' +#' @details +#' This function packages the results. +#' +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' @param minCellCount The minimum number of subjects contributing to a count before it can be included in the results. +#' +#' @export +packageResults <- function(outputFolder, + minCellCount = 5) { + if(missing(outputFolder)){ + stop('Missing outputFolder...') + } + + # for each analysis copy the requested files... + folders <- list.dirs(path = outputFolder, recursive = T, full.names = F) + folders <- folders[grep('Analysis_', folders)] + if(length(grep('inst/plp_models', folders))>0){ + folders <- folders[-grep('inst/plp_models', folders)] #in case using package directory + } + + if(length(folders)==0){ + stop('No results to export...') + } + + #create export subfolder in workFolder + exportFolder <- file.path(outputFolder, ""export"") + + for(folder in folders){ + #copy all plots across + if (!file.exists(file.path(exportFolder,folder))){ + dir.create(file.path(exportFolder,folder), recursive = T) + } + + # loads analysis results + if(file.exists(file.path(outputFolder,folder, 'validationResult.rds'))){ + plpResult <- readRDS(file.path(outputFolder,folder, 'validationResult.rds')) + + if(minCellCount==0){ + minCellCount <- NULL + } + result <- PatientLevelPrediction::transportPlp(plpResult, save = F, + n=minCellCount, + includeEvaluationStatistics=T, + includeThresholdSummary=T, + includeDemographicSummary=T, + includeCalibrationSummary =T, + includePredictionDistribution=T, + includeCovariateSummary=T) + saveRDS(result, file.path(exportFolder,folder, 'validationResult.rds')) + + } + } + + + ### Add all to zip file ### + zipName <- paste0(outputFolder, '.zip') + OhdsiSharing::compressFolder(exportFolder, zipName) + # delete temp folder + unlink(exportFolder, recursive = T) + + writeLines(paste(""\nStudy results are compressed and ready for sharing at:"", zipName)) + return(zipName) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","plpLiveValidation/extras/PackageMaintenance.R",".R","2354","48","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of plpLiveValidation +# +# 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. + +# Format and check code --------------------------------------------------- +OhdsiRTools::formatRFolder() +OhdsiRTools::checkUsagePackage(""plpLiveValidation"") +OhdsiRTools::updateCopyrightYearFolder() + +# Create manual ----------------------------------------------------------- +shell(""rm extras/plpLiveValidation.pdf"") +shell(""R CMD Rd2pdf ./ --output=extras/plpLiveValidation.pdf"") + +# Create vignette --------------------------------------------------------- +rmarkdown::render(""vignettes/UsingSkeletonPackage.Rmd"", + output_file = ""../inst/doc/UsingSkeletonPackage.pdf"", + rmarkdown::pdf_document(latex_engine = ""pdflatex"", + toc = TRUE, + number_sections = TRUE)) + +# Insert cohort definitions from ATLAS into package ----------------------- +OhdsiRTools::insertCohortDefinitionSetInPackage(fileName = ""CohortsToCreate.csv"", + baseUrl = Sys.getenv(""baseUrl""), + insertTableSql = TRUE, + insertCohortCreationR = TRUE, + generateStats = FALSE, + packageName = ""plpLiveValidation"") + +# transport the plp models ------------------------------------------------- +transportPlpModels(analysesDir= ""modelFolder"", + minCellCount = 5, + databaseName = 'sharable name of development data') + +# Store environment in which the study was executed ----------------------- +OhdsiRTools::insertEnvironmentSnapshotInPackage(""plpLiveValidation"") +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","QuantifyingBiasInApapStudies/R/Main.R",".R","6901","142","# Copyright 2019 Observational Health Data Sciences and Informatics +# +# This file is part of QuantifyingBiasInApapStudies +# +# 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. + +#' Execute the Study +#' +#' @details +#' This function executes the QuantifyingBiasInApapStudies Study. +#' +#' The \code{createCohorts}, \code{synthesizePositiveControls}, \code{runAnalyses}, and \code{runDiagnostics} arguments +#' are intended to be used to run parts of the full study at a time, but none of the parts are considerd to be optional. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param cohortDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param cohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/). Do not use a folder on a network drive since this greatly impacts +#' performance. +#' @param createCohorts Create the cohortTable table with the exposure and outcome cohorts? +#' @param runCohortMethod Perform the cohort method analyses? Requires the cohorts have been created. +#' @param runCaseControl Perform the case-control analyses? Requires the cohorts have been created. +#' @param createPlotsAndTables Generate output plots and tables? Requires CohortMethodd and CaseControl +#' analyses have been completed. +#' @param generateReport Generate a report document? Requires the plots and tables have been created. +#' @param maxCores How many parallel cores should be used? If more cores are made available +#' this can speed up the analyses. +#' @param blind Blind results? If true, no real effect sizes will be shown. To be used during development. +#' +#' @examples +#' \dontrun{ +#' connectionDetails <- createConnectionDetails(dbms = ""postgresql"", +#' user = ""joe"", +#' password = ""secret"", +#' server = ""myserver"") +#' +#' execute(connectionDetails, +#' cdmDatabaseSchema = ""cdm_data"", +#' cohortDatabaseSchema = ""study_results"", +#' cohortTable = ""cohort"", +#' oracleTempSchema = NULL, +#' outputFolder = ""c:/temp/study_results"", +#' maxCores = 4) +#' } +#' +#' @export +execute <- function(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema = cdmDatabaseSchema, + cohortTable = ""cohort"", + oracleTempSchema = cohortDatabaseSchema, + outputFolder, + createCohorts = TRUE, + runCohortMethod = TRUE, + runCaseControl = TRUE, + createPlotsAndTables = TRUE, + generateReport = TRUE, + maxCores = 4, + blind = TRUE) { + if (!file.exists(outputFolder)) { + dir.create(outputFolder, recursive = TRUE) + } + + ParallelLogger::addDefaultFileLogger(file.path(outputFolder, ""log.txt"")) + on.exit(ParallelLogger::unregisterLogger(""DEFAULT"")) + + if (!is.null(getOption(""fftempdir"")) && !file.exists(getOption(""fftempdir""))) { + warning(""fftempdir '"", getOption(""fftempdir""), ""' not found. Attempting to create folder"") + dir.create(getOption(""fftempdir""), recursive = TRUE) + } + + + if (createCohorts) { + ParallelLogger::logInfo(""Creating exposure and outcome cohorts"") + createCohorts(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder) + } + + if (runCohortMethod) { + ParallelLogger::logInfo(""Running CohortMethod analyses"") + runCohortMethod(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder, + maxCores = maxCores) + } + + if (runCaseControl) { + ParallelLogger::logInfo(""Running CaseControl analyses"") + runCaseControl(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder, + maxCores = maxCores) + } + + if (createPlotsAndTables) { + ParallelLogger::logInfo(""Generating plots and tables"") + createPlotsAndTables(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder, + blind = blind) + } + if (generateReport) { + ParallelLogger::logInfo(""Generating report"") + generateReport(outputFolder = outputFolder) + } + + invisible(NULL) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","QuantifyingBiasInApapStudies/R/QuantifyingBiasInApapStudies.R",".R","868","24","# Copyright 2019 Observational Health Data Sciences and Informatics +# +# This file is part of QuantifyingBiasInApapStudies +# +# 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. + +#' QuantifyingBiasInApapStudies +#' +#' @docType package +#' @name QuantifyingBiasInApapStudies +#' @importFrom utils read.csv write.csv +#' @importFrom stats qnorm rnorm +#' @import DatabaseConnector +NULL","R" +"Pharmacogenetics","OHDSI/StudyProtocols","QuantifyingBiasInApapStudies/R/CreateCohorts.R",".R","3576","69","# Copyright 2019 Observational Health Data Sciences and Informatics +# +# This file is part of QuantifyingBiasInApapStudies +# +# 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. + +.createCohorts <- function(connection, + cdmDatabaseSchema, + vocabularyDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable, + oracleTempSchema, + outputFolder) { + + # Create study cohort table structure: + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""CreateCohortTable.sql"", + packageName = ""QuantifyingBiasInApapStudies"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + cohort_database_schema = cohortDatabaseSchema, + cohort_table = cohortTable) + DatabaseConnector::executeSql(connection, sql, progressBar = FALSE, reportOverallTime = FALSE) + + + + # Instantiate cohorts: + pathToCsv <- system.file(""settings"", ""CohortsToCreate.csv"", package = ""QuantifyingBiasInApapStudies"") + cohortsToCreate <- read.csv(pathToCsv) + for (i in 1:nrow(cohortsToCreate)) { + writeLines(paste(""Creating cohort:"", cohortsToCreate$name[i])) + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = paste0(cohortsToCreate$name[i], "".sql""), + packageName = ""QuantifyingBiasInApapStudies"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + vocabulary_database_schema = vocabularyDatabaseSchema, + + target_database_schema = cohortDatabaseSchema, + target_cohort_table = cohortTable, + target_cohort_id = cohortsToCreate$cohortId[i]) + DatabaseConnector::executeSql(connection, sql) + } + + # Fetch cohort counts: + sql <- ""SELECT cohort_definition_id, COUNT(*) AS count FROM @cohort_database_schema.@cohort_table GROUP BY cohort_definition_id"" + sql <- SqlRender::render(sql, + cohort_database_schema = cohortDatabaseSchema, + cohort_table = cohortTable) + sql <- SqlRender::translate(sql, targetDialect = attr(connection, ""dbms"")) + counts <- DatabaseConnector::querySql(connection, sql) + names(counts) <- SqlRender::snakeCaseToCamelCase(names(counts)) + counts <- merge(counts, data.frame(cohortDefinitionId = cohortsToCreate$cohortId, + cohortName = cohortsToCreate$name)) + write.csv(counts, file.path(outputFolder, ""CohortCounts.csv"")) + + +} + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","QuantifyingBiasInApapStudies/R/CohortMethod.R",".R","17174","291","# Copyright 2019 Observational Health Data Sciences and Informatics +# +# This file is part of QuantifyingBiasInApapStudies +# +# 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. + + +#' Run CohortMethod package +#' +#' @details +#' Run the CohortMethod package, which implements the comparative cohort design. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param cohortDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param cohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param outputFolder Name of local folder where the results were generated; make sure to use forward slashes +#' (/). Do not use a folder on a network drive since this greatly impacts +#' performance. +#' @param maxCores How many parallel cores should be used? If more cores are made available +#' this can speed up the analyses. +#' +#' @export +runCohortMethod <- function(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable, + oracleTempSchema, + outputFolder, + maxCores) { + cmOutputFolder <- file.path(outputFolder, ""cmOutput"") + if (!file.exists(cmOutputFolder)) { + dir.create(cmOutputFolder) + } + cmAnalysisListFile <- system.file(""settings"", + ""cmAnalysisList.json"", + package = ""QuantifyingBiasInApapStudies"") + cmAnalysisList <- CohortMethod::loadCmAnalysisList(cmAnalysisListFile) + tcosList <- createTcos(outputFolder = outputFolder) + outcomesOfInterest <- getOutcomesOfInterest() + results <- CohortMethod::runCmAnalyses(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + exposureDatabaseSchema = cohortDatabaseSchema, + exposureTable = cohortTable, + outcomeDatabaseSchema = cohortDatabaseSchema, + outcomeTable = cohortTable, + outputFolder = cmOutputFolder, + oracleTempSchema = oracleTempSchema, + cmAnalysisList = cmAnalysisList, + targetComparatorOutcomesList = tcosList, + getDbCohortMethodDataThreads = min(3, maxCores), + createStudyPopThreads = min(3, maxCores), + createPsThreads = max(1, round(maxCores/10)), + psCvThreads = min(10, maxCores), + trimMatchStratifyThreads = min(10, maxCores), + fitOutcomeModelThreads = max(1, round(maxCores/2)), + outcomeCvThreads = min(2, maxCores), + refitPsForEveryOutcome = FALSE) + + ParallelLogger::logInfo(""Summarizing results"") + analysisSummary <- CohortMethod::summarizeAnalyses(referenceTable = results, + outputFolder = cmOutputFolder) + analysisSummary <- addCohortNames(analysisSummary, ""targetId"", ""targetName"") + analysisSummary <- addCohortNames(analysisSummary, ""comparatorId"", ""comparatorName"") + analysisSummary <- addCohortNames(analysisSummary, ""outcomeId"", ""outcomeName"") + analysisSummary <- addAnalysisDescription(analysisSummary, ""analysisId"", ""analysisDescription"") + write.csv(analysisSummary, file.path(outputFolder, ""cmAnalysisSummary.csv""), row.names = FALSE) +} + +#' Create the analyses details +#' +#' @details +#' This function creates files specifying the analyses that will be performed. +#' +#' @param workFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' +#' @export +createCmAnalysesDetails <- function(workFolder) { + defaultControl <- Cyclops::createControl(cvType = ""auto"", + startingVariance = 0.01, + noiseLevel = ""quiet"", + tolerance = 1e-06, + maxIterations = 2500, + cvRepetitions = 10, + seed = 123) + + # Exclude acetaminophen and all other ingredients included in drugs containing acetaminophen: + toExclude <- c(1134439, 1135766, 1153013, 1189596, 1201620, 906780, 1125315, 1130585, 1103518, 19092290, 1129625, 1119510, 724394, 1153664, 1124957, 964407, 1112807, 1103314, 44361362, 19004724, 19037833, 1139993, 1154332) + + defaultCovariateSettings <- FeatureExtraction::createDefaultCovariateSettings(excludedCovariateConceptIds = toExclude, + addDescendantsToExclude = TRUE) + customCovariateSettings <- createCustomCovariatesSettings(useSmoking = TRUE, + useRheumatoidArthritis = TRUE, + useNonRa = TRUE, + useFatigue = TRUE, + useMigraine = TRUE) + + covariateSettings <- list(defaultCovariateSettings, customCovariateSettings) + + getDbCmDataArgs <- CohortMethod::createGetDbCohortMethodDataArgs(washoutPeriod = 0, + firstExposureOnly = FALSE, + removeDuplicateSubjects = FALSE, + restrictToCommonPeriod = FALSE, + maxCohortSize = 0, + excludeDrugsFromCovariates = FALSE, + covariateSettings = covariateSettings) + + noDelayTar <- CohortMethod::createCreateStudyPopulationArgs(removeSubjectsWithPriorOutcome = TRUE, + firstExposureOnly = FALSE, + washoutPeriod = 0, + removeDuplicateSubjects = FALSE, + minDaysAtRisk = 1, + riskWindowStart = 0, + startAnchor = ""cohort start"", + riskWindowEnd = 0, + endAnchor = ""cohort end"", + censorAtNewRiskWindow = FALSE) + + delayTar <- CohortMethod::createCreateStudyPopulationArgs(removeSubjectsWithPriorOutcome = TRUE, + firstExposureOnly = FALSE, + washoutPeriod = 0, + removeDuplicateSubjects = FALSE, + minDaysAtRisk = 1, + riskWindowStart = 2*365, + startAnchor = ""cohort start"", + riskWindowEnd = 0, + endAnchor = ""cohort end"", + censorAtNewRiskWindow = FALSE) + + createPsArgs <- CohortMethod::createCreatePsArgs(control = defaultControl, + errorOnHighCorrelation = FALSE, + stopOnError = FALSE) + + # Covariates to include in outcome model: + includeCovariateIds <- c(8532001, + 1997, + 1901, + 1995, + 1994, + 1993, + 1992) + # Female + # Smoking + # Charlson Index + # History of rheumatoid arthritis + # History of non-rheumatoid arthritis or chronic neck/back/joint pain. + # History of fatigue or lack of energy + # History of migraines or frequent headaches + + fitOutcomeModelArgs <- CohortMethod::createFitOutcomeModelArgs(useCovariates = TRUE, + modelType = ""cox"", + stratified = FALSE, + prior = Cyclops::createPrior(""none""), + includeCovariateIds = includeCovariateIds) + + a9 <- CohortMethod::createCmAnalysis(analysisId = 9, + description = ""No delay"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = noDelayTar, + createPs = TRUE, + createPsArgs = createPsArgs, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs) + + a10 <- CohortMethod::createCmAnalysis(analysisId = 10, + description = ""Delay"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = delayTar, + createPs = TRUE, + createPsArgs = createPsArgs, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs) + + cmAnalysisList <- list(a9, a10) + + CohortMethod::saveCmAnalysisList(cmAnalysisList, file.path(workFolder, ""cmAnalysisList.json"")) +} + +computeCovariateBalance <- function(row, cmOutputFolder, balanceFolder) { + outputFileName <- file.path(balanceFolder, + sprintf(""bal_t%s_c%s_o%s_a%s.rds"", row$targetId, row$comparatorId, row$outcomeId, row$analysisId)) + if (!file.exists(outputFileName)) { + ParallelLogger::logTrace(""Creating covariate balance file "", outputFileName) + cohortMethodDataFolder <- file.path(cmOutputFolder, row$cohortMethodDataFolder) + cohortMethodData <- CohortMethod::loadCohortMethodData(cohortMethodDataFolder) + strataFile <- file.path(cmOutputFolder, row$strataFile) + strata <- readRDS(strataFile) + balance <- CohortMethod::computeCovariateBalance(population = strata, cohortMethodData = cohortMethodData) + saveRDS(balance, outputFileName) + } +} + +addAnalysisDescription <- function(data, IdColumnName = ""analysisId"", nameColumnName = ""analysisDescription"") { + cmAnalysisListFile <- system.file(""settings"", + ""cmAnalysisList.json"", + package = ""QuantifyingBiasInApapStudies"") + cmAnalysisList <- CohortMethod::loadCmAnalysisList(cmAnalysisListFile) + idToName <- lapply(cmAnalysisList, function(x) data.frame(analysisId = x$analysisId, description = as.character(x$description))) + idToName <- do.call(""rbind"", idToName) + names(idToName)[1] <- IdColumnName + names(idToName)[2] <- nameColumnName + data <- merge(data, idToName, all.x = TRUE) + # Change order of columns: + idCol <- which(colnames(data) == IdColumnName) + if (idCol < ncol(data) - 1) { + data <- data[, c(1:idCol, ncol(data) , (idCol + 1):(ncol(data) - 1))] + } + return(data) +} + +createTcos <- function(outputFolder) { + pathToCsv <- system.file(""settings"", ""TcosOfInterest.csv"", package = ""QuantifyingBiasInApapStudies"") + tcosOfInterest <- read.csv(pathToCsv, stringsAsFactors = FALSE) + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""QuantifyingBiasInApapStudies"") + allControls <- read.csv(pathToCsv) + + tcs <- unique(tcosOfInterest[, c(""targetId"", ""comparatorId"")]) + createTco <- function(i) { + targetId <- tcs$targetId[i] + comparatorId <- tcs$comparatorId[i] + outcomeIds <- as.character(tcosOfInterest$outcomeIds[tcosOfInterest$targetId == targetId & tcosOfInterest$comparatorId == comparatorId]) + outcomeIds <- as.numeric(strsplit(outcomeIds, split = "";"")[[1]]) + outcomeIds <- c(outcomeIds, allControls$outcomeId[allControls$targetId == targetId & allControls$comparatorId == comparatorId]) + excludeConceptIds <- as.character(tcosOfInterest$excludedCovariateConceptIds[tcosOfInterest$targetId == targetId & tcosOfInterest$comparatorId == comparatorId]) + if (length(excludeConceptIds) == 1 && is.na(excludeConceptIds)) { + excludeConceptIds <- c() + } else if (length(excludeConceptIds) > 0) { + excludeConceptIds <- as.numeric(strsplit(excludeConceptIds, split = "";"")[[1]]) + } + includeConceptIds <- as.character(tcosOfInterest$includedCovariateConceptIds[tcosOfInterest$targetId == targetId & tcosOfInterest$comparatorId == comparatorId]) + if (length(includeConceptIds) == 1 && is.na(includeConceptIds)) { + includeConceptIds <- c() + } else if (length(includeConceptIds) > 0) { + includeConceptIds <- as.numeric(strsplit(excludeConceptIds, split = "";"")[[1]]) + } + tco <- CohortMethod::createTargetComparatorOutcomes(targetId = targetId, + comparatorId = comparatorId, + outcomeIds = outcomeIds, + excludedCovariateConceptIds = excludeConceptIds, + includedCovariateConceptIds = includeConceptIds) + return(tco) + } + tcosList <- lapply(1:nrow(tcs), createTco) + return(tcosList) +} + +getOutcomesOfInterest <- function() { + pathToCsv <- system.file(""settings"", ""TcosOfInterest.csv"", package = ""QuantifyingBiasInApapStudies"") + tcosOfInterest <- read.csv(pathToCsv, stringsAsFactors = FALSE) + outcomeIds <- as.character(tcosOfInterest$outcomeIds) + outcomeIds <- do.call(""c"", (strsplit(outcomeIds, split = "";""))) + outcomeIds <- unique(as.numeric(outcomeIds)) + return(outcomeIds) +} + +getAllControls <- function(outputFolder) { + allControlsFile <- file.path(outputFolder, ""AllControls.csv"") + if (file.exists(allControlsFile)) { + # Positive controls must have been synthesized. Include both positive and negative controls. + allControls <- read.csv(allControlsFile) + } else { + # Include only negative controls + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""QuantifyingBiasInApapStudies"") + allControls <- read.csv(pathToCsv) + allControls$oldOutcomeId <- allControls$outcomeId + allControls$targetEffectSize <- rep(1, nrow(allControls)) + } + return(allControls) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","QuantifyingBiasInApapStudies/R/CreateAllCohorts.R",".R","11131","209","# Copyright 2019 Observational Health Data Sciences and Informatics +# +# This file is part of QuantifyingBiasInApapStudies +# +# 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. + +#' Create the exposure and outcome cohorts +#' +#' @details +#' This function will create the exposure and outcome cohorts following the definitions included in +#' this package. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param cohortDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param cohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' +#' @export +createCohorts <- function(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable = ""cohort"", + oracleTempSchema, + outputFolder) { + if (!file.exists(outputFolder)) + dir.create(outputFolder, recursive = TRUE) + + connection <- DatabaseConnector::connect(connectionDetails) + on.exit(DatabaseConnector::disconnect(connection)) + + ParallelLogger::logInfo(""Creating ATLAS cohorts"") + .createCohorts(connection = connection, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder) + + ParallelLogger::logInfo(""Creating negative control outcome cohorts"") + createNegativeControlCohorts(connection = connection, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema) + + ParallelLogger::logInfo(""Creating exposure cohorts"") + createExposureCohorts(connection = connection, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema) + + # Check number of subjects per cohort: + ParallelLogger::logInfo(""Counting cohorts"") + countCohorts(connection = connection, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder) + +} + +createNegativeControlCohorts <- function(connection, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable, + oracleTempSchema) { + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""QuantifyingBiasInApapStudies"") + negativeControls <- read.csv(pathToCsv) + negativeControlOutcomes <- negativeControls[negativeControls$type == ""outcome"", ] + sql <- SqlRender::loadRenderTranslateSql(""NegativeControlOutcomes.sql"", + ""QuantifyingBiasInApapStudies"", + dbms = connection@dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = cohortDatabaseSchema, + target_cohort_table = cohortTable, + outcome_ids = negativeControlOutcomes$outcomeId) + DatabaseConnector::executeSql(connection, sql) +} + +createExposureCohorts <- function(connection, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable, + oracleTempSchema) { + # connection <- DatabaseConnector::connect(connectionDetails) + washoutDays <- 4*365.25 + periodStartDate <- ""2008-01-01"" + periodEndDate <- ""2008-12-31"" + minAge <- 50 + maxAge <- 76 + + # Get initial set of eligible individuals (persons with observation somewhere during period): + sql <- SqlRender::loadRenderTranslateSql(""GetEligibleSubjects.sql"", + ""QuantifyingBiasInApapStudies"", + dbms = connection@dbms, + cdm_database_schema = cdmDatabaseSchema, + washout_days = washoutDays, + period_start_date = periodStartDate, + period_end_date = periodEndDate, + min_age = minAge, + max_age = maxAge) + persons <- DatabaseConnector::querySql(connection, sql, snakeCaseToCamelCase = TRUE) + # Sample index dates in R to assure reproducibility: + set.seed(123) + persons$indexDate <- as.Date(periodStartDate) + sample.int(1 + as.integer(as.Date(periodEndDate) - as.Date(periodStartDate)), + nrow(persons), + replace = TRUE) - 1 + + # Can only bulk upload into permanent table. Move to temp table later: + tableName <- paste(cohortDatabaseSchema, paste(sample(letters, 10), collapse = """"), sep = ""."") + DatabaseConnector::insertTable(connection = connection, + tableName = tableName, + data = persons, + dropTableIfExists = TRUE, + createTable = TRUE, + tempTable = FALSE, + oracleTempSchema = oracleTempSchema, + useMppBulkLoad = TRUE, + camelCaseToSnakeCase = TRUE) + sql <- "" + IF OBJECT_ID('tempdb..#index_date', 'U') IS NOT NULL + DROP TABLE #index_date; + SELECT * INTO #index_date FROM @table_name;"" + DatabaseConnector::renderTranslateExecuteSql(connection, sql, table_name = tableName, progressBar = FALSE, reportOverallTime = FALSE) + + sql <- ""TRUNCATE TABLE @table_name; DROP TABLE @table_name;"" + DatabaseConnector::renderTranslateExecuteSql(connection, sql, table_name = tableName, progressBar = FALSE, reportOverallTime = FALSE) + + # Create target and comparator cohorts: + sql <- SqlRender::loadRenderTranslateSql(""CreateExposureCohorts.sql"", + ""QuantifyingBiasInApapStudies"", + dbms = connection@dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + washout_days = washoutDays, + target_database_schema = cohortDatabaseSchema, + target_cohort_table = cohortTable) + DatabaseConnector::executeSql(connection, sql) + + +} + +countCohorts <- function(connection, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable = ""cohort"", + oracleTempSchema, + outputFolder) { + sql <- SqlRender::loadRenderTranslateSql(""GetCounts.sql"", + ""QuantifyingBiasInApapStudies"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + cohort_database_schema = cohortDatabaseSchema, + cohort_table = cohortTable) + counts <- DatabaseConnector::querySql(connection, sql) + colnames(counts) <- SqlRender::snakeCaseToCamelCase(colnames(counts)) + counts <- addCohortNames(counts) + write.csv(counts, file.path(outputFolder, ""CohortCounts.csv""), row.names = FALSE) +} + +addCohortNames <- function(data, IdColumnName = ""cohortDefinitionId"", nameColumnName = ""cohortName"") { + pathToCsv <- system.file(""settings"", ""CohortsToCreate.csv"", package = ""QuantifyingBiasInApapStudies"") + cohortsToCreate <- read.csv(pathToCsv) + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""QuantifyingBiasInApapStudies"") + negativeControls <- read.csv(pathToCsv) + + idToName <- data.frame(cohortId = c(cohortsToCreate$cohortId, + negativeControls$outcomeId), + cohortName = c(as.character(cohortsToCreate$fullName), + as.character(negativeControls$outcomeName))) + idToName <- idToName[order(idToName$cohortId), ] + idToName <- idToName[!duplicated(idToName$cohortId), ] + names(idToName)[1] <- IdColumnName + names(idToName)[2] <- nameColumnName + data <- merge(data, idToName, all.x = TRUE) + # Change order of columns: + idCol <- which(colnames(data) == IdColumnName) + if (idCol < ncol(data) - 1) { + data <- data[, c(1:idCol, ncol(data) , (idCol+1):(ncol(data)-1))] + } + return(data) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","QuantifyingBiasInApapStudies/R/PlotsAndTables.R",".R","19771","345","# Copyright 2019 Observational Health Data Sciences and Informatics +# +# This file is part of QuantifyingBiasInApapStudies +# +# 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. + +#' Generate plots and tables +#' +#' @details +#' Requires that the CohortMethod and CaseControl analyses have been executed +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param outputFolder Name of local folder where the results were generated; make sure to use forward slashes +#' (/). Do not use a folder on a network drive since this greatly impacts +#' performance. +#' @param blind Blind results? If true, no real effect sizes will be shown. To be used during development. +#' +#' @export +createPlotsAndTables <- function(connectionDetails, + cdmDatabaseSchema, + oracleTempSchema, + outputFolder, + blind = TRUE) { + plotsAndTablesFolder <- file.path(outputFolder, ""plotsAndTables"") + ParallelLogger::logInfo(""Generating plots and tables in folder "", plotsAndTablesFolder) + if (!file.exists(plotsAndTablesFolder)) { + dir.create(plotsAndTablesFolder) + } + + # Cohort method --------------------------------------------------------------------- + ParallelLogger::logInfo(""Generating plots and tables for cohort design"") + cmOutputFolder <- file.path(outputFolder, ""cmOutput"") + omr <- readRDS(file.path(cmOutputFolder, ""outcomeModelReference.rds"")) + + # PS distribution plot + ps <- readRDS(file.path(cmOutputFolder, omr$sharedPsFile[omr$analysisId == 9][1])) + CohortMethod::plotPs(ps, fileName = file.path(plotsAndTablesFolder, ""ps.png""), targetLabel = ""High use"", comparatorLabel = ""No use"", showEquiposeLabel = TRUE) + + # PS model + cmData <- CohortMethod::loadCohortMethodData(file.path(cmOutputFolder, omr$cohortMethodDataFolder[omr$analysisId == 9][1])) + model <- CohortMethod::getPsModel(ps, cmData) + write.csv(model, file.path(plotsAndTablesFolder, ""propensityModel.csv""), row.names = FALSE) + + # Balance + pop <- cmData$cohorts + pop$stratumId <- 0 + bal <- CohortMethod::computeCovariateBalance(pop, cmData) + table <- bal[order(-abs(bal$beforeMatchingStdDiff)), c(""covariateId"", ""covariateName"", ""beforeMatchingMeanTarget"", ""beforeMatchingMeanComparator"", ""beforeMatchingSd"", ""beforeMatchingStdDiff"")] + table$balanced <- abs(bal$beforeMatchingStdDiff) <= 0.1 + colnames(table) <- c(""Covariate ID"", ""Covariate name"", ""Mean in high use"", ""Mean in no use"", ""Std. Dev."", ""Standardized difference of the mean"", ""Balanced?"") + write.csv(table, file.path(plotsAndTablesFolder, ""balance.csv""), row.names = FALSE) + + # Table 1 + table1 <- CohortMethod::createCmTable1(bal, beforeTargetPopSize = sum(pop$treatment), beforeComparatorPopSize = sum(!pop$treatment)) + table1 <- table1[, 1:4] + write.csv(table1, file.path(plotsAndTablesFolder, ""cmCharacteristicsTable.csv""), col.names = NULL, row.names = FALSE) + + # Analysis summary + analysisSummary <- read.csv(file.path(outputFolder, ""cmAnalysisSummary.csv"")) + + if (blind) { + analysisSummary <- blind(analysisSummary) + } + + table <- analysisSummary[, c(""analysisId"", ""analysisDescription"", ""outcomeName"", ""rr"", ""ci95lb"", ""ci95ub"", ""p"", ""target"", ""comparator"", ""targetDays"", ""comparatorDays"", ""eventsTarget"", ""eventsComparator"")] + colnames(table) <- c(""Analysis ID"", ""Description"", ""Outcome"", ""HR"", ""95% CI LB"", ""95% CI UB"", ""P"", ""High-use subject count"", ""No-use subject count"", ""High-use follow-up days"", ""No-use follow-up days"", ""High-use outcome count"", ""No-use outcome count"") + write.csv(table, file.path(plotsAndTablesFolder, ""cmAnalysisSummary.csv""), row.names = FALSE) + + # Forest plot + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""QuantifyingBiasInApapStudies"") + negativeControls <- read.csv(pathToCsv) + createAnalysisForestPlot <- function(subset) { + subset$negativeControl <- FALSE + subset$negativeControl[subset$outcomeId %in% negativeControls$outcomeId] <- TRUE + analysisId <- subset$analysisId[1] + description <- subset$analysisDescription[1] + plotForest(subset, + xLabel = ""Hazard Ratio"", + fileName = file.path(plotsAndTablesFolder, sprintf(""forest_a%s.png"", analysisId))) + } + subsets <- split(analysisSummary, analysisSummary$analysisId) + lapply(subsets, createAnalysisForestPlot) + + # Calibration plot and distribution parameter estimates + subsets <- split(analysisSummary, analysisSummary$analysisId) + table <- lapply(subsets, createCalibrationPlot, negativeControls = negativeControls, plotsAndTablesFolder = plotsAndTablesFolder, xLabel = ""Hazard Ratio"") + table <- do.call(rbind, table) + write.csv(table, file.path(plotsAndTablesFolder, ""cmEmpiricalNullParams.csv""), row.names = FALSE) + + # Fraction significant negative controls + subsets <- split(analysisSummary, analysisSummary$analysisId) + table <- lapply(subsets, computeFractionSignificant, negativeControls = negativeControls) + table <- do.call(rbind, table) + write.csv(table, file.path(plotsAndTablesFolder, ""cmNcsSignificant.csv""), row.names = FALSE) + + # Case-control ----------------------------------------------------------------------- + ParallelLogger::logInfo(""Generating plots and tables for case-control design"") + ccOutputFolder <- file.path(outputFolder, ""ccOutput"") + omr <- readRDS(file.path(ccOutputFolder, ""outcomeModelReference.rds"")) + + # Table 1 + pathToCsv <- system.file(""settings"", ""TosOfInterest.csv"", package = ""QuantifyingBiasInApapStudies"") + tosOfInterest <- read.csv(pathToCsv, stringsAsFactors = FALSE) + hois <- unique(as.integer(do.call(c, (strsplit(tosOfInterest$outcomeIds, "";""))))) + connection <- DatabaseConnector::connect(connectionDetails) + + for (outcomeId in hois) { + for (analysisId in unique(omr$analysisId)) { + ParallelLogger::logInfo(""Generating population characteristics table for outcome "", outcomeId, "" using analysis "", analysisId) + fileName <- file.path(plotsAndTablesFolder, sprintf(""ccCharacteristicsTable_a%s_o%s.csv"", analysisId, outcomeId)) + createCharacteristicsByExposure(connection = connection, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder, + analysisId = analysisId, + outcomeId = outcomeId, + fileName = fileName) + } + } + DatabaseConnector::disconnect(connection) + + # Analysis summary + analysisSummary <- read.csv(file.path(outputFolder, ""ccAnalysisSummary.csv"")) + + if (blind) { + analysisSummary <- blind(analysisSummary) + } + + table <- analysisSummary[, c(""analysisId"", ""analysisDescription"", ""outcomeName"", ""rr"", ""ci95lb"", ""ci95ub"", ""p"", ""cases"", ""controls"", ""exposedCases"", ""exposedControls"")] + colnames(table) <- c(""Analysis ID"", ""Description"", ""Outcome"", ""OR"", ""95% CI LB"", ""95% CI UB"", ""P"", ""Cases"", ""Controls"", ""Exposed cases"", ""Exposed controls"") + write.csv(table, file.path(plotsAndTablesFolder, ""ccAnalysisSummary.csv""), row.names = FALSE) + + # Forest plot + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""QuantifyingBiasInApapStudies"") + negativeControls <- read.csv(pathToCsv) + createAnalysisForestPlot <- function(subset) { + subset$negativeControl <- FALSE + subset$negativeControl[subset$outcomeId %in% negativeControls$outcomeId] <- TRUE + analysisId <- subset$analysisId[1] + description <- subset$analysisDescription[1] + plotForest(subset, + xLabel = ""Odds Ratio"", + fileName = file.path(plotsAndTablesFolder, sprintf(""forest_a%s.png"", analysisId))) + } + subsets <- split(analysisSummary, analysisSummary$analysisId) + lapply(subsets, createAnalysisForestPlot) + + # Calibration plot and distribution parameter estimates + subsets <- split(analysisSummary, analysisSummary$analysisId) + table <- lapply(subsets, createCalibrationPlot, negativeControls = negativeControls, plotsAndTablesFolder = plotsAndTablesFolder, xLabel = ""Odds Ratio"") + table <- do.call(rbind, table) + write.csv(table, file.path(plotsAndTablesFolder, ""ccEmpiricalNullParams.csv""), row.names = FALSE) + + # Fraction significant negative controls + subsets <- split(analysisSummary, analysisSummary$analysisId) + table <- lapply(subsets, computeFractionSignificant, negativeControls = negativeControls) + table <- do.call(rbind, table) + write.csv(table, file.path(plotsAndTablesFolder, ""ccNcsSignificant.csv""), row.names = FALSE) +} + +computeFractionSignificant <- function(subset, negativeControls) { + ncs <- subset[subset$outcomeId %in% negativeControls$outcomeId, ] + row <- data.frame(analysisId = subset$analysisId[1], + description = subset$analysisDescription[1], + controlsWithEstimates = sum(!is.na(ncs$ci95lb)), + controlsSignficant = sum(!is.na(ncs$ci95lb) & ncs$p < 0.05)) + row$fractionSignificant <- row$controlsSignficant / row$controlsWithEstimates + colnames(row) <- c(""Analysis ID"", ""Description"", ""Controls with estimate"", ""Controls significant"", ""Fraction significant (p < 0.05)"") + return(row) +} + +createCalibrationPlot <- function(subset, negativeControls, plotsAndTablesFolder, xLabel) { + ncs <- subset[subset$outcomeId %in% negativeControls$outcomeId, ] + pcs <- subset[!(subset$outcomeId %in% negativeControls$outcomeId), ] + analysisId <- subset$analysisId[1] + EmpiricalCalibration::plotCalibrationEffect(ncs$logRr, ncs$seLogRr, pcs$logRr, pcs$seLogRr, + xLabel = xLabel, + showCis = TRUE, + fileName = file.path(plotsAndTablesFolder, sprintf(""calibration_a%s.png"", analysisId))) + param <- EmpiricalCalibration::fitNull(ncs$logRr, ncs$seLogRr) + row <- data.frame(analysisId = subset$analysisId[1], + description = subset$analysisDescription[1], + mean = param[1], + SD = param[2]) + colnames(row) <- c(""Analysis ID"", ""Description"", ""Mean"", ""SD"") + return(row) +} + +blind <- function(data) { + ParallelLogger::logInfo(""Blinding results"") + data$logRr <- rnorm(nrow(data)) + seLogRr <- (log(data$ci95ub) - log(data$ci95lb))/(2 * qnorm(0.975)) + data$ci95lb <- exp(data$logRr + qnorm(0.025) * seLogRr) + data$ci95ub <- exp(data$logRr + qnorm(0.975) * seLogRr) + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""QuantifyingBiasInApapStudies"") + negativeControls <- read.csv(pathToCsv) + data$outcomeName <- ""Simulated outcome of interest"" + data$outcomeName[data$outcomeId %in% negativeControls$outcomeId] <- ""Simulated negative control"" + return(data) +} + +plotForest <- function(data, + xLabel = ""Relative risk"", + limits = c(0.1, 10), + fileName = NULL) { + data <- data[!is.na(data$ci95lb), ] + data$type <- ""Outcome of interest"" + data$type[data$negativeControl] <- ""Negative control"" + data <- data[order(-data$negativeControl, data$outcomeName), ] + d1 <- data.frame(logRr = -100, logLb95Ci = -100, logUb95Ci = -100, + name = ""Outcome"", type = ""Outcome of interest"") + d2 <- data.frame(logRr = data$logRr, logLb95Ci = log(data$ci95lb), logUb95Ci = log(data$ci95ub), + name = data$outcomeName, type = data$type) + d <- rbind(d1, d2) + d$y <- nrow(d):1 + breaks <- c(0.1, 0.25, 0.5, 1, 2, 4, 6, 8, 10) + p <- ggplot2::ggplot(d, ggplot2::aes(x = exp(logRr), y = y, xmin = exp(logLb95Ci), xmax = exp(logUb95Ci))) + + ggplot2::geom_vline(xintercept = breaks, colour = ""#AAAAAA"", lty = 1, size = 0.2) + + ggplot2::geom_vline(xintercept = 1, size = 0.5) + + ggplot2::geom_errorbarh(height = 0.25) + + ggplot2::geom_point(size = 3, ggplot2::aes(shape = type, fill = type)) + + ggplot2::scale_fill_manual(values = c(""#FFFF00"", ""#0000DD"")) + + ggplot2::scale_shape_manual(values = c(23,21)) + + ggplot2::scale_x_continuous(xLabel, trans = ""log10"", breaks = breaks, labels = breaks) + + ggplot2::coord_cartesian(xlim = limits) + + ggplot2::theme(panel.grid.major = ggplot2::element_blank(), + panel.grid.minor = ggplot2::element_blank(), + panel.background = ggplot2::element_blank(), + legend.position = ""right"", + legend.title = ggplot2::element_blank(), + panel.border = ggplot2::element_blank(), + axis.text.y = ggplot2::element_blank(), + axis.title.y = ggplot2::element_blank(), + axis.ticks = ggplot2::element_blank(), + plot.margin = grid::unit(c(0, 0, 0.1, 0), ""lines"")) + labels <- paste0(formatC(exp(d$logRr), digits = 2, format = ""f""), + "" ("", + formatC(exp(d$logLb95Ci), digits = 2, format = ""f""), + ""-"", + formatC(exp(d$logUb95Ci), digits = 2, format = ""f""), + "")"") + labels <- data.frame(y = rep(d$y, 2), + x = rep(c(1, 3), each = nrow(d)), + label = c(as.character(d$name), labels), stringsAsFactors = FALSE) + labels$label[nrow(d) + 1] <- paste(xLabel, ""(95% CI)"") + data_table <- ggplot2::ggplot(labels, ggplot2::aes(x = x, y = y, label = label)) + + ggplot2::geom_text(size = 4, hjust = 0, vjust = 0.5) + + ggplot2::geom_hline(ggplot2::aes(yintercept = nrow(d) - 0.5)) + + ggplot2::theme(panel.grid.major = ggplot2::element_blank(), + panel.grid.minor = ggplot2::element_blank(), + legend.position = ""none"", + panel.border = ggplot2::element_blank(), + panel.background = ggplot2::element_blank(), + axis.text.x = ggplot2::element_text(colour = ""white""), + axis.text.y = ggplot2::element_blank(), + axis.ticks = ggplot2::element_line(colour = ""white""), + plot.margin = grid::unit(c(0, 0, 0.1, 0), ""lines"")) + + ggplot2::labs(x = """", y = """") + + ggplot2::coord_cartesian(xlim = c(1, 4)) + plot <- gridExtra::grid.arrange(data_table, p, ncol = 2) + if (!is.null(fileName)) + ggplot2::ggsave(fileName, plot, width = 12, height = 1 + + nrow(data) * 0.25, dpi = 300) + return(plot) +} + +createCharacteristicsByExposure <- function(connection, cdmDatabaseSchema, oracleTempSchema, outputFolder, analysisId, outcomeId, fileName) { + + # Fetch data from server --------------------------------------------------------------------------------------- + ccOutputFolder <- file.path(outputFolder, ""ccOutput"") + dataFolder <- file.path(ccOutputFolder, sprintf(""covariatesForChar_a%s_o%s"", analysisId, outcomeId)) + dir.create(dataFolder) + omr <- readRDS(file.path(ccOutputFolder, ""outcomeModelReference.rds"")) + + idx <- omr$outcomeId == outcomeId & omr$analysisId == analysisId + ccdFile <- file.path(ccOutputFolder, omr$caseControlDataFile[idx]) + ccFile <- file.path(ccOutputFolder, omr$caseControlsFile[idx]) + ccd <- readRDS(ccdFile) + cc <- readRDS(ccFile) + + tableToUpload <- data.frame(subjectId = cc$personId, + cohortStartDate = cc$indexDate, + cohortDefinitionId = as.integer(ccd$exposed), + exposed = as.integer(ccd$exposed), + isCase = as.integer(cc$isCase)) + + colnames(tableToUpload) <- SqlRender::camelCaseToSnakeCase(colnames(tableToUpload)) + + DatabaseConnector::insertTable(connection = connection, + tableName = ""scratch.dbo.mschuemi_temp"", + data = tableToUpload, + dropTableIfExists = TRUE, + createTable = TRUE, + tempTable = FALSE, + oracleTempSchema = oracleTempSchema, + useMppBulkLoad = TRUE) + + covariateSettings <- FeatureExtraction::createTable1CovariateSettings() + + covsExposed <- FeatureExtraction::getDbCovariateData(connection = connection, + oracleTempSchema = oracleTempSchema, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = ""scratch.dbo"", + cohortTable = ""mschuemi_temp"", + cohortTableIsTemp = FALSE, + cohortId = 1, + covariateSettings = covariateSettings, + aggregated = TRUE) + FeatureExtraction::saveCovariateData(covsExposed, file.path(dataFolder, ""covsExposed"")) + covsUnexposed <- FeatureExtraction::getDbCovariateData(connection = connection, + oracleTempSchema = oracleTempSchema, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = ""scratch.dbo"", + cohortTable = ""mschuemi_temp"", + cohortTableIsTemp = FALSE, + cohortId = 0, + covariateSettings = covariateSettings, + aggregated = TRUE) + FeatureExtraction::saveCovariateData(covsUnexposed, file.path(dataFolder, ""covsUnexposed"")) + + executeSql(connection, ""TRUNCATE TABLE scratch.dbo.mschuemi_temp; DROP TABLE scratch.dbo.mschuemi_temp;"") + + # Create table ---------------------------------------------------------------------------------- + covariateData1 <- FeatureExtraction::loadCovariateData(file.path(dataFolder, ""covsExposed"")) + covariateData2 <- FeatureExtraction::loadCovariateData(file.path(dataFolder, ""covsUnexposed"")) + table1 <- FeatureExtraction::createTable1(covariateData1 = covariateData1, covariateData2 = covariateData2) + write.csv(table1, fileName, row.names = FALSE) +}","R" +"Pharmacogenetics","OHDSI/StudyProtocols","QuantifyingBiasInApapStudies/R/CustomCovariatesBuilder.R",".R","20472","337","# Copyright 2019 Observational Health Data Sciences and Informatics +# +# This file is part of AhasHfBkleAmputation +# +# 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. + + + +#' Create custom covariate settings +#' +#' @param useBmi Create a covariate for BMI (prior to cohort start). +#' @param useAlcohol Create a covariate for alcohol use (prior to cohort start). +#' @param useSmoking Create a covariate for smoking (prior to cohort start). +#' @param useDiabetesMedication Create a covariate for diabetes (medication use) (prior to cohort start). +#' @param useRheumatoidArthritis Create a covariate for RA (prior to cohort start). +#' @param useNonRa Create a covariate for non-RA, chronic back or chronic neck pain (prior to cohort start). +#' @param useFatigue Create a covariate for fatigue or lack of energy (prior to cohort start). +#' @param useMigraine Create a covariate for migraine or chronic headache (prior to cohort start). +#' +#' @export +createCustomCovariatesSettings <- function(useBmi = FALSE, + useAlcohol = FALSE, + useSmoking = FALSE, + useDiabetesMedication = FALSE, + useRheumatoidArthritis = FALSE, + useNonRa = FALSE, + useFatigue = FALSE, + useMigraine = FALSE) { + covariateSettings <- list(useBmi = useBmi, + useAlcohol = useAlcohol, + useSmoking = useSmoking, + useDiabetesMedication = useDiabetesMedication, + useRheumatoidArthritis = useRheumatoidArthritis, + useNonRa = useNonRa, + useFatigue = useFatigue, + useMigraine = useMigraine) + attr(covariateSettings, ""fun"") <- ""QuantifyingBiasInApapStudies::getDbCustomCovariatesData"" + class(covariateSettings) <- ""covariateSettings"" + return(covariateSettings) +} + +#' Get custom covariate information from the database +#' +#' @description +#' Constructs custom covariates for a cohort. +#' +#' @param covariateSettings An object of type \code{covariateSettings} as created using the +#' \code{\link{createCustomCovariatesSettings}} function. +#' +#' @details +#' This function uses the data in the CDM to construct a large set of covariates for the provided +#' cohort. The cohort is assumed to be in an existing temp table with these fields: 'subject_id', +#' 'cohort_definition_id', 'cohort_start_date'. Optionally, an extra field can be added containing the +#' unique identifier that will be used as rowID in the output. Typically, users don't call this +#' function directly. +#' +#' @param connection A connection to the server containing the schema as created using the +#' \code{connect} function in the \code{DatabaseConnector} package. +#' @param oracleTempSchema A schema where temp tables can be created in Oracle. +#' @param cdmDatabaseSchema The name of the database schema that contains the OMOP CDM instance. +#' Requires read permissions to this database. On SQL Server, this should +#' specifiy both the database and the schema, so for example +#' 'cdm_instance.dbo'. +#' @param cohortTable Name of the table holding the cohort for which we want to construct +#' covariates. If it is a temp table, the name should have a hash prefix, +#' e.g. '#temp_table'. If it is a non-temp table, it should include the +#' database schema, e.g. 'cdm_database.cohort'. +#' @param cohortId For which cohort ID should covariates be constructed? If set to -1, +#' covariates will be constructed for all cohorts in the specified cohort +#' table. +#' @param cdmVersion The version of the Common Data Model used. Currently only +#' \code{cdmVersion = ""5""} is supported. +#' @param rowIdField The name of the field in the cohort temp table that is to be used as the +#' row_id field in the output table. This can be especially usefull if there +#' is more than one period per person. +#' @param aggregated Should aggregate statistics be computed instead of covariates per +#' cohort entry? +#' +#' @return +#' Returns an object of type \code{covariateData}, containing information on the baseline covariates. +#' Information about multiple outcomes can be captured at once for efficiency reasons. This object is +#' a list with the following components: \describe{ \item{covariates}{An ffdf object listing the +#' baseline covariates per person in the cohorts. This is done using a sparse representation: +#' covariates with a value of 0 are omitted to save space. The covariates object will have three +#' columns: rowId, covariateId, and covariateValue. The rowId is usually equal to the person_id, +#' unless specified otherwise in the rowIdField argument.} \item{covariateRef}{An ffdf object +#' describing the covariates that have been extracted.} \item{metaData}{A list of objects with +#' information on how the covariateData object was constructed.} } +#' +#' @export +getDbCustomCovariatesData <- function(connection, + oracleTempSchema = NULL, + cdmDatabaseSchema, + cohortTable = ""#cohort_person"", + cohortId = -1, + cdmVersion = ""5"", + rowIdField = ""subject_id"", + covariateSettings, + aggregated = FALSE) { + if (aggregated) + stop(""Aggregation not supported"") + ParallelLogger::logInfo(""Creating custom covariates"") + covariates <- data.frame() + covariateRef <- data.frame() + analysisRef <- data.frame() + + if (covariateSettings$useBmi) { + analysisId <- 999 + sql <- SqlRender::loadRenderTranslateSql(""CreateBmiCovariate.sql"", + packageName = ""QuantifyingBiasInApapStudies"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + row_id_field = rowIdField, + cohort_temp_table = cohortTable, + cohort_id = cohortId, + analysis_id = analysisId) + covariates <- rbind(covariates, DatabaseConnector::querySql(connection, sql, snakeCaseToCamelCase = TRUE)) + covariateRef <- rbind(covariateRef, + data.frame(covariateId = c(1000, 2000, 3000) + analysisId, + covariateName = c(""BMI < 25"", ""25 <= BMI < 30"", ""BMI >= 30""), + analysisId = analysisId, + conceptId = 3036277)) + analysisRef <- rbind(analysisRef, + data.frame(analysisId = as.numeric(analysisId), + analysisName = ""BMI"", + domainId = ""Measurement"", + startDay = NA, + endDay = 0, + isBinary = ""Y"", + missingMeansZero = ""Y"")) + } + if (covariateSettings$useAlcohol) { + analysisId <- 998 + sql <- SqlRender::loadRenderTranslateSql(""CreateAlcoholCovariate.sql"", + packageName = ""QuantifyingBiasInApapStudies"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + row_id_field = rowIdField, + cohort_temp_table = cohortTable, + cohort_id = cohortId, + analysis_id = analysisId) + covariates <- rbind(covariates, DatabaseConnector::querySql(connection, sql, snakeCaseToCamelCase = TRUE)) + covariateRef <- rbind(covariateRef, + data.frame(covariateId = 1000 + analysisId, + covariateName = ""Regular alcohol drinker"", + analysisId = analysisId, + conceptId = 40770351)) + analysisRef <- rbind(analysisRef, + data.frame(analysisId = as.numeric(analysisId), + analysisName = ""Alcohol"", + domainId = ""ObserVation"", + startDay = NA, + endDay = 0, + isBinary = ""Y"", + missingMeansZero = ""Y"")) + } + if (covariateSettings$useSmoking) { + analysisId <- 997 + sql <- SqlRender::loadRenderTranslateSql(""CreateSmokingCovariate.sql"", + packageName = ""QuantifyingBiasInApapStudies"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + row_id_field = rowIdField, + cohort_temp_table = cohortTable, + cohort_id = cohortId, + analysis_id = analysisId) + covariates <- rbind(covariates, DatabaseConnector::querySql(connection, sql, snakeCaseToCamelCase = TRUE)) + covariateRef <- rbind(covariateRef, + data.frame(covariateId = 1000 + analysisId, + covariateName = ""Smoker"", + analysisId = analysisId, + conceptId = 40766929)) + analysisRef <- rbind(analysisRef, + data.frame(analysisId = as.numeric(analysisId), + analysisName = ""Smoking"", + domainId = ""ObserVation"", + startDay = NA, + endDay = 0, + isBinary = ""Y"", + missingMeansZero = ""Y"")) + } + if (covariateSettings$useDiabetesMedication) { + analysisId <- 996 + sql <- SqlRender::loadRenderTranslateSql(""CreateDiabetesCovariate.sql"", + packageName = ""QuantifyingBiasInApapStudies"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + row_id_field = rowIdField, + cohort_temp_table = cohortTable, + cohort_id = cohortId, + analysis_id = analysisId) + covariates <- rbind(covariates, DatabaseConnector::querySql(connection, sql, snakeCaseToCamelCase = TRUE)) + covariateRef <- rbind(covariateRef, + data.frame(covariateId = 1000 + analysisId, + covariateName = ""Diabetes (medication use)"", + analysisId = analysisId, + conceptId = 21600712)) + analysisRef <- rbind(analysisRef, + data.frame(analysisId = as.numeric(analysisId), + analysisName = ""Diabetes (medication use)"", + domainId = ""Drug"", + startDay = NA, + endDay = 0, + isBinary = ""Y"", + missingMeansZero = ""Y"")) + } + if (covariateSettings$useRheumatoidArthritis) { + analysisId <- 995 + sql <- SqlRender::loadRenderTranslateSql(""CreateRaCovariate.sql"", + packageName = ""QuantifyingBiasInApapStudies"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + row_id_field = rowIdField, + cohort_temp_table = cohortTable, + cohort_id = cohortId, + analysis_id = analysisId) + covariates <- rbind(covariates, DatabaseConnector::querySql(connection, sql, snakeCaseToCamelCase = TRUE)) + covariateRef <- rbind(covariateRef, + data.frame(covariateId = 1000 + analysisId, + covariateName = ""History of rheumatoid arthritis"", + analysisId = analysisId, + conceptId = 80809)) + analysisRef <- rbind(analysisRef, + data.frame(analysisId = as.numeric(analysisId), + analysisName = ""Rheumatoid arthritis"", + domainId = ""Condition"", + startDay = NA, + endDay = 0, + isBinary = ""Y"", + missingMeansZero = ""Y"")) + } + if (covariateSettings$useNonRa) { + analysisId <- 994 + sql <- SqlRender::loadRenderTranslateSql(""CreateNonRaCovariate.sql"", + packageName = ""QuantifyingBiasInApapStudies"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + row_id_field = rowIdField, + cohort_temp_table = cohortTable, + cohort_id = cohortId, + analysis_id = analysisId) + covariates <- rbind(covariates, DatabaseConnector::querySql(connection, sql, snakeCaseToCamelCase = TRUE)) + covariateRef <- rbind(covariateRef, + data.frame(covariateId = 1000 + analysisId, + covariateName = ""History of non-rheumatoid arthritis or chronic neck/back/joint pain"", + analysisId = analysisId, + conceptId = 4291025)) + analysisRef <- rbind(analysisRef, + data.frame(analysisId = as.numeric(analysisId), + analysisName = ""Non-rheumatoid arthritis or chronic neck/back/joint pain"", + domainId = ""Condition"", + startDay = NA, + endDay = 0, + isBinary = ""Y"", + missingMeansZero = ""Y"")) + } + if (covariateSettings$useFatigue) { + analysisId <- 993 + sql <- SqlRender::loadRenderTranslateSql(""CreateFatigueCovariate.sql"", + packageName = ""QuantifyingBiasInApapStudies"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + row_id_field = rowIdField, + cohort_temp_table = cohortTable, + cohort_id = cohortId, + analysis_id = analysisId) + covariates <- rbind(covariates, DatabaseConnector::querySql(connection, sql, snakeCaseToCamelCase = TRUE)) + covariateRef <- rbind(covariateRef, + data.frame(covariateId = 1000 + analysisId, + covariateName = ""History of fatigue or lack of energy"", + analysisId = analysisId, + conceptId = 439926)) + analysisRef <- rbind(analysisRef, + data.frame(analysisId = as.numeric(analysisId), + analysisName = ""Fatigue"", + domainId = ""Condition"", + startDay = NA, + endDay = 0, + isBinary = ""Y"", + missingMeansZero = ""Y"")) + } + if (covariateSettings$useMigraine) { + analysisId <- 992 + sql <- SqlRender::loadRenderTranslateSql(""CreateMigraineCovariate.sql"", + packageName = ""QuantifyingBiasInApapStudies"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + row_id_field = rowIdField, + cohort_temp_table = cohortTable, + cohort_id = cohortId, + analysis_id = analysisId) + covariates <- rbind(covariates, DatabaseConnector::querySql(connection, sql, snakeCaseToCamelCase = TRUE)) + covariateRef <- rbind(covariateRef, + data.frame(covariateId = 1000 + analysisId, + covariateName = ""History of migraines or frequent headaches"", + analysisId = analysisId, + conceptId = 318736)) + analysisRef <- rbind(analysisRef, + data.frame(analysisId = as.numeric(analysisId), + analysisName = ""Migraine"", + domainId = ""Condition"", + startDay = NA, + endDay = 0, + isBinary = ""Y"", + missingMeansZero = ""Y"")) + } + + covariates <- ff::as.ffdf(covariates) + covariateRef <- ff::as.ffdf(covariateRef) + analysisRef <- ff::as.ffdf(analysisRef) + metaData <- list(call = match.call()) + result <- list(covariates = covariates, + covariateRef = covariateRef, + analysisRef = analysisRef, + metaData = metaData) + class(result) <- ""covariateData"" + return(result) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","QuantifyingBiasInApapStudies/R/Report.R",".R","1455","31","# Copyright 2019 Observational Health Data Sciences and Informatics +# +# This file is part of QuantifyingBiasInApapStudies +# +# 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. + +#' Generate a report containing the main results +#' +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/). Do not use a folder on a network drive since this greatly impacts +#' performance. +#' +#' @export +generateReport <- function(outputFolder) { + fileName <- file.path(outputFolder, ""QuantifyingBiasInApapStudiesReport.docx"") + rmarkdown::render(system.file(""rmarkdown"", ""report.Rmd"", package = ""QuantifyingBiasInApapStudies""), + params = list(outputFolder = outputFolder), + output_file = fileName, + rmarkdown::word_document(toc = TRUE, fig_caption = TRUE)) + ParallelLogger::logInfo(""Report generated: "", fileName) +}","R" +"Pharmacogenetics","OHDSI/StudyProtocols","QuantifyingBiasInApapStudies/R/CaseControl.R",".R","17492","275","# Copyright 2019 Observational Health Data Sciences and Informatics +# +# This file is part of QuantifyingBiasInApapStudies +# +# 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. + +#' Run CohortMethod package +#' +#' @details +#' Run the CohortMethod package, which implements the comparative cohort design. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param cohortDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param cohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param outputFolder Name of local folder where the results were generated; make sure to use forward slashes +#' (/). Do not use a folder on a network drive since this greatly impacts +#' performance. +#' @param maxCores How many parallel cores should be used? If more cores are made available +#' this can speed up the analyses. +#' +#' @export +runCaseControl <- function(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable, + oracleTempSchema, + outputFolder, + maxCores) { + ccOutputFolder <- file.path(outputFolder, ""ccOutput"") + if (!file.exists(ccOutputFolder)) { + dir.create(ccOutputFolder) + } + ccAnalysisListFile <- system.file(""settings"", + ""ccAnalysisList.json"", + package = ""QuantifyingBiasInApapStudies"") + ccAnalysisList <- CaseControl::loadCcAnalysisList(ccAnalysisListFile) + tosList <- createTos(outputFolder = outputFolder) + # Note: using just 1 thread to get exposure data because bulk upload otherwise fails + results <- CaseControl::runCcAnalyses(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + exposureDatabaseSchema = cohortDatabaseSchema, + exposureTable = cohortTable, + outcomeDatabaseSchema = cohortDatabaseSchema, + outcomeTable = cohortTable, + outputFolder = ccOutputFolder, + oracleTempSchema = cohortDatabaseSchema, + ccAnalysisList = ccAnalysisList, + exposureOutcomeNestingCohortList = tosList, + prefetchExposureData = TRUE, + compressCaseDataFiles = TRUE, + getDbCaseDataThreads = min(3, maxCores), + selectControlsThreads = min(5, maxCores), + getDbExposureDataThreads = 1, + createCaseControlDataThreads = min(5, maxCores), + fitCaseControlModelThreads = min(5, maxCores)) + + ParallelLogger::logInfo(""Summarizing results"") + analysisSummary <- CaseControl::summarizeCcAnalyses(outcomeReference = results, + outputFolder = ccOutputFolder) + analysisSummary <- addCohortNames(analysisSummary, ""outcomeId"", ""outcomeName"") + analysisSummary <- addCcAnalysisDescription(analysisSummary, ""analysisId"", ""analysisDescription"") + write.csv(analysisSummary, file.path(outputFolder, ""ccAnalysisSummary.csv""), row.names = FALSE) +} + +addCcAnalysisDescription <- function(data, IdColumnName = ""analysisId"", nameColumnName = ""analysisDescription"") { + ccAnalysisListFile <- system.file(""settings"", + ""ccAnalysisList.json"", + package = ""QuantifyingBiasInApapStudies"") + ccAnalysisList <- CaseControl::loadCcAnalysisList(ccAnalysisListFile) + idToName <- lapply(ccAnalysisList, function(x) data.frame(analysisId = x$analysisId, description = as.character(x$description))) + idToName <- do.call(""rbind"", idToName) + names(idToName)[1] <- IdColumnName + names(idToName)[2] <- nameColumnName + data <- merge(data, idToName, all.x = TRUE) + # Change order of columns: + idCol <- which(colnames(data) == IdColumnName) + if (idCol < ncol(data) - 1) { + data <- data[, c(1:idCol, ncol(data) , (idCol + 1):(ncol(data) - 1))] + } + return(data) +} + +#' Create the case-control analyses details +#' +#' @details +#' This function creates files specifying the case-control analyses that will be performed. +#' +#' @param workFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' +#' @export +createCcAnalysesDetails <- function(workFolder) { + prior <- Cyclops::createPrior(""none"") + + getDbCaseDataArgs1 <- CaseControl::createGetDbCaseDataArgs(useNestingCohort = FALSE, + getVisits = FALSE) + + + samplingCriteria <- CaseControl::createSamplingCriteria(controlsPerCase = 4, + seed = 123) + + + selectControlsArgs1 <- CaseControl::createSelectControlsArgs(firstOutcomeOnly = TRUE, + washoutPeriod = 365 * 2, + minAge = 30, + controlSelectionCriteria = samplingCriteria) + + # Excluding one gender (8507 = male) explicitly to avoid redundancy: + defaultCovariateSettings <- FeatureExtraction::createCovariateSettings(useDemographicsAgeGroup = TRUE, + useDemographicsGender = TRUE, + useDemographicsIndexYear = TRUE, + excludedCovariateConceptIds = 8507) + + customCovariateSettings <- createCustomCovariatesSettings(useBmi = TRUE, + useAlcohol = TRUE, + useSmoking = TRUE, + useDiabetesMedication = TRUE) + + covariateSettings1 <- list(defaultCovariateSettings, customCovariateSettings) + + getDbExposureDataArgs1 <- CaseControl::createGetDbExposureDataArgs(covariateSettings = covariateSettings1) + + createCaseControlDataArgs1 <- CaseControl::createCreateCaseControlDataArgs(firstExposureOnly = FALSE, + riskWindowStart = -999990, + riskWindowEnd = 0) + + fitCaseControlModelArgs1 <- CaseControl::createFitCaseControlModelArgs(useCovariates = TRUE, + excludeCovariateIds = c(1999, 2999, 3999, 1998, 1997, 1996), + prior = prior) + + ccAnalysis1 <- CaseControl::createCcAnalysis(analysisId = 1, + description = ""Sampling, all time prior, adj. for age, sex & year"", + getDbCaseDataArgs = getDbCaseDataArgs1, + selectControlsArgs = selectControlsArgs1, + getDbExposureDataArgs = getDbExposureDataArgs1, + createCaseControlDataArgs = createCaseControlDataArgs1, + fitCaseControlModelArgs = fitCaseControlModelArgs1) + + fitCaseControlModelArgs2 <- CaseControl::createFitCaseControlModelArgs(useCovariates = TRUE, + prior = prior) + + ccAnalysis2 <- CaseControl::createCcAnalysis(analysisId = 2, + description = ""Sampling, all time prior, adj. for age, sex, year, BMI, alcohol, smoking & diabetes"", + getDbCaseDataArgs = getDbCaseDataArgs1, + selectControlsArgs = selectControlsArgs1, + getDbExposureDataArgs = getDbExposureDataArgs1, + createCaseControlDataArgs = createCaseControlDataArgs1, + fitCaseControlModelArgs = fitCaseControlModelArgs2) + + createCaseControlDataArgs2 <- CaseControl::createCreateCaseControlDataArgs(firstExposureOnly = FALSE, + riskWindowStart = -999990, + riskWindowEnd = -365) + + + ccAnalysis3 <- CaseControl::createCcAnalysis(analysisId = 3, + description = ""Sampling, year delay, adj. for age, sex & year"", + getDbCaseDataArgs = getDbCaseDataArgs1, + selectControlsArgs = selectControlsArgs1, + getDbExposureDataArgs = getDbExposureDataArgs1, + createCaseControlDataArgs = createCaseControlDataArgs2, + fitCaseControlModelArgs = fitCaseControlModelArgs1) + + ccAnalysis4 <- CaseControl::createCcAnalysis(analysisId = 4, + description = ""Sampling, year delay, adj. for age, sex, year, BMI, alcohol, smoking & diabetes"", + getDbCaseDataArgs = getDbCaseDataArgs1, + selectControlsArgs = selectControlsArgs1, + getDbExposureDataArgs = getDbExposureDataArgs1, + createCaseControlDataArgs = createCaseControlDataArgs2, + fitCaseControlModelArgs = fitCaseControlModelArgs2) + + matchingCriteria <- CaseControl::createMatchingCriteria(controlsPerCase = 4, + matchOnAge = TRUE, + ageCaliper = 2, + matchOnGender = TRUE, + matchOnTimeInCohort = TRUE, + daysInCohortCaliper = 365, + matchOnCareSite = TRUE) + + selectControlsArgs2 <- CaseControl::createSelectControlsArgs(firstOutcomeOnly = TRUE, + washoutPeriod = 365 * 2, + minAge = 30, + controlSelectionCriteria = matchingCriteria) + + getDbExposureDataArgs2 <- CaseControl::createGetDbExposureDataArgs(covariateSettings = customCovariateSettings) + + fitCaseControlModelArgs3 <- CaseControl::createFitCaseControlModelArgs(useCovariates = FALSE, + prior = prior) + + ccAnalysis5 <- CaseControl::createCcAnalysis(analysisId = 5, + description = ""Matching, all time prior"", + getDbCaseDataArgs = getDbCaseDataArgs1, + selectControlsArgs = selectControlsArgs2, + getDbExposureDataArgs = getDbExposureDataArgs2, + createCaseControlDataArgs = createCaseControlDataArgs1, + fitCaseControlModelArgs = fitCaseControlModelArgs3) + + fitCaseControlModelArgs4<- CaseControl::createFitCaseControlModelArgs(useCovariates = TRUE, + prior = prior) + + ccAnalysis6 <- CaseControl::createCcAnalysis(analysisId = 6, + description = ""Matching, all time prior, adj. for BMI, alcohol, smoking & diabetes"", + getDbCaseDataArgs = getDbCaseDataArgs1, + selectControlsArgs = selectControlsArgs2, + getDbExposureDataArgs = getDbExposureDataArgs2, + createCaseControlDataArgs = createCaseControlDataArgs1, + fitCaseControlModelArgs = fitCaseControlModelArgs4) + + createCaseControlDataArgs2 <- CaseControl::createCreateCaseControlDataArgs(firstExposureOnly = FALSE, + riskWindowStart = -999990, + riskWindowEnd = -365) + + ccAnalysis7 <- CaseControl::createCcAnalysis(analysisId = 7, + description = ""Matching, year delay"", + getDbCaseDataArgs = getDbCaseDataArgs1, + selectControlsArgs = selectControlsArgs2, + getDbExposureDataArgs = getDbExposureDataArgs2, + createCaseControlDataArgs = createCaseControlDataArgs2, + fitCaseControlModelArgs = fitCaseControlModelArgs3) + + ccAnalysis8 <- CaseControl::createCcAnalysis(analysisId = 8, + description = ""Matching, year delay, adj. for BMI, alcohol, smoking & diabetes"", + getDbCaseDataArgs = getDbCaseDataArgs1, + selectControlsArgs = selectControlsArgs2, + getDbExposureDataArgs = getDbExposureDataArgs2, + createCaseControlDataArgs = createCaseControlDataArgs2, + fitCaseControlModelArgs = fitCaseControlModelArgs4) + + ccAnalysisList <- list(ccAnalysis1, ccAnalysis2, ccAnalysis3, ccAnalysis4, ccAnalysis5, ccAnalysis6, ccAnalysis7, ccAnalysis8) + CaseControl::saveCcAnalysisList(ccAnalysisList, file.path(workFolder, ""ccAnalysisList.json"")) +} + +createTos <- function(outputFolder) { + pathToCsv <- system.file(""settings"", ""TosOfInterest.csv"", package = ""QuantifyingBiasInApapStudies"") + tosOfInterest <- read.csv(pathToCsv, stringsAsFactors = FALSE) + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""QuantifyingBiasInApapStudies"") + negativeControls <- read.csv(pathToCsv) + ts <- unique(tosOfInterest$targetId) + createTo <- function(i) { + targetId <- ts[i] + outcomeIds <- as.character(tosOfInterest$outcomeIds[tosOfInterest$targetId == targetId]) + outcomeIds <- as.numeric(strsplit(outcomeIds, split = "";"")[[1]]) + outcomeIds <- c(outcomeIds, negativeControls$outcomeId[negativeControls$targetId == targetId]) + + createSingleTo <- function(outcomeId) { + CaseControl::createExposureOutcomeNestingCohort(exposureId = targetId, outcomeId = outcomeId) + } + to <- lapply(outcomeIds, createSingleTo) + return(to) + } + tosList <- lapply(1:length(ts), createTo) + tosList <- do.call(c, tosList) + return(tosList) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","QuantifyingBiasInApapStudies/extras/PackageMaintenance.R",".R","2024","42","# Copyright 2019 Observational Health Data Sciences and Informatics +# +# This file is part of QuantifyingBiasInApapStudies +# +# 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. + +# Format and check code --------------------------------------------------- +OhdsiRTools::formatRFolder() +OhdsiRTools::checkUsagePackage(""QuantifyingBiasInApapStudies"") +OhdsiRTools::updateCopyrightYearFolder() + +# Create manual ----------------------------------------------------------- +unlink(""extras/QuantifyingBiasInApapStudies.pdf"") +shell(""R CMD Rd2pdf ./ --output=extras/QuantifyingBiasInApapStudies.pdf"") + +# Insert cohort definitions from ATLAS into package ----------------------- +ROhdsiWebApi::insertCohortDefinitionSetInPackage(fileName = ""inst/settings/CohortsToCreate.csv"", + baseUrl = Sys.getenv(""baseUrl""), + insertTableSql = TRUE, + insertCohortCreationR = TRUE, + generateStats = FALSE, + packageName = ""QuantifyingBiasInApapStudies"") + +# Create analysis details ------------------------------------------------- +source(""R/CohortMethod.R"") +createCmAnalysesDetails(""inst/settings/"") +source(""R/CaseControl.R"") +createCcAnalysesDetails(""inst/settings/"") + +# Store environment in which the study was executed ----------------------- +OhdsiRTools::insertEnvironmentSnapshotInPackage(""QuantifyingBiasInApapStudies"") +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","QuantifyingBiasInApapStudies/extras/ForProtocol.R",".R","11839","271","library(DatabaseConnector) + +connectionDetails <- createConnectionDetails(dbms = ""pdw"", + server = Sys.getenv(""PDW_SERVER""), + port = Sys.getenv(""PDW_PORT"")) + +cdmDatabaseSchema <- ""cdM_cprd_v1017.dbo"" +cohortDatabaseSchema <- ""scratch.dbo"" +cohortTable <- ""mschuemi_epi_688_cohorts"" +oracleTempSchema <- NULL +outputFolder <- ""s:/QuantifyingBiasInApapStudies"" +maxCores <- parallel::detectCores() + +conn <- connect(connectionDetails) + +# List all drugs in CPRD containing APAP ----------------------------------------------------------------- +sql <- "" +SELECT vocabulary_id AS coding_system, + concept_code AS code, + concept_name AS description, + COUNT(*) AS code_frequency +FROM @cdm_database_schema.drug_exposure +INNER JOIN @cdm_database_schema.concept_ancestor + ON drug_concept_id = descendant_concept_id +INNER JOIN @cdm_database_schema.concept + ON drug_source_concept_id = concept_id +WHERE ancestor_concept_id = 1125315 -- Acetaminophen +GROUP BY vocabulary_id, + concept_code, + concept_name; +"" + +table <- renderTranslateQuerySql(conn, sql, cdm_database_schema = cdmDatabaseSchema) +write.csv(table, ""documents/AppendixA.csv"", row.names = FALSE) + +# Identify all ingredients in drugs containing APAP ------------------------------------------------------- +sql <- "" +SELECT concept_id, + concept_name, + COUNT_BIG(*) AS concept_frequency +FROM @cdm_database_schema.drug_exposure +INNER JOIN @cdm_database_schema.concept_ancestor apap + ON drug_concept_id = apap.descendant_concept_id +INNER JOIN @cdm_database_schema.concept_ancestor other_ingredient + ON drug_concept_id = other_ingredient.descendant_concept_id +INNER JOIN @cdm_database_schema.concept + ON other_ingredient.ancestor_concept_id = concept_id +WHERE apap.ancestor_concept_id = 1125315 -- Acetaminophen + AND concept_class_id = 'Ingredient' +GROUP BY concept_id, + concept_name; +"" + +table <- renderTranslateQuerySql(conn, sql, cdm_database_schema = cdmDatabaseSchema, snakeCaseToCamelCase = TRUE) +write.csv(table, ""documents/IngredientsToExclude.csv"", row.names = FALSE) + +paste(table$conceptId, collapse = "", "") + +# Observed subjects over time ----------------------------------------------------------------------------- +sql <- "" +SELECT year, + COUNT(*) AS persons_observed +FROM ( + SELECT DISTINCT year, + mid_month + FROM ( + SELECT YEAR(observation_period_start_date) + CAST((MONTH(observation_period_start_date)-1) AS FLOAT)/12 AS year, + DATEFROMPARTS(YEAR(observation_period_start_date), MONTH(observation_period_start_date), 15) AS mid_month + FROM @cdm_database_schema.observation_period + + UNION ALL + + SELECT YEAR(observation_period_end_date) + CAST((MONTH(observation_period_end_date)-1) AS FLOAT)/12 AS year, + DATEFROMPARTS(YEAR(observation_period_end_date), MONTH(observation_period_end_date), 15) AS mid_month + FROM @cdm_database_schema.observation_period + ) temp +) months +INNER JOIN @cdm_database_schema.observation_period + ON mid_month >= observation_period_start_date + AND mid_month <= observation_period_end_date +GROUP BY year; +"" +data <- renderTranslateQuerySql(conn, sql, cdm_database_schema = cdmDatabaseSchema, snakeCaseToCamelCase = TRUE) + + +library(ggplot2) +require(scales) +maxY <- max(data$personsObserved) +ggplot(data, aes(x = year, y = personsObserved)) + + geom_rect(xmin = 2008, xmax = 2009, ymin = 0, ymax = maxY*1.2, color = NA, fill = rgb(0.1, 0.1, 0.1, alpha = 0.01)) + + geom_area(fill = rgb(0, 0, 0.8), alpha = 0.6) + + geom_vline(xintercept = c(2008, 2009), size = 1) + + geom_label(x = 2008.5, y = maxY*1.01, label = ""2008"", hjust = 0.5) + + # geom_label(x = 2015.5, y = maxY*1.01, label = ""Dec 31, 2014"", hjust = 0.5) + + scale_x_continuous(""Calendar time"") + + scale_y_continuous(""Persons observed"", labels = comma) +ggsave(""documents/cprdTime.png"", width = 11, height = 3) + +disconnect(conn) + +# Evaluate cohort definitions ---------------------------------------- +cohortsToCreate <- read.csv(""inst/settings/CohortsToCreate.csv"") +for (i in 1:nrow(cohortsToCreate)) { + jsonFileName <- file.path(""inst"",""cohorts"", paste0(cohortsToCreate$name[i], "".json"")) + sqlFileName <- file.path(""inst"",""sql"", ""sql_server"", paste0(cohortsToCreate$name[i], "".sql"")) + outputFile <- file.path(""documents"", paste0(""SourceCodeCheck_"", cohortsToCreate$name[i], "".html"")) + cohortJson <- readChar(jsonFileName, file.info(jsonFileName)$size) + cohortSql <- readChar(sqlFileName, file.info(sqlFileName)$size) + MethodEvaluation::checkCohortSourceCodes(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortJson = cohortJson, + cohortSql = cohortSql, + outputFile = outputFile) +} + +orphans <- MethodEvaluation::findOrphanSourceCodes(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + conceptName = ""Acetaminophen"", + conceptSynonyms = c(""Paracetamol"")) +View(orphans) +# Note: potential orphans found, but these turned out to be legacy STCM entries + +# Inspect cohorts --------------------------------------------- +CdmTools::launchCohortExplorer(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + cohortDefinitionId = 1) + +CdmTools::launchCohortExplorer(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + cohortDefinitionId = 2) + +# Power calculations case-control study ---------------------------------- +createCohorts(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable, + oracleTempSchema, + outputFolder) + +runCaseControl(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable, + oracleTempSchema, + outputFolder, + maxCores) + +ccOutputFolder <- file.path(outputFolder, ""ccOutput"") +omReference <- readRDS(file.path(ccOutputFolder, ""outcomeModelReference.rds"")) + +outcomeId <- 11666 +analysisId <- 1 + +computeMdrr <- function(outcomeId, analysisId) { + studyPopFile <- omReference$caseControlDataFile[omReference$outcomeId == outcomeId & omReference$analysisId == analysisId] + studyPop <- readRDS(file.path(ccOutputFolder, studyPopFile)) + mdrr <- CaseControl::computeMdrr(studyPop) + mdrr$analysisId <- analysisId + mdrr$outcomeId <- outcomeId + return(mdrr) +} +computeMdrrForAnalysis <- function(analysisId) { + mdrrs <- lapply(unique(omReference$outcomeId), computeMdrr, analysisId = analysisId) + return(do.call(rbind, mdrrs)) +} + +mdrrs <- lapply(unique(omReference$analysisId), computeMdrrForAnalysis) +mdrrs <- do.call(rbind, mdrrs) +mdrrs <- QuantifyingBiasInApapStudies:::addCohortNames(mdrrs, IdColumnName = ""outcomeId"", nameColumnName = ""outcomeName"") +pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""QuantifyingBiasInApapStudies"") +negativeControls <- read.csv(pathToCsv) +mdrrs$negativeControl <- ""No"" +mdrrs$negativeControl[mdrrs$outcomeId %in% negativeControls$outcomeId] <- ""Yes"" + +mdrrs <- mdrrs[order(mdrrs$analysisId, mdrrs$outcomeId), ] +write.csv(mdrrs, file.path(""documents"", ""AppendixB.csv""), row.names = FALSE) + +min(mdrrs$exposedControls, na.rm = TRUE) +max(mdrrs$exposedControls, na.rm = TRUE) + +# Power calculations cohort study ----------------------------------------- +createCohorts(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable, + oracleTempSchema, + outputFolder) + +runCohortMethod(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable, + oracleTempSchema, + outputFolder, + maxCores) + +cmOutputFolder <- file.path(outputFolder, ""cmOutput"") +omReference <- readRDS(file.path(cmOutputFolder, ""outcomeModelReference.rds"")) +outcomeId <- 11666 +analysisId <- 1 + +computeMdrr <- function(outcomeId, analysisId) { + studyPopFile <- omReference$studyPopFile[omReference$outcomeId == outcomeId & omReference$analysisId == analysisId] + studyPop <- readRDS(file.path(cmOutputFolder, studyPopFile)) + mdrr <- CohortMethod::computeMdrr(studyPop) + mdrr$analysisId <- analysisId + mdrr$outcomeId <- outcomeId + return(mdrr) +} +computeMdrrForAnalysis <- function(analysisId) { + mdrrs <- lapply(unique(omReference$outcomeId), computeMdrr, analysisId = analysisId) + return(do.call(rbind, mdrrs)) +} + +mdrrs <- lapply(unique(omReference$analysisId), computeMdrrForAnalysis) +mdrrs <- do.call(rbind, mdrrs) +mdrrs <- QuantifyingBiasInApapStudies:::addCohortNames(mdrrs, IdColumnName = ""outcomeId"", nameColumnName = ""outcomeName"") +mdrrs <- mdrrs[order(mdrrs$analysisId, mdrrs$outcomeId), ] +pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""QuantifyingBiasInApapStudies"") +negativeControls <- read.csv(pathToCsv) +mdrrs$negativeControl <- ""No"" +mdrrs$negativeControl[mdrrs$o %in% negativeControls$outcomeId] <- ""Yes"" +write.csv(mdrrs, file.path(""documents"", ""AppendixC.csv""), row.names = FALSE) + +# Get code lists for cohort definitions ----------------------------------------------- +pathToCsv <- system.file(""settings"", ""CohortsToCreate.csv"", package = ""QuantifyingBiasInApapStudies"") +cohortsToCreate <- read.csv(pathToCsv) +codeListsFolder <- file.path(""documents"", ""codeLists"") +if (!file.exists(codeListsFolder)) { + dir.create(codeListsFolder) +} +getCodeLists <- function(i) { + writeLines(paste(""Getting codelists for cohort:"", cohortsToCreate$name[i])) + conceptSets <- ROhdsiWebApi::getConceptSetsAndConceptsFromCohort(Sys.getenv(""baseUrl""), cohortsToCreate$atlasId[i]) + for (j in 1:length(conceptSets)) { + conceptSets[[1]]$name + conceptIds <- conceptSets[[1]]$includedConceptsDf$CONCEPT_ID + DatabaseConnector::insertTable(connection = conn, + tableName = ""#concepts"", + data = data.frame(concept_id = conceptIds), + dropTableIfExists = TRUE, + createTable = TRUE, + tempTable = TRUE, + oracleTempSchema = oracleTempSchema, + progressBar = TRUE) + + sql <- "" + SELECT DISTINCT condition_concept_id AS concept_id, + concept_code AS source_code, + vocabulary_id, + concept_name AS description + FROM @cdm_database_schema.condition_occurrence + INNER JOIN #concepts c + ON condition_concept_id = c.concept_id + INNER JOIN @cdm_database_schema.concept source_code + ON condition_source_concept_id = source_code.concept_id; + "" + codeList <- DatabaseConnector::renderTranslateQuerySql(conn, sql, cdm_database_schema = cdmDatabaseSchema, snakeCaseToCamelCase = TRUE) + fileName <- file.path(codeListsFolder, paste(conceptSets[[1]]$name, ""csv"", sep = ""."")) + write.csv(codeList, fileName, row.names = FALSE) + writeLines(paste(""- Saved code list"",fileName)) + } +} +lapply(1:nrow(cohortsToCreate), getCodeLists) + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","QuantifyingBiasInApapStudies/extras/PostHoc.R",".R","933","20"," + + +# Understanding why no estimate for renal cell carcinoma in analysis 4 +ccOutputFolder <- file.path(outputFolder, ""ccOutput"") +omr <- readRDS(file.path(ccOutputFolder, ""outcomeModelReference.rds"")) +idx <- omr$analysisId == 4 & omr$outcomeId == 11666 +om <- readRDS(file.path(ccOutputFolder, omr$modelFile[idx])) +summary(om) +# Ill-conditioned + +ccd <- readRDS(file.path(ccOutputFolder, omr$caseControlDataFile[idx])) +ed <- CaseControl::loadCaseControlsExposure(file.path(ccOutputFolder, omr$exposureDataFile[idx])) +undebug(CaseControl::fitCaseControlModel) +om <- CaseControl::fitCaseControlModel(caseControlData = ccd, + useCovariates = TRUE, + caseControlsExposure = ed, + prior = Cyclops::createPrior(""normal"", variance = 1), + control = Cyclops::createControl(noiseLevel = ""noisy"")) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","QuantifyingBiasInApapStudies/extras/InstallPackages.R",".R","7","1","# To do","R" +"Pharmacogenetics","OHDSI/StudyProtocols","QuantifyingBiasInApapStudies/extras/CodeToRun.R",".R","999","27","library(QuantifyingBiasInApapStudies) + +options(fftempdir = ""s:/FFtemp"") +connectionDetails <- createConnectionDetails(dbms = ""pdw"", + server = Sys.getenv(""PDW_SERVER""), + port = Sys.getenv(""PDW_PORT"")) +cdmDatabaseSchema <- ""cdm_cprd_v1017.dbo"" +cohortDatabaseSchema <- ""scratch.dbo"" +cohortTable <- ""mschuemi_epi_688_cohorts"" +oracleTempSchema <- NULL +outputFolder <- ""s:/QuantifyingBiasInApapStudies"" +maxCores <- parallel::detectCores() + +execute(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder, + createCohorts = TRUE, + runCohortMethod = TRUE, + runCaseControl = TRUE, + createPlotsAndTables = TRUE, + generateReport = TRUE, + maxCores = maxCores, + blind = FALSE) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CelecoxibPredictiveModels/R/EvaluatePredictiveModels.R",".R","3176","72","# Copyright 2015 Observational Health Data Sciences and Informatics +# +# This file is part of CelecoxibPredictiveModels +# +# 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. + +#' Compute evaluation metrics for the predictive models +#' +#' @details +#' This function computes the AUC and plots the ROC and calibration plots per predictive model. +#' +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes (/) +#' +#' @export +evaluatePredictiveModels <- function(outputFolder) { + + outcomeIds <- 10:16 + minOutcomeCount <- 25 + + testPlpDataFile <- file.path(outputFolder, ""testPlpData"") + testPlpData <- PatientLevelPrediction::loadPlpData(testPlpDataFile) + + counts <- summary(testPlpData)$outcomeCounts + for (outcomeId in outcomeIds){ + modelFile <- file.path(outputFolder, paste(""model_o"",outcomeId, "".rds"", sep = """")) + if (counts$eventCount[counts$outcomeId == outcomeId] > minOutcomeCount && file.exists(modelFile)){ + writeLines(paste(""- Evaluating model for outcome"", outcomeId)) + model <- readRDS(modelFile) + + predictionsFile <- file.path(outputFolder, paste(""predictions_o"",outcomeId, "".rds"", sep = """")) + if (file.exists(predictionsFile)){ + predictions <- readRDS(predictionsFile) + } else { + predictions <- PatientLevelPrediction::predictProbabilities(model, testPlpData) + saveRDS(predictions, predictionsFile) + } + + detailsFile <- file.path(outputFolder, paste(""details_o"",outcomeId, "".csv"", sep = """")) + if (!file.exists(detailsFile)){ + details <- PatientLevelPrediction::getModelDetails(model, testPlpData) + write.csv(details, detailsFile, row.names = FALSE) + } + + aucFile <- file.path(outputFolder, paste(""auc_o"",outcomeId, "".csv"", sep = """")) + if (!file.exists(aucFile)){ + auc <- PatientLevelPrediction::computeAuc(predictions, testPlpData, confidenceInterval = TRUE) + write.csv(auc, aucFile, row.names = FALSE) + } + + rocFile <- file.path(outputFolder, paste(""roc_o"",outcomeId, "".png"", sep = """")) + if (!file.exists(rocFile)){ + PatientLevelPrediction::plotRoc(predictions, testPlpData, fileName = rocFile) + } + + calibrationFile <- file.path(outputFolder, paste(""calibration_o"",outcomeId, "".png"", sep = """")) + if (!file.exists(calibrationFile)){ + PatientLevelPrediction::plotCalibration(predictions, testPlpData, numberOfStrata = 10, fileName = calibrationFile) + } + } + } +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CelecoxibPredictiveModels/R/Main.R",".R","4269","105","# Copyright 2015 Observational Health Data Sciences and Informatics +# +# This file is part of CelecoxibPredictiveModels +# +# 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. + +#' @title Execute OHDSI Celecoxib predictive modelsstudy +#' +#' @details +#' This function executes the OHDSI Celecoxib predictive models study. +#' +#' @return +#' TODO +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the \code{\link[DatabaseConnector]{createConnectionDetails}} +#' function in the DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. Note that for SQL Server, this should include +#' both the database and schema name, for example 'cdm_data.dbo'. +#' @param workDatabaseSchema Schema name where intermediate data can be stored. You will need to have write priviliges in this schema. Note that +#' for SQL Server, this should include both the database and schema name, for example 'cdm_data.dbo'. +#' @param studyCohortTable The name of the table that will be created in the work database schema. This table will hold the exposure and outcome +#' cohorts used in this study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write priviliges for storing temporary tables. +#' @param cdmVersion Version of the CDM. Can be ""4"" or ""5"" +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes (/) +#' +#' @examples \dontrun{ +#' connectionDetails <- createConnectionDetails(dbms = ""postgresql"", +#' user = ""joe"", +#' password = ""secret"", +#' server = ""myserver"") +#' +#' execute(connectionDetails, +#' cdmDatabaseSchema = ""cdm_data"", +#' workDatabaseSchema = ""results"", +#' oracleTempSchema = NULL, +#' outputFolder = ""c:/temp/study_results"", +#' cdmVersion = ""5"") +#' +#' } +#' +#' @export +execute <- function(connectionDetails, + cdmDatabaseSchema, + workDatabaseSchema = cdmDatabaseSchema, + studyCohortTable = ""ohdsi_celecoxib_prediction"", + oracleTempSchema = NULL, + cdmVersion = 5, + outputFolder, + createCohorts = TRUE, + createPredictiveModels = TRUE, + evaluatePredictiveModels = TRUE, + packageResultsForSharing = TRUE) { + + if (cdmVersion == 4) { + stop(""CDM version 4 not supported"") + } + + if (!file.exists(outputFolder)) + dir.create(outputFolder) + + if (createCohorts) { + writeLines(""Creating exposure and outcome cohorts"") + createCohorts(connectionDetails, + cdmDatabaseSchema, + workDatabaseSchema, + studyCohortTable, + oracleTempSchema, + cdmVersion, + outputFolder) + } + + if (createPredictiveModels) { + writeLines(""Creating predictive models"") + createPredictiveModels(connectionDetails, + cdmDatabaseSchema, + workDatabaseSchema, + studyCohortTable, + oracleTempSchema, + cdmVersion, + outputFolder) + } + + if (evaluatePredictiveModels) { + writeLines(""Evaluate predictive models"") + evaluatePredictiveModels(outputFolder) + } + + if (packageResultsForSharing) { + writeLines(""Packaging results"") + packageResults(outputFolder) + } +} + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CelecoxibPredictiveModels/R/CreatePredictiveModels.R",".R","12499","175","# Copyright 2015 Observational Health Data Sciences and Informatics +# +# This file is part of CelecoxibPredictiveModels +# +# 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. + +#' Create the exposure and outcome cohorts +#' +#' @details +#' This function creates the predictive outcomes for the different outcomes. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the \code{\link[DatabaseConnector]{createConnectionDetails}} +#' function in the DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. Note that for SQL Server, this should include +#' both the database and schema name, for example 'cdm_data.dbo'. +#' @param workDatabaseSchema Schema name where intermediate data can be stored. You will need to have write priviliges in this schema. Note that +#' for SQL Server, this should include both the database and schema name, for example 'cdm_data.dbo'. +#' @param studyCohortTable The name of the table that will be created in the work database schema. This table will hold the exposure and outcome +#' cohorts used in this study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write priviliges for storing temporary tables. +#' @param cdmVersion Version of the CDM. Can be ""4"" or ""5"" +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes (/) +#' +#' @export +createPredictiveModels <- function(connectionDetails, + cdmDatabaseSchema, + workDatabaseSchema, + studyCohortTable = ""ohdsi_celecoxib_prediction"", + oracleTempSchema, + cdmVersion = 5, + outputFolder) { + + outcomeIds <- 10:16 + minOutcomeCount <- 25 + + plpDataFile <- file.path(outputFolder, ""plpData"") + if (file.exists(plpDataFile)) { + plpData <- PatientLevelPrediction::loadPlpData(plpDataFile) + } else { + writeLines(""- Extracting cohorts/covariates/outcomes"") + conn <- DatabaseConnector::connect(connectionDetails) + sql <- ""SELECT descendant_concept_id FROM @cdm_database_schema.concept_ancestor WHERE ancestor_concept_id = 1118084"" + sql <- SqlRender::renderSql(sql, cdm_database_schema = cdmDatabaseSchema)$sql + sql <- SqlRender::translateSql(sql, targetDialect = connectionDetails$dbms)$sql + celecoxibDrugs <- DatabaseConnector::querySql(conn, sql) + celecoxibDrugs <- celecoxibDrugs[,1] + RJDBC::dbDisconnect(conn) + + covariateSettings <- PatientLevelPrediction::createCovariateSettings(useCovariateDemographics = TRUE, + useCovariateDemographicsGender = TRUE, + useCovariateDemographicsRace = TRUE, + useCovariateDemographicsEthnicity = TRUE, + useCovariateDemographicsAge = TRUE, + useCovariateDemographicsYear = TRUE, + useCovariateDemographicsMonth = TRUE, + useCovariateConditionOccurrence = TRUE, + useCovariateConditionOccurrence365d = TRUE, + useCovariateConditionOccurrence30d = TRUE, + useCovariateConditionOccurrenceInpt180d = TRUE, + useCovariateConditionEra = TRUE, + useCovariateConditionEraEver = TRUE, + useCovariateConditionEraOverlap = TRUE, + useCovariateConditionGroup = TRUE, + useCovariateConditionGroupMeddra = TRUE, + useCovariateConditionGroupSnomed = TRUE, + useCovariateDrugExposure = TRUE, + useCovariateDrugExposure365d = TRUE, + useCovariateDrugExposure30d = TRUE, + useCovariateDrugEra = TRUE, + useCovariateDrugEra365d = TRUE, + useCovariateDrugEra30d = TRUE, + useCovariateDrugEraOverlap = TRUE, + useCovariateDrugEraEver = TRUE, + useCovariateDrugGroup = TRUE, + useCovariateProcedureOccurrence = TRUE, + useCovariateProcedureOccurrence365d = TRUE, + useCovariateProcedureOccurrence30d = TRUE, + useCovariateProcedureGroup = TRUE, + useCovariateObservation = TRUE, + useCovariateObservation365d = TRUE, + useCovariateObservation30d = TRUE, + useCovariateObservationCount365d = TRUE, + useCovariateMeasurement = TRUE, + useCovariateMeasurement365d = TRUE, + useCovariateMeasurement30d = TRUE, + useCovariateMeasurementCount365d = TRUE, + useCovariateMeasurementBelow = TRUE, + useCovariateMeasurementAbove = TRUE, + useCovariateConceptCounts = TRUE, + useCovariateRiskScores = TRUE, + useCovariateRiskScoresCharlson = TRUE, + useCovariateRiskScoresDCSI = TRUE, + useCovariateRiskScoresCHADS2 = TRUE, + useCovariateRiskScoresCHADS2VASc = TRUE, + useCovariateInteractionYear = FALSE, + useCovariateInteractionMonth = FALSE, + excludedCovariateConceptIds = celecoxibDrugs, + includedCovariateConceptIds = c(), + deleteCovariatesSmallCount = 100) + + + + + plpData <- PatientLevelPrediction::getDbPlpData(connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = workDatabaseSchema, + cohortTable = studyCohortTable, + cohortIds = 1, + useCohortEndDate = FALSE, + windowPersistence = 365, + covariateSettings = covariateSettings, + outcomeDatabaseSchema = workDatabaseSchema, + outcomeTable = studyCohortTable, + outcomeIds = outcomeIds, + cdmVersion = cdmVersion) + + + PatientLevelPrediction::savePlpData(plpData, plpDataFile) + } + + trainPlpDataFile <- file.path(outputFolder, ""trainPlptData"") + testPlpDataFile <- file.path(outputFolder, ""testPlpData"") + if (file.exists(trainPlpDataFile) && + file.exists(testPlpDataFile)) { + trainPlpData <- PatientLevelPrediction::loadPlpData(trainPlpDataFile) + } else { + writeLines(""Creating train-test split"") + parts <- PatientLevelPrediction::splitData(plpData, c(0.75, 0.25)) + + PatientLevelPrediction::savePlpData(parts[[1]], trainPlpDataFile) + PatientLevelPrediction::savePlpData(parts[[2]], testPlpDataFile) + + trainPlpData <- parts[[1]] + testPlpData <- parts[[2]] + + sumTrainPlpData <- summary(trainPlpData) + sumTestPlpData <- summary(testPlpData) + + write.csv(c(summary(trainPlpData)$subjectCount, summary(trainPlpData)$windowCount), file.path(outputFolder, ""trainCohortSize.csv""), row.names = FALSE) + write.csv(addOutcomeNames(summary(trainPlpData)$outcomeCounts), file.path(outputFolder, ""trainOutcomeCounts.csv""), row.names = FALSE) + write.csv(c(summary(testPlpData)$subjectCount, summary(testPlpData)$windowCount), file.path(outputFolder, ""testCohortSize.csv""), row.names = FALSE) + write.csv(addOutcomeNames(summary(trainPlpData)$outcomeCounts), file.path(outputFolder, ""testOutcomeCounts.csv""), row.names = FALSE) + } + counts <- summary(trainPlpData)$outcomeCounts + for (outcomeId in outcomeIds){ + writeLines(paste(outcomeId)) + modelFile <- file.path(outputFolder, paste(""model_o"",outcomeId, "".rds"", sep = """")) + if (counts$eventCount[counts$outcomeId == outcomeId] > minOutcomeCount && + !file.exists(modelFile)){ + writeLines(paste(""- Fitting model for outcome"", outcomeId)) + control = Cyclops::createControl(noiseLevel = ""quiet"", + cvType = ""auto"", + startingVariance = 0.1, + threads = 10) + + + model <- PatientLevelPrediction::fitPredictiveModel(trainPlpData, + outcomeId = outcomeId, + modelType = ""logistic"", + control = control) + saveRDS(model, modelFile) + } + } +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CelecoxibPredictiveModels/R/CreateCohorts.R",".R","10641","174","# Copyright 2015 Observational Health Data Sciences and Informatics +# +# This file is part of CelecoxibPredictiveModels +# +# 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. + + +#' Create the exposure and outcome cohorts +#' +#' @details +#' This function will create the exposure and outcome cohorts following the definitions included in this package. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the \code{\link[DatabaseConnector]{createConnectionDetails}} +#' function in the DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. Note that for SQL Server, this should include +#' both the database and schema name, for example 'cdm_data.dbo'. +#' @param workDatabaseSchema Schema name where intermediate data can be stored. You will need to have write priviliges in this schema. Note that +#' for SQL Server, this should include both the database and schema name, for example 'cdm_data.dbo'. +#' @param studyCohortTable The name of the table that will be created in the work database schema. This table will hold the exposure and outcome +#' cohorts used in this study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write priviliges for storing temporary tables. +#' @param cdmVersion Version of the CDM. Can be ""4"" or ""5"" +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes (/) +#' +#' @export +createCohorts <- function(connectionDetails, + cdmDatabaseSchema, + workDatabaseSchema, + studyCohortTable = ""ohdsi_celecoxib_prediction"", + oracleTempSchema, + cdmVersion = 5, + outputFolder) { + conn <- DatabaseConnector::connect(connectionDetails) + + # Create study cohort table structure: + sql <- ""IF OBJECT_ID('@work_database_schema.@study_cohort_table', 'U') IS NOT NULL + DROP TABLE @work_database_schema.@study_cohort_table; + CREATE TABLE @work_database_schema.@study_cohort_table (cohort_definition_id INT, subject_id BIGINT, cohort_start_date DATE, cohort_end_date DATE);"" + sql <- SqlRender::renderSql(sql, work_database_schema = workDatabaseSchema, study_cohort_table = studyCohortTable)$sql + sql <- SqlRender::translateSql(sql, targetDialect = connectionDetails$dbms)$sql + DatabaseConnector::executeSql(conn, sql, progressBar = FALSE, reportOverallTime = FALSE) + + writeLines(""- Creating exposure cohort"") + sql <- SqlRender::loadRenderTranslateSql(""Celecoxib.sql"", + ""CelecoxibPredictiveModels"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable, + cohort_definition_id = 1) + DatabaseConnector::executeSql(conn, sql) + + writeLines(""- Creating myocardial infarction cohort"") + sql <- SqlRender::loadRenderTranslateSql(""MyocardialInfarction.sql"", + ""CelecoxibPredictiveModels"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable, + cohort_definition_id = 10) + DatabaseConnector::executeSql(conn, sql) + + writeLines(""- Creating myocardial infarction and ischemic death cohort"") + sql <- SqlRender::loadRenderTranslateSql(""MiAndIschemicDeath.sql"", + ""CelecoxibPredictiveModels"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable, + cohort_definition_id = 11) + DatabaseConnector::executeSql(conn, sql) + + writeLines(""- Creating gastrointestinal hemorrhage cohort"") + sql <- SqlRender::loadRenderTranslateSql(""GiHemorrhage.sql"", + ""CelecoxibPredictiveModels"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable, + cohort_definition_id = 12) + DatabaseConnector::executeSql(conn, sql) + + writeLines(""- Creating angioedema cohort"") + sql <- SqlRender::loadRenderTranslateSql(""Angioedema.sql"", + ""CelecoxibPredictiveModels"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable, + cohort_definition_id = 13) + DatabaseConnector::executeSql(conn, sql) + + writeLines(""- Creating acute renal failure cohort"") + sql <- SqlRender::loadRenderTranslateSql(""AcuteRenalFailure.sql"", + ""CelecoxibPredictiveModels"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable, + cohort_definition_id = 14) + DatabaseConnector::executeSql(conn, sql) + + writeLines(""- Creating drug induced liver injury cohort"") + sql <- SqlRender::loadRenderTranslateSql(""DrugInducedLiverInjury.sql"", + ""CelecoxibPredictiveModels"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable, + cohort_definition_id = 15) + DatabaseConnector::executeSql(conn, sql) + + writeLines(""- Creating heart failure cohort"") + sql <- SqlRender::loadRenderTranslateSql(""HeartFailure.sql"", + ""CelecoxibPredictiveModels"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable, + cohort_definition_id = 16) + DatabaseConnector::executeSql(conn, sql) + + # Check number of subjects per cohort: + sql <- ""SELECT cohort_definition_id, COUNT(*) AS count FROM @work_database_schema.@study_cohort_table GROUP BY cohort_definition_id"" + sql <- SqlRender::renderSql(sql, work_database_schema = workDatabaseSchema, study_cohort_table = studyCohortTable)$sql + sql <- SqlRender::translateSql(sql, targetDialect = connectionDetails$dbms)$sql + counts <- DatabaseConnector::querySql(conn, sql) + names(counts) <- SqlRender::snakeCaseToCamelCase(names(counts)) + counts <- addOutcomeNames(counts, ""cohortDefinitionId"") + write.csv(counts, file.path(outputFolder,""CohortCounts.csv"")) + print(counts) + + RJDBC::dbDisconnect(conn) +} + +#' Add names to a data frame with outcome IDs +#' +#' @param data The data frame to add the outcome names to +#' @param outcomeIdColumnName The name of the column in the data frame that holds the outcome IDs. +#' +#' @export +addOutcomeNames <- function(data, outcomeIdColumnName = ""outcomeId""){ + idToName <- data.frame(outcomeId = c(1,10,11,12,13,14,15,16), + cohortName = c(""Exposure"", + ""Myocardial infarction"", + ""Myocardial infarction and ischemic death"", + ""Gastrointestinal hemorrhage"", + ""Angioedema"", + ""Acute renal failure"", + ""Drug induced liver injury"", + ""Heart failure"")) + names(idToName)[1] <- outcomeIdColumnName + data <- merge(data, idToName) + return(data) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CelecoxibPredictiveModels/R/TestCode.R",".R","1099","28",".testCode <- function(user,pw) { + library(CelecoxibPredictiveModels) + options(fftempdir = ""s:/FFtemp"") + + dbms <- ""pdw"" + #user <- NULL + #pw <- NULL + server <- ""JRDUSAPSCTL01"" + port <- 17001 + connectionDetails <- DatabaseConnector::createConnectionDetails(dbms = dbms, + server = server, + user = user, + password = pw, + port = port) + cdmDatabaseSchema <- ""cdm_truven_mdcd_v5.dbo"" + workDatabaseSchema <- ""scratch.dbo"" + studyCohortTable <- ""ohdsi_celecoxib_prediction"" + oracleTempSchema <- NULL + cdmVersion <- ""5"" + outputFolder <- ""S:/temp/CelecoxibPredictiveModels"" + + execute(connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + workDatabaseSchema = workDatabaseSchema, + studyCohortTable = studyCohortTable, + outputFolder = outputFolder) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CelecoxibPredictiveModels/R/PackageResultsForSharing.R",".R","970","28","# Copyright 2015 Observational Health Data Sciences and Informatics +# +# This file is part of CelecoxibPredictiveModels +# +# 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. + +#' Package the results for sharing with OHDSI researchers +#' +#' @details +#' This function packages the results. +#' +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes (/) +#' +#' @export +packageResults <- function(outputFolder = outputFolder) { + # TODO +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CelecoxibPredictiveModels/tests/testthat.R",".R","94","5","library(testthat) +library(CelecoxibPredictiveModels) + +test_check(""CelecoxibPredictiveModels"") +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","KeppraAngioedema/R/Main.R",".R","6847","139","# Copyright 2016 Observational Health Data Sciences and Informatics +# +# This file is part of KeppraAngioedema +# +# 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. + +#' Execute OHDSI Keppra and the Risk of Angioedema study +#' +#' @details +#' This function executes the OHDSI Keppra and the Risk of Angioedema study. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param workDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param studyCohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param cdmVersion Version of the CDM. Can be ""4"" or ""5"" +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/). Do not use a folder on a network drive since this greatly impacts +#' performance. +#' @param createCohorts Create the studyCohortTable table with the exposure and outcome cohorts? +#' @param runAnalyses Perform the cohort method analyses? +#' @param packageResults Package the results for sharing? +#' @param maxCores How many parallel cores should be used? If more cores are made available +#' this can speed up the analyses. +#' +#' @examples +#' \dontrun{ +#' connectionDetails <- createConnectionDetails(dbms = ""postgresql"", +#' user = ""joe"", +#' password = ""secret"", +#' server = ""myserver"") +#' +#' execute(connectionDetails, +#' cdmDatabaseSchema = ""cdm_data"", +#' workDatabaseSchema = ""results"", +#' studyCohortTable = ""ohdsi_keppra_angioedema"", +#' oracleTempSchema = NULL, +#' outputFolder = ""c:/temp/study_results"", +#' maxCores = 4) +#' } +#' +#' @export +execute <- function(connectionDetails, + cdmDatabaseSchema, + workDatabaseSchema = cdmDatabaseSchema, + studyCohortTable = ""ohdsi_keppra_angioedema"", + oracleTempSchema = workDatabaseSchema, + cdmVersion = 5, + outputFolder, + createCohorts = TRUE, + runAnalyses = TRUE, + packageResults = TRUE, + maxCores = 4) { + + if (cdmVersion == 4) { + stop(""CDM version 4 not supported"") + } + + if (!file.exists(outputFolder)) + dir.create(outputFolder) + + cmOutputFolder <- file.path(outputFolder, ""cmOutput"") + if (!file.exists(cmOutputFolder)) + dir.create(cmOutputFolder) + + if (createCohorts) { + writeLines(""Creating exposure and outcome cohorts"") + createCohorts(connectionDetails, + cdmDatabaseSchema, + workDatabaseSchema, + studyCohortTable, + oracleTempSchema, + cdmVersion, + outputFolder) + writeLines("""") + } + + if (runAnalyses) { + writeLines(""Running analyses"") + cmAnalysisListFile <- system.file(""settings"", + ""cmAnalysisList.txt"", + package = ""KeppraAngioedema"") + cmAnalysisList <- CohortMethod::loadCmAnalysisList(cmAnalysisListFile) + drugComparatorOutcomesListFile <- system.file(""settings"", + ""drugComparatorOutcomesList.txt"", + package = ""KeppraAngioedema"") + drugComparatorOutcomesList <- CohortMethod::loadDrugComparatorOutcomesList(drugComparatorOutcomesListFile) + CohortMethod::runCmAnalyses(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + exposureDatabaseSchema = workDatabaseSchema, + exposureTable = studyCohortTable, + outcomeDatabaseSchema = workDatabaseSchema, + outcomeTable = studyCohortTable, + outputFolder = cmOutputFolder, + oracleTempSchema = oracleTempSchema, + cmAnalysisList = cmAnalysisList, + cdmVersion = cdmVersion, + drugComparatorOutcomesList = drugComparatorOutcomesList, + getDbCohortMethodDataThreads = 1, + createStudyPopThreads = min(3, maxCores), + createPsThreads = 1, + psCvThreads = min(16, maxCores), + computeCovarBalThreads = min(3, maxCores), + trimMatchStratifyThreads = min(10, maxCores), + fitOutcomeModelThreads = max(1, round(maxCores/4)), + outcomeCvThreads = min(4, maxCores), + refitPsForEveryOutcome = FALSE) + writeLines("""") + } + if (packageResults) { + writeLines(""Packaging results in export folder for sharing"") + packageResults(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + outputFolder = outputFolder) + writeLines("""") + } + invisible(NULL) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","KeppraAngioedema/R/CreateCohorts.R",".R","10852","136","# Copyright 2016 Observational Health Data Sciences and Informatics +# +# This file is part of KeppraAngioedema +# +# 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. + + +#' Create the exposure and outcome cohorts +#' +#' @details +#' This function will create the exposure and outcome cohorts following the definitions included in +#' this package. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param workDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param studyCohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param cdmVersion Version of the CDM. Can be ""4"" or ""5"" +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/). +#' +#' @export +createCohorts <- function(connectionDetails, + cdmDatabaseSchema, + workDatabaseSchema, + studyCohortTable = ""ohdsi_keppra_angioedema"", + oracleTempSchema, + cdmVersion = 5, + outputFolder) { + conn <- DatabaseConnector::connect(connectionDetails) + + # Create study cohort table structure: + sql <- ""IF OBJECT_ID('@work_database_schema.@study_cohort_table', 'U') IS NOT NULL\n DROP TABLE @work_database_schema.@study_cohort_table;\n CREATE TABLE @work_database_schema.@study_cohort_table (cohort_definition_id INT, subject_id BIGINT, cohort_start_date DATE, cohort_end_date DATE);"" + sql <- SqlRender::renderSql(sql, + work_database_schema = workDatabaseSchema, + study_cohort_table = studyCohortTable)$sql + sql <- SqlRender::translateSql(sql, targetDialect = connectionDetails$dbms)$sql + DatabaseConnector::executeSql(conn, sql, progressBar = FALSE, reportOverallTime = FALSE) + + writeLines(""- Creating treatment cohort"") + sql <- SqlRender::loadRenderTranslateSql(""Treatment.sql"", + ""KeppraAngioedema"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable, + cohort_definition_id = 1) + DatabaseConnector::executeSql(conn, sql) + + writeLines(""- Creating comparator cohort"") + sql <- SqlRender::loadRenderTranslateSql(""Comparator.sql"", + ""KeppraAngioedema"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable, + cohort_definition_id = 2) + DatabaseConnector::executeSql(conn, sql) + + writeLines(""- Creating angioedema cohort"") + sql <- SqlRender::loadRenderTranslateSql(""Angioedema.sql"", + ""KeppraAngioedema"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable, + cohort_definition_id = 3) + DatabaseConnector::executeSql(conn, sql) + + writeLines(""- Creating negative control outcome cohort"") + sql <- SqlRender::loadRenderTranslateSql(""NegativeControls.sql"", + ""KeppraAngioedema"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable) + DatabaseConnector::executeSql(conn, sql) + + # Check number of subjects per cohort: + sql <- ""SELECT cohort_definition_id, COUNT(*) AS count FROM @work_database_schema.@study_cohort_table GROUP BY cohort_definition_id"" + sql <- SqlRender::renderSql(sql, + work_database_schema = workDatabaseSchema, + study_cohort_table = studyCohortTable)$sql + sql <- SqlRender::translateSql(sql, targetDialect = connectionDetails$dbms)$sql + counts <- DatabaseConnector::querySql(conn, sql) + names(counts) <- SqlRender::snakeCaseToCamelCase(names(counts)) + counts <- addCohortNames(counts, ""cohortDefinitionId"") + write.csv(counts, file.path(outputFolder, ""CohortCounts.csv"")) + writeLines(""Cohort counts:"") + print(counts) + + RJDBC::dbDisconnect(conn) + invisible(NULL) +} + +addCohortNames <- function(data, IdColumnName = ""outcomeId"", nameColumnName = ""outcomeName"") { + idToName <- data.frame(cohortId = c(1, 2, 3, 29056, 29735, 73842, 74396, 75344, 75576, 77650, 78786, 78804, 79072, 79903, 80217, 80494, 80665, 80951, 133141, 133228, 133834, 134453, 134461, 134898, 136773, 136937, 137057, 138387, 139099, 140480, 140949, 141663, 141932, 192367, 192606, 192964, 193016, 193326, 194997, 195562, 195588, 195873, 196162, 197032, 197320, 197684, 198075, 198199, 199067, 199876, 200528, 200588, 253796, 256722, 258180, 260134, 261326, 261880, 312437, 313792, 314054, 316993, 317109, 317585, 318800, 319843, 321596, 372409, 373478, 374914, 376103, 376415, 378160, 378424, 378425, 380731, 432436, 432851, 433163, 433440, 433516, 434056, 434926, 435459, 436027, 437409, 437833, 439080, 440328, 440358, 440448, 440814, 441284, 441589, 442013, 443344, 4002650, 4193869, 4205509, 4291005, 4311499, 4324765, 43531027), + cohortName = c(""Levetiracetam"", + ""Phenytoin"", + ""Angioedema"", + ""Sialoadenitis"", ""Candidiasis of mouth"", ""Enthesopathy of elbow region"", ""Temporomandibular joint disorder"", ""Intervertebral disc disorder"", ""Irritable bowel syndrome"", ""Aseptic necrosis of bone"", ""Pleurisy"", ""Fibrocystic disease of breast"", ""Inflammatory disorder of breast"", ""Effusion of joint"", ""Anal finding"", ""Arthropathy associated with another disorder"", ""Malignant neoplasm of thorax"", ""Candidiasis of urogenital site"", ""Tinea pedis"", ""Dental caries"", ""Atopic dermatitis"", ""Bursitis"", ""Tietze's disease"", ""Non-toxic uninodular goiter"", ""Rosacea"", ""Benign neoplasm of endocrine gland"", ""Paronychia"", ""Thyrotoxicosis"", ""Ingrowing nail"", ""Impetigo"", ""Infestation by Sarcoptes scabiei var hominis"", ""Osteomyelitis"", ""Seborrheic keratosis"", ""Dysplasia of cervix"", ""Paraplegia"", ""Infectious disorder of kidney"", ""Cystic disease of kidney"", ""Urge incontinence of urine"", ""Prostatitis"", ""Hemorrhoids"", ""Cystitis"", ""Leukorrhea"", ""Inflammatory disease of the uterus"", ""Hyperplasia of prostate"", ""Acute renal failure syndrome"", ""Dysuria"", ""Condyloma acuminatum"", ""Pyelonephritis"", ""Inflammatory disease of female pelvic organs AND/OR tissues"", ""Prolapse of female genital organs"", ""Ascites"", ""Injury of abdomen"", ""Pneumothorax"", ""Bronchopneumonia"", ""Pneumonia due to Gram negative bacteria"", ""Croup"", ""Viral pneumonia"", ""Atelectasis"", ""Dyspnea"", ""Paroxysmal tachycardia"", ""Aortic valve disorder"", ""Tricuspid valve disorder"", ""Respiratory arrest"", ""Aortic aneurysm"", ""Gastroesophageal reflux disease"", ""Mitral valve disorder"", ""Peripheral venous insufficiency"", ""Sciatica"", ""Presbyopia"", ""Tetraplegia"", ""Retinopathy"", ""Hypermetropia"", ""Otorrhea"", ""Astigmatism"", ""Blepharitis"", ""Otitis externa"", ""Symbolic dysfunction"", ""Secondary malignant neoplastic disease"", ""Deficiency of macronutrients"", ""Dysthymia"", ""Duodenitis"", ""Late effects of cerebrovascular disease"", ""Iridocyclitis"", ""Staphylococcal infectious disease"", ""Coxsackie virus disease"", ""Intracranial injury"", ""Hypokalemia"", ""Dyspareunia"", ""Pneumococcal infectious disease"", ""Lipoma"", ""Appendicitis"", ""Torticollis"", ""Open-angle glaucoma"", ""Endocarditis"", ""Burn"", ""Barrett's esophagus"", ""Plantar fasciitis"", ""Bacterial intestinal infectious disease"", ""Arthritis of elbow"", ""Viral hepatitis"", ""Primary malignant neoplasm of respiratory tract"", ""Arthropathy of knee joint"", ""Mononeuropathy of upper limb"")) + names(idToName)[1] <- IdColumnName + names(idToName)[2] <- nameColumnName + data <- merge(data, idToName, all.x = TRUE) + # Change order of columns: + idCol <- which(colnames(data) == IdColumnName) + if (idCol < ncol(data) - 1) { + data <- data[, c(1:idCol, ncol(data) , (idCol+1):(ncol(data)-1))] + } + return(data) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","KeppraAngioedema/R/SubmitResults.R",".R","1859","48","# Copyright 2016 Observational Health Data Sciences and Informatics +# +# This file is part of KeppraAngioedema +# +# 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. + +#' Submit the study results to the study coordinating center +#' +#' @details +#' This will upload the file \code{StudyResults.zip} to the study coordinating center using Amazon S3. +#' This requires an active internet connection. +#' +#' @param exportFolder The path to the folder containing the \code{StudyResults.zip} file. +#' @param key The key string as provided by the study coordinator +#' @param secret The secret string as provided by the study coordinator +#' +#' @return +#' TRUE if the upload was successful. +#' +#' @export +submitResults <- function(exportFolder, key, secret) { + zipName <- file.path(exportFolder, ""StudyResults.zip"") + if (!file.exists(zipName)) { + stop(paste(""Cannot find file"", zipName)) + } + writeLines(paste0(""Uploading file '"", zipName, ""' to study coordinating center"")) + result <- OhdsiSharing::putS3File(file = zipName, + bucket = ""ohdsi-study-angioedema"", + key = key, + secret = secret) + if (result) { + writeLines(""Upload complete"") + } else { + writeLines(""Upload failed. Please contact the study coordinator"") + } + invisible(result) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","KeppraAngioedema/R/CreateTablesAndFigures.R",".R","11083","192","# Copyright 2016 Observational Health Data Sciences and Informatics +# +# This file is part of KeppraAngioedema +# +# 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. + + +#' Create tables and figures +#' +#' @details +#' Creates tables and figures for viewing and interpreting the results. Requires that the +#' \code{\link{execute}} function has completed first. +#' +#' @param exportFolder The path to the export folder containing the results. +#' +#' @export +createTableAndFigures <- function(exportFolder) { + analysisSummary <- read.csv(file.path(exportFolder, ""MainResults.csv"")) + + tablesAndFiguresFolder <- file.path(exportFolder, ""tablesAndFigures"") + if (!file.exists(tablesAndFiguresFolder)) + dir.create(tablesAndFiguresFolder) + + negControlCohortIds <- unique(analysisSummary$outcomeId[analysisSummary$outcomeId != 3]) + # Calibrate p-values and draw calibration plots: + for (analysisId in unique(analysisSummary$analysisId)) { + negControlSubset <- analysisSummary[analysisSummary$analysisId == analysisId & analysisSummary$outcomeId %in% + negControlCohortIds, ] + negControlSubset <- negControlSubset[!is.na(negControlSubset$logRr) & negControlSubset$logRr != + 0, ] + if (nrow(negControlSubset) > 10) { + null <- EmpiricalCalibration::fitMcmcNull(negControlSubset$logRr, negControlSubset$seLogRr) + subset <- analysisSummary[analysisSummary$analysisId == analysisId, ] + calibratedP <- EmpiricalCalibration::calibrateP(null, subset$logRr, subset$seLogRr) + subset$calibratedP <- calibratedP$p + subset$calibratedP_lb95ci <- calibratedP$lb95ci + subset$calibratedP_ub95ci <- calibratedP$ub95ci + mcmc <- attr(null, ""mcmc"") + subset$null_mean <- mean(mcmc$chain[, 1]) + subset$null_sd <- 1/sqrt(mean(mcmc$chain[, 2])) + analysisSummary$calibratedP[analysisSummary$analysisId == analysisId] <- subset$calibratedP + analysisSummary$calibratedP_lb95ci[analysisSummary$analysisId == analysisId] <- subset$calibratedP_lb95ci + analysisSummary$calibratedP_ub95ci[analysisSummary$analysisId == analysisId] <- subset$calibratedP_ub95ci + analysisSummary$null_mean[analysisSummary$analysisId == analysisId] <- subset$null_mean + analysisSummary$null_sd[analysisSummary$analysisId == analysisId] <- subset$null_sd + EmpiricalCalibration::plotCalibration(negControlSubset$logRr, + negControlSubset$seLogRr, + fileName = file.path(tablesAndFiguresFolder, + paste0(""Cal_a"", analysisId, "".png""))) + EmpiricalCalibration::plotCalibrationEffect(negControlSubset$logRr, + negControlSubset$seLogRr, + fileName = file.path(tablesAndFiguresFolder, + paste0(""CalEffectNoHoi_a"", analysisId, "".png""))) + hoi <- analysisSummary[analysisSummary$analysisId == analysisId & !(analysisSummary$outcomeId %in% + negControlCohortIds), ] + EmpiricalCalibration::plotCalibrationEffect(negControlSubset$logRr, + negControlSubset$seLogRr, + hoi$logRr, + hoi$seLogRr, + fileName = file.path(tablesAndFiguresFolder, + paste0(""CalEffect_a"", analysisId, "".png""))) + EmpiricalCalibration::plotCalibrationEffect(negControlSubset$logRr, + negControlSubset$seLogRr, + hoi$logRr, + hoi$seLogRr, + showCis = TRUE, + fileName = file.path(tablesAndFiguresFolder, + paste0(""CalEffectCi_a"", analysisId, "".png""))) + } + } + write.csv(analysisSummary, file.path(tablesAndFiguresFolder, + ""EmpiricalCalibration.csv""), row.names = FALSE) + + # Balance plots: + balance <- read.csv(file.path(exportFolder, ""Balance1On1Matching.csv"")) + CohortMethod::plotCovariateBalanceScatterPlot(balance, + fileName = file.path(tablesAndFiguresFolder, + ""BalanceScatterPlot1On1Matching.png"")) + CohortMethod::plotCovariateBalanceOfTopVariables(balance, + fileName = file.path(tablesAndFiguresFolder, + ""BalanceTopVariables1On1Matching.png"")) + + balance <- read.csv(file.path(exportFolder, ""BalanceVarRatioMatching.csv"")) + CohortMethod::plotCovariateBalanceScatterPlot(balance, + fileName = file.path(tablesAndFiguresFolder, + ""BalanceScatterPlotVarRatioMatching.png"")) + CohortMethod::plotCovariateBalanceOfTopVariables(balance, + fileName = file.path(tablesAndFiguresFolder, + ""BalanceTopVariablesVarRatioMatching.png"")) + + ### Population characteristics table + balance <- read.csv(file.path(exportFolder, ""BalanceVarRatioMatching.csv"")) + + ## Age + age <- balance[grep(""Age group:"", balance$covariateName), ] + age <- data.frame(group = age$covariateName, + countTreated = age$beforeMatchingSumTreated, + countComparator = age$beforeMatchingSumComparator, + fractionTreated = age$beforeMatchingMeanTreated, + fractionComparator = age$beforeMatchingMeanComparator) + + # Add removed age group (if any): + removedCovars <- read.csv(file.path(exportFolder, ""RemovedCovars.csv"")) + removedAgeGroup <- removedCovars[grep(""Age group:"", removedCovars$covariateName), ] + if (nrow(removedAgeGroup) == 1) { + totalTreated <- age$countTreated[1] / age$fractionTreated[1] + totalComparator <- age$countComparator[1] / age$fractionComparator[1] + missingFractionTreated <- 1 - sum(age$fractionTreated) + missingFractionComparator <- 1 - sum(age$fractionComparator) + removedAgeGroup <- data.frame(group = removedAgeGroup$covariateName, + countTreated = round(missingFractionTreated * totalTreated), + countComparator = round(missingFractionComparator * totalComparator), + fractionTreated = missingFractionTreated, + fractionComparator = missingFractionComparator) + age <- rbind(age, removedAgeGroup) + } + age$start <- gsub(""Age group: "", """", gsub(""-.*$"", """", age$group)) + age$start <- as.integer(age$start) + age <- age[order(age$start), ] + age$start <- NULL + + ## Gender + gender <- balance[grep(""Gender"", balance$covariateName), ] + gender <- data.frame(group = gender$covariateName, + countTreated = gender$beforeMatchingSumTreated, + countComparator = gender$beforeMatchingSumComparator, + fractionTreated = gender$beforeMatchingMeanTreated, + fractionComparator = gender$beforeMatchingMeanComparator) + # Add removed gender (if any): + removedGender <- removedCovars[grep(""Gender"", removedCovars$covariateName), ] + if (nrow(removedGender) == 1) { + totalTreated <- gender$countTreated[1] / gender$fractionTreated[1] + missingFractionTreated <- 1 - sum(gender$fractionTreated) + missingFractionComparator <- 1 - sum(gender$fractionComparator) + removedGender <- data.frame(group = removedGender$covariateName, + countTreated = round(missingFractionTreated * totalTreated), + countComparator = round(missingFractionComparator * totalTreated), + fractionTreated = missingFractionTreated, + fractionComparator = missingFractionComparator) + gender <- rbind(gender, removedGender) + } + gender$group <- gsub(""Gender = "", """", gender$group) + + ## Calendar year + year <- balance[grep(""Index year"", balance$covariateName), ] + year <- data.frame(group = year$covariateName, + countTreated = year$beforeMatchingSumTreated, + countComparator = year$beforeMatchingSumComparator, + fractionTreated = year$beforeMatchingMeanTreated, + fractionComparator = year$beforeMatchingMeanComparator) + # Add removed year (if any): + removedYear <- removedCovars[grep(""Index year"", removedCovars$covariateName), ] + if (nrow(removedYear) == 1) { + totalTreated <- year$countTreated[1] / year$fractionTreated[1] + missingFractionTreated <- 1 - sum(year$fractionTreated) + missingFractionComparator <- 1 - sum(year$fractionComparator) + removedYear <- data.frame(group = removedYear$covariateName, + countTreated = round(missingFractionTreated * totalTreated), + countComparator = round(missingFractionComparator * totalTreated), + fractionTreated = missingFractionTreated, + fractionComparator = missingFractionComparator) + year <- rbind(year, removedYear) + } + year$group <- gsub(""Index year: "", """", year$group) + year <- year[order(year$group), ] + + table <- rbind(age, gender, year) + write.csv(table, file.path(tablesAndFiguresFolder, ""PopChar.csv""), row.names = FALSE) + + ### Attrition diagrams + attrition <- read.csv(file.path(exportFolder, ""Attrition1On1Matching.csv"")) + object <- list() + attr(object, ""metaData"") <- list(attrition = attrition) + CohortMethod::drawAttritionDiagram(object, fileName = file.path(tablesAndFiguresFolder, ""Attr1On1Matching.png"")) + + attrition <- read.csv(file.path(exportFolder, ""AttritionVarRatioMatching.csv"")) + object <- list() + attr(object, ""metaData"") <- list(attrition = attrition) + CohortMethod::drawAttritionDiagram(object, fileName = file.path(tablesAndFiguresFolder, ""AttrVarRatioMatching.png"")) + +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","KeppraAngioedema/R/PackageResults.R",".R","12809","231","# Copyright 2016 Observational Health Data Sciences and Informatics +# +# This file is part of KeppraAngioedema +# +# 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. + +#' Package the results for sharing with OHDSI researchers +#' +#' @details +#' This function packages the results. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' @param minCellCount The minimum number of subjects contributing to a count before it can be included in the results. +#' +#' @export +packageResults <- function(connectionDetails, cdmDatabaseSchema, outputFolder, minCellCount = 5) { + exportFolder <- file.path(outputFolder, ""export"") + if (!file.exists(exportFolder)) + dir.create(exportFolder) + + createMetaData(connectionDetails, cdmDatabaseSchema, exportFolder) + cmOutputFolder <- file.path(outputFolder, ""cmOutput"") + outcomeReference <- readRDS(file.path(cmOutputFolder, ""outcomeModelReference.rds"")) + analysisSummary <- CohortMethod::summarizeAnalyses(outcomeReference) + analysisSummary <- addCohortNames(analysisSummary, ""outcomeId"", ""outcomeName"") + analysisSummary <- addCohortNames(analysisSummary, ""targetId"", ""targetName"") + analysisSummary <- addCohortNames(analysisSummary, ""comparatorId"", ""comparatorName"") + analysisSummary <- addAnalysisDescriptions(analysisSummary) + + cohortMethodDataFolder <- outcomeReference$cohortMethodDataFolder[outcomeReference$analysisId == + 3 & outcomeReference$outcomeId == 3] + cohortMethodData <- CohortMethod::loadCohortMethodData(cohortMethodDataFolder) + + ### Write results table ### + write.csv(analysisSummary, file.path(exportFolder, ""MainResults.csv""), row.names = FALSE) + + ### Main attrition table ### + strataFile <- outcomeReference$strataFile[outcomeReference$analysisId == 3 & outcomeReference$outcomeId == + 3] + strata <- readRDS(strataFile) + attrition <- CohortMethod::getAttritionTable(strata) + write.csv(attrition, file.path(exportFolder, ""AttritionVarRatioMatching.csv""), row.names = FALSE) + strataFile <- outcomeReference$strataFile[outcomeReference$analysisId == 2 & outcomeReference$outcomeId == + 3] + strata <- readRDS(strataFile) + attrition <- CohortMethod::getAttritionTable(strata) + write.csv(attrition, file.path(exportFolder, ""Attrition1On1Matching.csv""), row.names = FALSE) + + ### Main propensity score plots ### + psFileName <- outcomeReference$sharedPsFile[outcomeReference$sharedPsFile != """"][1] + ps <- readRDS(psFileName) + CohortMethod::plotPs(ps, fileName = file.path(exportFolder, ""PsPrefScale.png"")) + CohortMethod::plotPs(ps, scale = ""propensity"", fileName = file.path(exportFolder, ""Ps.png"")) + strataFile <- outcomeReference$strataFile[outcomeReference$analysisId == 3 & outcomeReference$outcomeId == + 3] + strata <- readRDS(strataFile) + CohortMethod::plotPs(strata, + unfilteredData = ps, + fileName = file.path(exportFolder, ""PsAfterVarRatioMatchingPrefScale.png"")) + CohortMethod::plotPs(strata, + unfilteredData = ps, + scale = ""propensity"", + fileName = file.path(exportFolder, ""PsAfterVarRatioMatching.png"")) + strataFile <- outcomeReference$strataFile[outcomeReference$analysisId == 2 & outcomeReference$outcomeId == + 3] + strata <- readRDS(strataFile) + CohortMethod::plotPs(strata, + unfilteredData = ps, + fileName = file.path(exportFolder, ""PsAfter1On1MatchingPrefScale.png"")) + CohortMethod::plotPs(strata, + unfilteredData = ps, + scale = ""propensity"", + fileName = file.path(exportFolder, ""PsAfter1On1Matching.png"")) + + ### Propensity model ### + psFileName <- outcomeReference$sharedPsFile[outcomeReference$sharedPsFile != """"][1] + ps <- readRDS(psFileName) + psModel <- CohortMethod::getPsModel(ps, cohortMethodData) + write.csv(psModel, file.path(exportFolder, ""PsModel.csv""), row.names = FALSE) + + ### Main balance tables ### + strataFile <- outcomeReference$strataFile[outcomeReference$analysisId == 3 & outcomeReference$outcomeId == + 3] + strata <- readRDS(strataFile) + balance <- CohortMethod::computeCovariateBalance(strata, cohortMethodData) + idx <- balance$beforeMatchingSumTreated < minCellCount + balance$beforeMatchingSumTreated[idx] <- NA + balance$beforeMatchingMeanTreated[idx] <- NA + idx <- balance$beforeMatchingSumComparator < minCellCount + balance$beforeMatchingSumComparator[idx] <- NA + balance$beforeMatchingMeanComparator[idx] <- NA + idx <- balance$afterMatchingSumTreated < minCellCount + balance$afterMatchingSumTreated[idx] <- NA + balance$afterMatchingMeanTreated[idx] <- NA + idx <- balance$afterMatchingSumComparator < minCellCount + balance$afterMatchingSumComparator[idx] <- NA + balance$afterMatchingMeanComparator[idx] <- NA + write.csv(balance, file.path(exportFolder, ""BalanceVarRatioMatching.csv""), row.names = FALSE) + + strataFile <- outcomeReference$strataFile[outcomeReference$analysisId == 2 & outcomeReference$outcomeId == + 3] + strata <- readRDS(strataFile) + balance <- CohortMethod::computeCovariateBalance(strata, cohortMethodData) + idx <- balance$beforeMatchingSumTreated < minCellCount + balance$beforeMatchingSumTreated[idx] <- NA + balance$beforeMatchingMeanTreated[idx] <- NA + idx <- balance$beforeMatchingSumComparator < minCellCount + balance$beforeMatchingSumComparator[idx] <- NA + balance$beforeMatchingMeanComparator[idx] <- NA + idx <- balance$afterMatchingSumTreated < minCellCount + balance$afterMatchingSumTreated[idx] <- NA + balance$afterMatchingMeanTreated[idx] <- NA + idx <- balance$afterMatchingSumComparator < minCellCount + balance$afterMatchingSumComparator[idx] <- NA + balance$afterMatchingMeanComparator[idx] <- NA + write.csv(balance, file.path(exportFolder, ""Balance1On1Matching.csv""), row.names = FALSE) + + ### Removed (redunant) covariates ### + if (!is.null(cohortMethodData$metaData$deletedCovariateIds)) { + idx <- is.na(ffbase::ffmatch(cohortMethodData$covariateRef$covariateId, ff::as.ff(cohortMethodData$metaData$deletedCovariateIds))) + removedCovars <- ff::as.ram(cohortMethodData$covariateRef[ffbase::ffwhich(idx, idx == FALSE), ]) + write.csv(removedCovars, file.path(exportFolder, ""RemovedCovars.csv""), row.names = FALSE) + } + + ### Main Kaplan Meier plots ### + strataFile <- outcomeReference$strataFile[outcomeReference$analysisId == 2 & outcomeReference$outcomeId == + 3] + strata <- readRDS(strataFile) + CohortMethod::plotKaplanMeier(strata, + includeZero = FALSE, + fileName = file.path(exportFolder, ""KaplanMeierPerProtocol.png"")) + strataFile <- outcomeReference$strataFile[outcomeReference$analysisId == 6 & outcomeReference$outcomeId == + 3] + strata <- readRDS(strataFile) + CohortMethod::plotKaplanMeier(strata, + includeZero = FALSE, + fileName = file.path(exportFolder, ""KaplanMeierIntentToTreat.png"")) + + ### Main outcome models ### + outcomeModelFile <- outcomeReference$outcomeModelFile[outcomeReference$analysisId == 4 & outcomeReference$outcomeId == + 3] + outcomeModel <- readRDS(outcomeModelFile) + if (outcomeModel$outcomeModelStatus == ""OK"") { + model <- CohortMethod::getOutcomeModel(outcomeModel, cohortMethodData) + write.csv(model, file.path(exportFolder, ""OutcomeModelPerProtocol.csv""), row.names = FALSE) + } + + outcomeModelFile <- outcomeReference$outcomeModelFile[outcomeReference$analysisId == 8 & outcomeReference$outcomeId == + 3] + outcomeModel <- readRDS(outcomeModelFile) + if (outcomeModel$outcomeModelStatus == ""OK"") { + model <- CohortMethod::getOutcomeModel(outcomeModel, cohortMethodData) + write.csv(model, file.path(exportFolder, ""OutcomeModelIntentToTreat.csv""), row.names = FALSE) + } + + ### Add all to zip file ### + zipName <- file.path(exportFolder, ""StudyResults.zip"") + OhdsiSharing::compressFolder(exportFolder, zipName) + writeLines(paste(""\nStudy results are ready for sharing at:"", zipName)) +} + +#' Create metadata file +#' +#' @details +#' Creates a file containing metadata about the source data (taken from the cdm_source table) and R +#' package versions. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param exportFolder The name of the folder where the metadata file should be created. +#' +#' @export +createMetaData <- function(connectionDetails, cdmDatabaseSchema, exportFolder) { + conn <- DatabaseConnector::connect(connectionDetails) + sql <- ""SELECT * FROM @cdm_database_schema.cdm_source"" + sql <- SqlRender::renderSql(sql, cdm_database_schema = cdmDatabaseSchema)$sql + sql <- SqlRender::translateSql(sql, targetDialect = connectionDetails$dbms)$sql + cdmSource <- DatabaseConnector::querySql(conn, sql) + RJDBC::dbDisconnect(conn) + lines <- paste(names(cdmSource), cdmSource[1, ], sep = "": "") + lines <- c(lines, paste(""OhdsiRTools version"", packageVersion(""OhdsiRTools""), sep = "": "")) + lines <- c(lines, paste(""SqlRender version"", packageVersion(""SqlRender""), sep = "": "")) + lines <- c(lines, + paste(""DatabaseConnector version"", packageVersion(""DatabaseConnector""), sep = "": "")) + lines <- c(lines, paste(""Cyclops version"", packageVersion(""Cyclops""), sep = "": "")) + lines <- c(lines, + paste(""FeatureExtraction version"", packageVersion(""FeatureExtraction""), sep = "": "")) + lines <- c(lines, paste(""CohortMethod version"", packageVersion(""CohortMethod""), sep = "": "")) + lines <- c(lines, paste(""OhdsiSharing version"", packageVersion(""OhdsiSharing""), sep = "": "")) + lines <- c(lines, + paste(""KeppraAngioedema version"", packageVersion(""KeppraAngioedema""), sep = "": "")) + write(lines, file.path(exportFolder, ""MetaData.txt"")) + invisible(NULL) +} + +addAnalysisDescriptions <- function(object) { + cmAnalysisListFile <- system.file(""settings"", ""cmAnalysisList.txt"", package = ""KeppraAngioedema"") + cmAnalysisList <- CohortMethod::loadCmAnalysisList(cmAnalysisListFile) + # Add analysis description: + for (i in 1:length(cmAnalysisList)) { + object$analysisDescription[object$analysisId == cmAnalysisList[[i]]$analysisId] <- cmAnalysisList[[i]]$description + } + # Change order of columns: + aidCol <- which(colnames(object) == ""analysisId"") + if (aidCol < ncol(object) - 1) { + object <- object[, c(1:aidCol, ncol(object) , (aidCol+1):(ncol(object)-1))] + } + return(object) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","KeppraAngioedema/R/CreateStudyAnalysesDetails.R",".R","28420","515","# Copyright 2016 Observational Health Data Sciences and Informatics +# +# This file is part of KeppraAngioedema +# +# 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. + +#' Create the analyses details +#' +#' @details +#' This function creates files specifying the analyses that will be performed. +#' +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes (/) +#' +#' @export +createAnalysesDetails <- function(outputFolder) { + + angioedemaId <- 3 + negativeControlIds <- c(29056, + 29735, + 73842, + 74396, + 75344, + 75576, + 77650, + 78786, + 78804, + 79072, + 79903, + 80217, + 80494, + 80665, + 80951, + 133141, + 133228, + 133834, + 134453, + 134461, + 134898, + 136773, + 136937, + 137057, + 138387, + 139099, + 140480, + 140949, + 141663, + 141932, + 192367, + 192606, + 192964, + 193016, + 193326, + 194997, + 195562, + 195588, + 195873, + 196162, + 197032, + 197320, + 197684, + 198075, + 198199, + 199067, + 199876, + 200528, + 200588, + 253796, + 256722, + 258180, + 260134, + 261326, + 261880, + 312437, + 313792, + 314054, + 316993, + 317109, + 317585, + 318800, + 319843, + 321596, + 372409, + 373478, + 374914, + 376103, + 376415, + 378160, + 378424, + 378425, + 380731, + 432436, + 432851, + 433163, + 433440, + 433516, + 434056, + 434926, + 435459, + 436027, + 437409, + 437833, + 439080, + 440328, + 440358, + 440448, + 440814, + 441284, + 441589, + 442013, + 443344, + 4002650, + 4193869, + 4205509, + 4291005, + 4311499, + 4324765, + 43531027) + excludedCovariateConceptIds <- c(702773, + 711584, + 711585, + 711586, + 711587, + 711588, + 711589, + 711615, + 711620, + 711621, + 711644, + 711645, + 734514, + 734519, + 734543, + 740910, + 740939, + 740940, + 740971, + 740992, + 740995, + 740996, + 740999, + 741000, + 741001, + 741022, + 19000857, + 19006201, + 19006202, + 19006235, + 19022290, + 19025782, + 19025783, + 19025784, + 19025785, + 19060002, + 19060401, + 19062939, + 19064833, + 19078781, + 19085062, + 19086166, + 19086167, + 19088478, + 19099448, + 19099449, + 19099450, + 19099461, + 19101553, + 19102504, + 19102835, + 19103081, + 19104539, + 19104540, + 19104541, + 19104542, + 19104549, + 19104550, + 19104551, + 19104602, + 19104603, + 19104604, + 19106807, + 19107017, + 19107287, + 19111376, + 19111377, + 19111378, + 19111379, + 19111380, + 19111381, + 19111382, + 19111383, + 19111386, + 19115093, + 19116034, + 19124115, + 19124116, + 19125803, + 19125804, + 19132401, + 19132402, + 19134946, + 19134947, + 19135179, + 19135378, + 40020027, + 40052545, + 40052546, + 40052547, + 40052548, + 40061698, + 40061699, + 40070681, + 40070682, + 40075252, + 40075255, + 40075257, + 40075258, + 40075259, + 40075260, + 40075261, + 40075262, + 40075263, + 40075264, + 40075265, + 40075266, + 40075267, + 40075270, + 40075271, + 40075272, + 40119293, + 40131124, + 40132106, + 40135474, + 40135475, + 40141414, + 40154738, + 40154739, + 40163204, + 40163205, + 40163206, + 40163207, + 40163208, + 40163209, + 40163210, + 40163211, + 40163212, + 40163213, + 40163214, + 40163215, + 40163218, + 40163219, + 40163220, + 40163221, + 40163222, + 40163223, + 40163228, + 40163229, + 40163230, + 40163231, + 40163232, + 40163233, + 40163234, + 40163235, + 40163236, + 40163237, + 40163238, + 40163241, + 40163243, + 40163244, + 40163245, + 40163246, + 40163251, + 40163252, + 40163253, + 40167308, + 40167309, + 40167310, + 40167311, + 40167313, + 40167314, + 40167315, + 40238910, + 40238911, + 40238912, + 40238920, + 40238921, + 40244397, + 40244398, + 40244399, + 40244400, + 40244401, + 40244402, + 42900977, + 42901023, + 42901024, + 42901025, + 42901674, + 42901704, + 42901705, + 42901706, + 42901707, + 42901708, + 42902608, + 45776841, + 45776842, + 45776843) + + dcos <- CohortMethod::createDrugComparatorOutcomes(targetId = 1, + comparatorId = 2, + excludedCovariateConceptIds = excludedCovariateConceptIds, + outcomeIds = c(angioedemaId, + negativeControlIds)) + drugComparatorOutcomesList <- list(dcos) + + covarSettings <- FeatureExtraction::createCovariateSettings(useCovariateDemographics = TRUE, + useCovariateDemographicsGender = TRUE, + useCovariateDemographicsRace = TRUE, + useCovariateDemographicsEthnicity = TRUE, + useCovariateDemographicsAge = TRUE, + useCovariateDemographicsYear = TRUE, + useCovariateDemographicsMonth = TRUE, + useCovariateConditionOccurrence = TRUE, + useCovariateConditionOccurrence365d = TRUE, + useCovariateConditionOccurrence30d = TRUE, + useCovariateConditionOccurrenceInpt180d = TRUE, + useCovariateConditionEra = TRUE, + useCovariateConditionEraEver = TRUE, + useCovariateConditionEraOverlap = TRUE, + useCovariateConditionGroup = TRUE, + useCovariateDrugExposure = TRUE, + useCovariateDrugExposure365d = TRUE, + useCovariateDrugExposure30d = TRUE, + useCovariateDrugEra = TRUE, + useCovariateDrugEra365d = TRUE, + useCovariateDrugEra30d = TRUE, + useCovariateDrugEraEver = TRUE, + useCovariateDrugEraOverlap = TRUE, + useCovariateDrugGroup = TRUE, + useCovariateProcedureOccurrence = TRUE, + useCovariateProcedureOccurrence365d = TRUE, + useCovariateProcedureOccurrence30d = TRUE, + useCovariateProcedureGroup = TRUE, + useCovariateObservation = TRUE, + useCovariateObservation365d = TRUE, + useCovariateObservation30d = TRUE, + useCovariateObservationCount365d = TRUE, + useCovariateMeasurement365d = TRUE, + useCovariateMeasurement30d = TRUE, + useCovariateMeasurementCount365d = TRUE, + useCovariateMeasurementBelow = TRUE, + useCovariateMeasurementAbove = TRUE, + useCovariateConceptCounts = TRUE, + useCovariateRiskScores = TRUE, + useCovariateRiskScoresCharlson = TRUE, + useCovariateRiskScoresDCSI = TRUE, + useCovariateRiskScoresCHADS2 = TRUE, + useCovariateRiskScoresCHADS2VASc = TRUE, + useCovariateInteractionYear = FALSE, + useCovariateInteractionMonth = FALSE, + excludedCovariateConceptIds = c(), + deleteCovariatesSmallCount = 100) + + getDbCmDataArgs <- CohortMethod::createGetDbCohortMethodDataArgs(excludeDrugsFromCovariates = FALSE, + covariateSettings = covarSettings) + + createStudyPopArgs1 <- CohortMethod::createCreateStudyPopulationArgs(removeDuplicateSubjects = TRUE, + removeSubjectsWithPriorOutcome = TRUE, + riskWindowStart = 0, + riskWindowEnd = 0, + addExposureDaysToEnd = TRUE, + minDaysAtRisk = 1) + + createStudyPopArgs2 <- CohortMethod::createCreateStudyPopulationArgs(removeDuplicateSubjects = TRUE, + removeSubjectsWithPriorOutcome = TRUE, + riskWindowStart = 0, + riskWindowEnd = 99999, + addExposureDaysToEnd = FALSE, + minDaysAtRisk = 1) + + # Fixing seed for reproducability: + createPsArgs <- CohortMethod::createCreatePsArgs(control = Cyclops::createControl(noiseLevel = ""silent"", + cvType = ""auto"", + tolerance = 2e-07, + cvRepetitions = 10, + startingVariance = 0.01, + seed = 123)) + + matchOnPsArgs1 <- CohortMethod::createMatchOnPsArgs(maxRatio = 1) + + matchOnPsArgs2 <- CohortMethod::createMatchOnPsArgs(maxRatio = 100) + + fitOutcomeModelArgs1 <- CohortMethod::createFitOutcomeModelArgs(stratified = FALSE, + useCovariates = FALSE, + modelType = ""cox"") + + fitOutcomeModelArgs2 <- CohortMethod::createFitOutcomeModelArgs(stratified = TRUE, + useCovariates = FALSE, + modelType = ""cox"") + + # Fixing seed for reproducability + fitOutcomeModelArgs3 <- CohortMethod::createFitOutcomeModelArgs(stratified = TRUE, + useCovariates = TRUE, + modelType = ""cox"", + control = Cyclops::createControl(cvType = ""auto"", + startingVariance = 0.01, + tolerance = 2e-07, + cvRepetitions = 10, + selectorType = ""byPid"", + noiseLevel = ""quiet"", + seed = 123)) + + cmAnalysis1 <- CohortMethod::createCmAnalysis(analysisId = 1, + description = ""No matching, simple outcome model, per protocol"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = createStudyPopArgs1, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + cmAnalysis2 <- CohortMethod::createCmAnalysis(analysisId = 2, + description = ""1-on-1 matching plus simple conditioned outcome model, per protocol"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = createStudyPopArgs1, + createPs = TRUE, + createPsArgs = createPsArgs, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgs1, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs2) + + cmAnalysis3 <- CohortMethod::createCmAnalysis(analysisId = 3, + description = ""Variable ratio matching plus simple conditioned outcome model, per protocol"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = createStudyPopArgs1, + createPs = TRUE, + createPsArgs = createPsArgs, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgs2, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs2) + + cmAnalysis4 <- CohortMethod::createCmAnalysis(analysisId = 4, + description = ""Variable ratio matching plus full outcome model, per protocol"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = createStudyPopArgs1, + createPs = TRUE, + createPsArgs = createPsArgs, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgs2, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs3) + + cmAnalysis5 <- CohortMethod::createCmAnalysis(analysisId = 5, + description = ""No matching, simple outcome model, intent-to-treat"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = createStudyPopArgs2, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + cmAnalysis6 <- CohortMethod::createCmAnalysis(analysisId = 6, + description = ""1-on-1 matching plus simple conditioned outcome model, intent-to-treat"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = createStudyPopArgs2, + createPs = TRUE, + createPsArgs = createPsArgs, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgs1, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs2) + + cmAnalysis7 <- CohortMethod::createCmAnalysis(analysisId = 7, + description = ""Variable ratio matching plus simple conditioned outcome model, intent-to-treat"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = createStudyPopArgs2, + createPs = TRUE, + createPsArgs = createPsArgs, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgs2, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs2) + + cmAnalysis8 <- CohortMethod::createCmAnalysis(analysisId = 8, + description = ""Variable ratio matching plus full outcome model, intent-to-treat"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = createStudyPopArgs2, + createPs = TRUE, + createPsArgs = createPsArgs, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgs2, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs3) + + cmAnalysisList <- list(cmAnalysis1, + cmAnalysis2, + cmAnalysis3, + cmAnalysis4, + cmAnalysis5, + cmAnalysis6, + cmAnalysis7, + cmAnalysis8) + + CohortMethod::saveCmAnalysisList(cmAnalysisList, file.path(outputFolder, ""cmAnalysisList.txt"")) + CohortMethod::saveDrugComparatorOutcomesList(drugComparatorOutcomesList, + file.path(outputFolder, + ""drugComparatorOutcomesList.txt"")) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","KeppraAngioedema/R/KeppraAngioedema.R",".R","795","24","# Copyright 2016 Observational Health Data Sciences and Informatics +# +# This file is part of KeppraAngioedema +# +# 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. + +#' CohortMethod +#' +#' @docType package +#' @name KeppraAngioedema +#' @import DatabaseConnector +#' @importFrom OhdsiRTools makeCluster +NULL +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","KeppraAngioedema/R/WriteReport.R",".R","10218","150","# Copyright 2016 Observational Health Data Sciences and Informatics +# +# This file is part of KeppraAngioedema +# +# 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. + +#' Write a report summarizing all the results for a single database +#' +#' @details +#' Requires that the \code{\link{createTableAndFigures}} has been executed first. +#' +#' @param exportFolder The path to the export folder containing the results. +#' @param outputFile The name of the .docx file that will be created. +#' +#' @export +writeReport <- function(exportFolder, outputFile) { + rmarkdown::render(system.file(""markdown"", ""Report.rmd"", package = ""KeppraAngioedema""), + params = list(exportFolder = exportFolder), + output_file = outputFile, + rmarkdown::word_document(toc = TRUE, fig_caption = TRUE)) +} + +# Same report, using ReportRs package: +# writeReport <- function(exportFolder, dbName) { +# results <- read.csv(file.path(exportFolder, ""tablesAndFigures"", ""EmpiricalCalibration.csv"")) +# analysisIds <- unique(results$analysisId) +# analysisIds <- analysisIds[order(analysisIds)] +# hois <- 3 +# +# report <- ReporteRs::docx() +# +# ### Table of contents ### +# report <- ReporteRs::addTitle(report, ""Table of contents"", level = 1) +# report <- ReporteRs::addTOC(report) +# +# ### Intro ### +# report <- ReporteRs::addTitle(report, ""Introduction"", level = 1) +# text <- ""This reports describes the results from a comparative effectiveness study comparing new users of levetiracetam to new users of phenytoin. Propensity scores were generated using large scale regression, and one-on-one and variable ratio matching was performed. Effect sizes were estimated using a univariate Cox regression, conditioned on the matched sets. A set of negative control outcomes was included to estimate residual bias and calibrate p-values."" +# report <- ReporteRs::addParagraph(report, value = text) +# +# ## Analysis variations ## +# report <- ReporteRs::addTitle(report, ""Analyses variations"", level = 2) +# text <- paste(""In total,"", length(analysisIds), ""analysis variations were executed:"") +# for (analysisId in analysisIds) { +# text <- c(text, paste0(analysisId, "". "", results$analysisDescription[results$analysisId == analysisId][1])) +# } +# report <- ReporteRs::addParagraph(report, value = text) +# +# ### Model diagnostics ### +# report <- ReporteRs::addTitle(report, ""Model diagnostics"", level = 1) +# +# ## Propensity score distribution ## +# report <- ReporteRs::addTitle(report, ""Propensity score distribution"", level = 2) +# report <- ReporteRs::addImage(report, file.path(exportFolder, ""PsPrefScale.png""), width = 6.5, height = 5) +# text <- ""Propensity score distribution plot. This plot shows the propensity score distribution using the preference score scale."" +# report <- ReporteRs::addParagraph(report, value = text) +# +# ## Covariate balance ## +# report <- ReporteRs::addTitle(report, ""Covariate balance"", level = 2) +# +# # After one-on-one matching # +# report <- ReporteRs::addTitle(report, ""After one-on-one matching"", level = 3) +# report <- ReporteRs::addImage(report, file.path(exportFolder, ""tablesAndFigures"", ""BalanceScatterPlot1On1Matching.png""), width = 5, height = 5) +# text <- ""Balance scatter plot. This plot shows the standardized difference before and after matching for all covariates used in the propensity score model."" +# report <- ReporteRs::addParagraph(report, value = text) +# report <- ReporteRs::addImage(report, file.path(exportFolder, ""tablesAndFigures"", ""BalanceTopVariables1On1Matching.png""), width = 7, height = 5) +# text <- ""Balance plot for top covariates. This plot shows the standardized difference before and after matching for those covariates with the largest difference before matching (top) and after matching (bottom). A negative difference means the value in the treated group was lower than in the comparator group."" +# report <- ReporteRs::addParagraph(report, value = text) +# +# # After variable ratio matching # +# report <- ReporteRs::addTitle(report, ""After variable ratio matching"", level = 3) +# report <- ReporteRs::addImage(report, file.path(exportFolder, ""tablesAndFigures"", ""BalanceScatterPlotVarRatioMatching.png""), width = 5, height = 5) +# text <- ""Balance scatter plot. This plot shows the standardized difference before and after matching for all covariates used in the propensity score model."" +# report <- ReporteRs::addParagraph(report, value = text) +# report <- ReporteRs::addImage(report, file.path(exportFolder, ""tablesAndFigures"", ""BalanceTopVariablesVarRatioMatching.png""), width = 7, height = 5) +# text <- ""Balance plot for top covariates. This plot shows the standardized difference before and after matching for those covariates with the largest difference before matching (top) and after matching (bottom). A negative difference means the value in the treated group was lower than in the comparator group."" +# report <- ReporteRs::addParagraph(report, value = text) +# +# ## Empirical calibration ## +# report <- ReporteRs::addTitle(report, ""Empirical calibration"", level = 2) +# +# # Per analysis # +# for (analysisId in analysisIds) { +# title <- paste0(""Analysis "", analysisId, "": "", results$analysisDescription[results$analysisId == analysisId][1]) +# report <- ReporteRs::addTitle(report, title, level = 3) +# report <- ReporteRs::addImage(report, file.path(exportFolder, ""tablesAndFigures"", paste0(""CalEffectNoHoi_a"", analysisId, "".png"")), width = 5, height = 4) +# text <- ""Calibration effect plot. Blue dots represent the negative controls used in this study. The dashed line indicates the boundary below which p < 0.05 using traditional p-value computation. The orange area indicated the area where p < 0.05 using calibrated p-value computation."" +# report <- ReporteRs::addParagraph(report, value = text) +# report <- ReporteRs::addImage(report, file.path(exportFolder, ""tablesAndFigures"", paste0(""Cal_a"", analysisId, "".png"")), width = 4, height = 4) +# text <- ""Calibration plot. This plot shows the fraction of negative controls with p-values below alpha, for every level of alpha. Ideally, the plots should follow the diagonal. This plot has been generated using leave-one-out: when computing the calibrated p-value for a negative control, the bias distribution was fitted using all other negative controls."" +# report <- ReporteRs::addParagraph(report, value = text) +# } +# +# ### Main results ### +# report <- ReporteRs::addTitle(report, ""Main results"", level = 1) +# +# report <- ReporteRs::addTitle(report, ""Analyses variations"", level = 2) +# text <- paste(""In total,"", length(analysisIds), ""analysis variations were executed:"") +# for (analysisId in analysisIds) { +# text <- c(text, paste0(analysisId, "". "", results$analysisDescription[results$analysisId == analysisId][1])) +# } +# text <- c(text, """") +# report <- ReporteRs::addParagraph(report, value = text) +# +# table <- results[results$outcomeId %in% hois, c(""analysisId"", ""treated"", ""comparator"", ""eventsTreated"", ""eventsComparator"")] +# table <- table[order(table$analysisId), ] +# colnames(table) <- c(""Analysis ID"", ""# treated"", ""# comparator"", ""# treated with event"", ""# comparator with event"") +# report <- ReporteRs::addFlexTable(report, ReporteRs::FlexTable(table)) +# text <- ""Counts of subjects and events for the treated and comparator groups."" +# text <- c(text, """") +# report <- ReporteRs::addParagraph(report, value = text) +# +# table <- results[results$outcomeId %in% hois, c(""analysisId"", ""rr"", ""ci95lb"" , ""ci95ub"", ""p"", ""calibratedP"" ,""calibratedP_lb95ci"" ,""calibratedP_ub95ci"")] +# table <- table[order(table$analysisId), ] +# colnames(table) <- c(""Analysis ID"", ""Hazard Ratio"", ""95% CI LB"", ""95% CI UB"", ""P"", ""Calibrated P"", ""Cal. P 95% CI LB"", ""Cal. P 95% CI UB"") +# table <- sapply(table, function(x) {if (is.numeric(x)) round(x,2) else as.character(x)}) +# report <- ReporteRs::addFlexTable(report, ReporteRs::FlexTable(table)) +# text <- ""Harard ratios for angioedema in the levetiracetam group compared to the phenytoin group. Also included are traditional and calibrated p-values, as well as the 95% credible interval for the calibrated p-value."" +# report <- ReporteRs::addParagraph(report, value = text) +# +# ## Kaplan-Meier plots ## +# report <- ReporteRs::addTitle(report, ""Kaplan-Meier plots"", level = 2) +# +# # Per-protocol analysis # +# report <- ReporteRs::addTitle(report, ""Per-protocol analysis"", level = 3) +# report <- ReporteRs::addImage(report, file.path(exportFolder, ""KaplanMeierPerProtocol.png""), width = 5, height = 4) +# paragraph <- ""Kaplan-Meier plot. Shaded areas indicate the 95% confidence interval. Note that this plot does not take into account conditioning on the matched sets, as done when fitting the Cox model."" +# report <- ReporteRs::addParagraph(report, value = paragraph) +# +# # Intent-to-treat analysis # +# report <- ReporteRs::addTitle(report, ""Intent-to-treat analysis"", level = 3) +# report <- ReporteRs::addImage(report, file.path(exportFolder, ""KaplanMeierIntentToTreat.png""), width = 5, height = 4) +# paragraph <- ""Kaplan-Meier plot. Shaded areas indicate the 95% confidence interval. Note that this plot does not take into account conditioning on the matched sets, as done when fitting the Cox model."" +# report <- ReporteRs::addParagraph(report, value = paragraph) +# +# ReporteRs::writeDoc(report, file.path(exportFolder, ""Report.docx"")) +# } + + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","KeppraAngioedema/extras/PackageMaintenance.R",".R","3419","66","# Copyright 2016 Observational Health Data Sciences and Informatics +# +# This file is part of KeppraAngioedema +# +# 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. + +# Format and check code: +OhdsiRTools::formatRFolder() +OhdsiRTools::checkUsagePackage(""KeppraAngioedema"") +OhdsiRTools::updateCopyrightYearFolder() + +# Create manual and vignettes: +shell(""rm extras/KeppraAngioedema.pdf"") +shell(""R CMD Rd2pdf ./ --output=extras/KeppraAngioedema.pdf"") + +# Insert cohort definitions from Circe into package: +OhdsiRTools::insertCirceDefinitionInPackage(2189, ""Treatment"") +OhdsiRTools::insertCirceDefinitionInPackage(2191, ""Comparator"") +OhdsiRTools::insertCirceDefinitionInPackage(2193, ""Angioedema"") + +# Create analysis details +createAnalysesDetails(""inst/settings/"") + +# Get negative control names and exclusion concept IDs +dbms <- ""pdw"" +user <- NULL +pw <- NULL +server <- ""JRDUSAPSCTL01"" +port <- 17001 +connectionDetails <- DatabaseConnector::createConnectionDetails(dbms = dbms, + server = server, + user = user, + password = pw, + port = port) +sql <- ""SELECT concept_id, concept_name FROM cdm_truven_mdcd.dbo.concept WHERE concept_id IN (75344, 312437, 4324765, 318800, 197684, 437409, 434056, 261880, 380731, 433516, 437833, 319843, 195562, 195588, 432851, 378425, 433440, 43531027, 139099, 79903, 435459, 197320, 433163, 4002650, 197032, 141932, 372409, 137057, 80665, 200588, 316993, 80951, 134453, 133228, 133834, 80217, 442013, 313792, 75576, 314054, 195873, 198199, 134898, 140480, 200528, 193016, 321596, 29735, 138387, 4193869, 73842, 193326, 4205509, 78804, 141663, 376103, 4311499, 136773, 4291005, 440358, 134461, 192367, 261326, 74396, 78786, 374914, 260134, 196162, 253796, 133141, 136937, 192964, 194997, 440328, 258180, 441284, 440448, 80494, 199876, 376415, 317585, 441589, 140949, 432436, 256722, 378160, 373478, 436027, 443344, 192606, 434926, 439080, 29056, 199067, 77650, 440814, 198075, 79072, 317109, 378424) ORDER BY concept_id"" +connection <- DatabaseConnector::connect(connectionDetails) +ncNames <- querySql(connection, sql) +dbDisconnect(connection) + +writeLines(paste(ncNames$CONCEPT_ID, collapse = "", "")) +writeLines(paste0(""\"""", paste(ncNames$CONCEPT_NAME, collapse = ""\"", \""""), ""\"""")) + + +sql <- ""SELECT descendant_concept_id FROM cdm_truven_mdcd.dbo.concept_ancestor WHERE ancestor_concept_id IN (711584, 740910) ORDER BY descendant_concept_id"" +connection <- DatabaseConnector::connect(connectionDetails) +excludeIds <- querySql(connection, sql) +dbDisconnect(connection) + +writeLines(paste(excludeIds$DESCENDANT_CONCEPT_ID, collapse = "", "")) + +# Store environment in which the study was executed +OhdsiRTools::insertEnvironmentSnapshotInPackage(""KeppraAngioedema"") + + + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","KeppraAngioedema/extras/TestCodeImeds.R",".R","696","19","# Use a Linux 64/c1.xlarge instance + +library(KeppraAngioedema) + +connectionDetails <- createConnectionDetails( + dbms = ""redshift"", + user = Sys.getenv(""REDSHIFT_USER""), # Assumes environmental variables set before running R, + password = Sys.getenv(""REDSHIFT_PASSWORD""), # otherwise fill-in with correct user/password pair. + server = ""omop-datasets.cqlmv7nlakap.us-east-1.redshift.amazonaws.com/truven"", + port = ""5439"") + +execute(connectionDetails, + cdmDatabaseSchema = ""mdcr_v5"", + workDatabaseSchema = ""ohdsi"", + studyCohortTable = ""ohdsi_keppra_angioedema"", + oracleTempSchema = NULL, + outputFolder = ""~/study_results"", + maxCores = 8) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","KeppraAngioedema/extras/TestCode.R",".R","4756","135","library(KeppraAngioedema) +options(fftempdir = ""s:/FFtemp"") + +dbms <- ""pdw"" +user <- NULL +pw <- NULL +server <- ""JRDUSAPSCTL01"" +port <- 17001 +connectionDetails <- DatabaseConnector::createConnectionDetails(dbms = dbms, + server = server, + user = user, + password = pw, + port = port) +cdmDatabaseSchema <- ""CDM_Truven_MDCD_V446.dbo"" +workDatabaseSchema <- ""scratch.dbo"" +studyCohortTable <- ""ohdsi_keppra_angioedema"" +oracleTempSchema <- NULL +cdmVersion <- ""5"" +outputFolder <- ""S:/temp/KeppraAngioedemaMdcd"" + +cdmDatabaseSchema <- ""cdm_truven_ccae_v441.dbo"" +workDatabaseSchema <- ""scratch.dbo"" +studyCohortTable <- ""ohdsi_keppra_angioedema_ccae"" +oracleTempSchema <- NULL +cdmVersion <- ""5"" +outputFolder <- ""S:/temp/KeppraAngioedemaCcae"" + +cdmDatabaseSchema <- ""cdm_truven_mdcr_v445.dbo"" +workDatabaseSchema <- ""scratch.dbo"" +studyCohortTable <- ""ohdsi_keppra_angioedema_mdcr"" +oracleTempSchema <- NULL +cdmVersion <- ""5"" +outputFolder <- ""S:/temp/KeppraAngioedemaMdcr"" + +cdmDatabaseSchema <- ""cdm_optum_extended_ses_v458.dbo"" +workDatabaseSchema <- ""scratch.dbo"" +studyCohortTable <- ""ohdsi_keppra_angioedema_optum"" +oracleTempSchema <- NULL +cdmVersion <- ""5"" +outputFolder <- ""S:/temp/KeppraAngioedemaOptum"" + +# cdmDatabaseSchema <- ""cdm_cprd_v5.dbo"" +# workDatabaseSchema <- ""scratch.dbo"" +# studyCohortTable <- ""ohdsi_keppra_angioedema_cprd"" +# oracleTempSchema <- NULL +# cdmVersion <- ""5"" +# outputFolder <- ""S:/temp/KeppraAngioedemaCprd"" + +# dbms <- ""redshift"" +# user <- ""martijn"" +# pw <- Sys.getenv(""pwPharmetrics"") +# server <- ""ohdsi.cxmbbsphpllo.us-east-1.redshift.amazonaws.com/pplus"" +# cdmDatabaseSchema <- ""cdmv5"" +# workDatabaseSchema <- ""scratch"" +# oracleTempSchema <- NULL +# studyCohortTable <- ""ohdsi_test_cohorts"" +# outputFolder <- ""S:/temp/KeppraAngioedemaPplus"" +# port <- 5439 +# cdmVersion <- ""5"" + + +connectionDetails <- DatabaseConnector::createConnectionDetails(dbms = dbms, + server = server, + user = user, + password = pw, + port = port) + +execute(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + workDatabaseSchema = workDatabaseSchema, + studyCohortTable = studyCohortTable, + oracleTempSchema = oracleTempSchema, + cdmVersion = cdmVersion, + outputFolder = outputFolder, + createCohorts = FALSE, + runAnalyses = TRUE, + maxCores = 20) + +packageResults(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + outputFolder = outputFolder, + minCellCount = 5) + +createTableAndFigures(file.path(outputFolder, ""export"")) + +writeReport(file.path(outputFolder, ""export""), file.path(outputFolder, ""Report.docx"")) + +submitResults(file.path(outputFolder, ""export""), + key = Sys.getenv(""keyAngioedema""), + secret = Sys.getenv(""secretAngioedema"")) + +### Test on Oracle ### + +dbms <- ""oracle"" +user <- ""system"" +pw <- ""OHDSI"" +server <- ""xe"" +port <- NULL +connectionDetails <- DatabaseConnector::createConnectionDetails(dbms = dbms, + server = server, + user = user, + password = pw, + port = port) +cdmDatabaseSchema <- ""cdm_truven_ccae_6k_V5"" +workDatabaseSchema <- ""scratch"" +studyCohortTable <- ""ohdsi_keppra_angioedema"" +oracleTempSchema <- ""scratch"" +cdmVersion <- ""5"" +outputFolder <- ""S:/temp/KeppraAngioedemaOracle"" + +execute(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + workDatabaseSchema = workDatabaseSchema, + studyCohortTable = studyCohortTable, + oracleTempSchema = oracleTempSchema, + cdmVersion = cdmVersion, + outputFolder = outputFolder, + createCohorts = TRUE, + maxCores = 30) + +om <- readRDS(file.path(outputFolder, ""cmOutput"", ""Analysis_3"", ""om_t1_c2_o3.rds"")) +summary(om) + + +library(CohortMethod) +cmData <- loadCohortMethodData(file.path(outputFolder, ""cmOutput"", ""CmData_l1_t1_c2"")) +str(cmData$cohorts$treatment) +str(cmData$covariateRef$covariateName) +as.Date(cmData$cohorts$cohortStartDate) +ff::as.ff(cmData$cohorts$cohortStartDate) + +as.Date(c(""2001-13-13"")) + + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","KeppraAngioedema/extras/MetaAnalysis.R",".R","4001","84","plotForest <- function(logRr, logLb95Ci, logUb95Ci, names, xLabel = ""Relative risk"", fileName = NULL) { + # logRr <- results$logRr + # logLb95Ci <- log(results$ci95lb) + # logUb95Ci <- log(results$ci95ub) + # names <- results$db + seLogRr <- (logUb95Ci-logLb95Ci) / (2 * qnorm(0.975)) + meta <- meta::metagen(logRr, seLogRr, studlab = names, sm = ""RR"") + s <- summary(meta)$random + d1 <- data.frame(logRr = logRr, + logLb95Ci = logLb95Ci, + logUb95Ci = logUb95Ci, + name = names, + type = ""db"") + d2 <- data.frame(logRr = s$TE, + logLb95Ci = s$lower, + logUb95Ci = s$upper, + name = ""Summary"", + type = ""ma"") + d3 <- data.frame(logRr = NA, + logLb95Ci = NA, + logUb95Ci = NA, + name = ""Source"", + type = ""header"") + + d <- rbind(d1, d2, d3) + d$name <- factor(d$name, levels = c(""Summary"", rev(sort(as.character(names))), ""Source"")) + + breaks <- c(0.25, 0.5, 1, 2, 4, 6, 8, 10) + myText <- ggplot2::element_text(family = ""Calibri"") + p <- ggplot2::ggplot(d,ggplot2::aes(x = exp(logRr), y = name, xmin = exp(logLb95Ci), xmax = exp(logUb95Ci))) + + ggplot2::geom_vline(xintercept = breaks, colour = ""#AAAAAA"", lty = 1, size = 0.2) + + ggplot2::geom_vline(xintercept = 1, size = 0.5) + + ggplot2::geom_errorbarh(height = 0.15) + + ggplot2::geom_point(size=3, shape = 23, ggplot2::aes(fill=type)) + + ggplot2::scale_fill_manual(values = c(""#000000"", ""#FFFFFF"", ""#FFFFFF"")) + + ggplot2::scale_x_continuous(xLabel, trans = ""log10"", breaks = breaks, labels = breaks) + + ggplot2::coord_cartesian(xlim = c(0.25, 10)) + + ggplot2::theme( + axis.text.x = myText, + axis.title.x = myText, + panel.grid.major = ggplot2::element_blank(), + panel.grid.minor = ggplot2::element_blank(), + panel.background = ggplot2::element_blank(), + legend.position = ""none"", + panel.border = ggplot2::element_blank(), + axis.text.y = ggplot2::element_blank(), + axis.title.y = ggplot2::element_blank(), + axis.ticks = ggplot2::element_blank(), + plot.margin = grid::unit(c(0,0,0.1,0), ""lines"")) + + labels <- paste0(formatC(exp(d$logRr), digits = 2, format = ""f""), + "" ("", + formatC(exp(d$logLb95Ci), digits = 2, format = ""f""), + ""-"", + formatC(exp(d$logUb95Ci), digits = 2, format = ""f""), + "")"") + + labels <- data.frame(y = rep(d$name, 2), + x = rep(1:2, each = nrow(d)), + label = c(as.character(d$name), labels)) + + levels(labels$label)[1] <- paste(xLabel,""(95% CI)"") + + data_table <- ggplot2::ggplot(labels, ggplot2::aes(x = x, y = y, label = label)) + + ggplot2::geom_text(size = 4, hjust=0, vjust=0.5, family = ""Calibri"") + + ggplot2::geom_hline(ggplot2::aes(yintercept=nrow(d) - 0.5)) + + ggplot2::theme(panel.grid.major = ggplot2::element_blank(), + panel.grid.minor = ggplot2::element_blank(), + legend.position = ""none"", + panel.border = ggplot2::element_blank(), + panel.background = ggplot2::element_blank(), + axis.text.x = ggplot2::element_text(colour=""white""),#element_blank(), + axis.text.y = ggplot2::element_blank(), + axis.ticks = ggplot2::element_line(colour=""white""),#element_blank(), + plot.margin = grid::unit(c(0,0,0.1,0), ""lines"")) + + ggplot2::labs(x="""",y="""") + + ggplot2::coord_cartesian(xlim=c(1,3)) + + plot <- gridExtra::grid.arrange(data_table, p, ncol=2) + + if (!is.null(fileName)) + ggplot2::ggsave(fileName, plot, width = 7, height = 1 + length(logRr) * 0.4, dpi = 400) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","KeppraAngioedema/extras/CentralizedProcessing.R",".R","4118","107","library(KeppraAngioedema) + +# Create per-database reports: +studyFolder <- ""S:/Angioedema"" +folders <- c(""Truven_CCAE"", ""Truven_MDCD"", ""Truven_MDCR"", ""Optum"") +folders <- ""Ims_Amb_Emr"" +folders <- ""Pplus_Ims"" +folders <- ""Ims_Da_French_Emr"" +#for (file in list.files(path = studyFolder, include.dirs = TRUE)) { +for (file in folders) { + if (file.info(file.path(studyFolder, file))$isdir) { + writeLines(paste(""Processing"", file)) + createTableAndFigures(file.path(studyFolder, file)) + writeReport(file.path(studyFolder, file), file.path(studyFolder, paste0(""Report_"", file, "".docx""))) + } +} + +# Create summary csv file: +allResults <- data.frame() +skip <- c(""IMEDS_MDCR"", ""Regenstrief"", ""Pplus"") +for (file in list.files(path = studyFolder, include.dirs = TRUE)) { + if (!(file %in% skip)) { + if (file.info(file.path(studyFolder, file))$isdir) { + writeLines(paste(""Processing"", file)) + results <- read.csv(file.path(studyFolder, file, ""tablesAndFigures"", ""EmpiricalCalibration.csv"")) + results <- results[results$outcomeId == 3, ] + results$db <- file + results <- results[,c(ncol(results), 1:(ncol(results)-1))] + allResults <- rbind(allResults, results) + } + } +} +write.csv(allResults, file.path(studyFolder, ""AllResults.csv""), row.names = FALSE) + + + +# Meta analysis ----------------------------------------------------------- +allResults <- read.csv(file.path(studyFolder, ""AllResults.csv""), stringsAsFactors = FALSE) +allResults$db[allResults$db == ""Ims_Amb_Emr""] <- ""IMS Ambulatory"" +allResults$db[allResults$db == ""Optum""] <- ""Optum"" +allResults$db[allResults$db == ""Pplus_Ims""] <- ""IMS P-Plus"" +allResults$db[allResults$db == ""Truven_CCAE""] <- ""Truven CCAE"" +allResults$db[allResults$db == ""Truven_MDCD""] <- ""Truven MDCD"" +allResults$db[allResults$db == ""Truven_MDCR""] <- ""Truven MDCR"" +allResults$db[allResults$db == ""UT_Cerner""] <- ""UT EMR"" +source(""extras/MetaAnalysis.R"") + +fileName <- file.path(studyFolder, ""ForestPp.png"") +results <- allResults[allResults$analysisId == 3, ] +results <- results[!is.na(results$seLogRr), ] +plotForest(logRr = results$logRr, + logLb95Ci = log(results$ci95lb), + logUb95Ci = log(results$ci95ub), + names = results$db, + xLabel = ""Hazard Ratio"", + fileName = fileName) + +fileName <- file.path(studyFolder, ""ForestItt.png"") +results <- allResults[allResults$analysisId == 7, ] +results <- results[!is.na(results$seLogRr), ] +plotForest(logRr = results$logRr, + logLb95Ci = log(results$ci95lb), + logUb95Ci = log(results$ci95ub), + names = results$db, + xLabel = ""Hazard Ratio"", + fileName = fileName) + +meta <- metagen(results$logRr, results$seLogRr, studlab = results$db, sm = ""RR"") +s <- summary(meta)$random +exp(s$TE) + +forest(meta) + +results <- allResults[allResults$analysisId == 7, ] +results <- results[!is.na(results$seLogRr), ] +meta <- metagen(results$logRr, results$seLogRr, studlab = results$db, sm = ""RR"") +forest(meta) + + +# exportFolder <- ""S:/Angioedema/Regenstrief"" +# mr <- read.csv(file.path(exportFolder, ""MainResults.csv"")) +# mr <- KeppraAngioedema:::addAnalysisDescriptions(mr) +mr <- KeppraAngioedema:::addCohortNames(mr, ""outcomeId"", ""outcomeName"") +# mr <- KeppraAngioedema:::addCohortNames(mr, ""targetId"", ""targetName"") +# mr <- KeppraAngioedema:::addCohortNames(mr, ""comparatorId"", ""comparatorName"") +# write.csv(mr, file.path(exportFolder, ""MainResults.csv""), row.names = FALSE) + + + +# Grab all PS model files ------------------------------------------------- + +allModels <- data.frame() +skip <- c(""IMEDS_MDCR"", ""Regenstrief"", ""Pplus"") +for (file in list.files(path = studyFolder, include.dirs = TRUE)) { + if (!(file %in% skip)) { + if (file.info(file.path(studyFolder, file))$isdir) { + writeLines(paste(""Processing"", file)) + model <- read.csv(file.path(studyFolder, file, ""PsModel.csv"")) + model$db <- file + allModels <- rbind(allModels, model) + } + } +} +write.csv(allModels, file.path(studyFolder, ""AllPSModels.csv""), row.names = FALSE) + + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","LargeScalePopEst/R/CustomCmDataObjectBuilding.R",".R","18446","281","# Copyright 2017 Observational Health Data Sciences and Informatics +# +# This file is part of LargeScalePopEst +# +# 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. + +#' Fetch all data on the cohorts for analysis +#' +#' @details +#' This function will create covariates and fetch outcomes and person information from the server. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param workDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param studyCohortTable The name of the study cohort table in the work database schema. +#' @param exposureCohortSummaryTable The name of the exposure summary table in the work database schema. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param workFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' +#' @export +fetchAllDataFromServer <- function(connectionDetails, + cdmDatabaseSchema, + workDatabaseSchema, + studyCohortTable = ""ohdsi_cohorts"", + oracleTempSchema, + workFolder) { + exposureSummary <- read.csv(file.path(workFolder, ""exposureSummaryFilteredBySize.csv"")) + exposureIdToConceptId <- rbind(data.frame(exposureId = exposureSummary$tprimeCohortDefinitionId, + conceptId = exposureSummary$tCohortDefinitionId), + data.frame(exposureId = exposureSummary$cprimeCohortDefinitionId, + conceptId = exposureSummary$cCohortDefinitionId)) + exposureIds <- exposureIdToConceptId$exposureId + exposureConceptIds <- unique(exposureIdToConceptId$conceptId) + + cohortNames <- read.csv(file.path(workFolder, ""cohortNames.csv"")) + outcomeIds <- cohortNames$cohortDefinitionId[cohortNames$type == ""outcome"" | cohortNames$type == ""negativeControl""] + + conn <- DatabaseConnector::connect(connectionDetails) + + # Lump persons of interest into one table: + sql <- SqlRender::loadRenderTranslateSql(""UnionExposureCohorts.sql"", + ""LargeScalePopEst"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable, + exposure_ids = exposureIds) + DatabaseConnector::executeSql(conn, sql, progressBar = FALSE, reportOverallTime = FALSE) + # Note: removing concept counts because number of drugs is very predictive of drugs vs procedures + covariateSettings <- FeatureExtraction::createCovariateSettings(useCovariateDemographics = TRUE, + useCovariateDemographicsGender = TRUE, + useCovariateDemographicsRace = TRUE, + useCovariateDemographicsEthnicity = TRUE, + useCovariateDemographicsAge = TRUE, + useCovariateDemographicsYear = TRUE, + useCovariateDemographicsMonth = TRUE, + useCovariateConditionOccurrence = TRUE, + useCovariateConditionOccurrence365d = TRUE, + useCovariateConditionOccurrence30d = TRUE, + useCovariateConditionOccurrenceInpt180d = TRUE, + useCovariateConditionGroup = TRUE, + useCovariateConditionGroupMeddra = TRUE, + useCovariateConditionGroupSnomed = TRUE, + useCovariateDrugEra = TRUE, + useCovariateDrugEra365d = TRUE, + useCovariateDrugEra30d = TRUE, + useCovariateDrugEraOverlap = TRUE, + useCovariateDrugGroup = TRUE, + useCovariateProcedureOccurrence = TRUE, + useCovariateProcedureOccurrence365d = TRUE, + useCovariateProcedureOccurrence30d = TRUE, + useCovariateProcedureGroup = TRUE, + useCovariateObservation = TRUE, + useCovariateObservation365d = TRUE, + useCovariateObservation30d = TRUE, + useCovariateObservationCount365d = TRUE, + useCovariateMeasurement = TRUE, + useCovariateMeasurement365d = TRUE, + useCovariateMeasurement30d = TRUE, + useCovariateMeasurementCount365d = TRUE, + useCovariateMeasurementBelow = TRUE, + useCovariateMeasurementAbove = TRUE, + useCovariateConceptCounts = FALSE, + useCovariateRiskScores = TRUE, + useCovariateRiskScoresCharlson = TRUE, + useCovariateRiskScoresDCSI = TRUE, + useCovariateRiskScoresCHADS2 = TRUE, + useCovariateRiskScoresCHADS2VASc = TRUE, + excludedCovariateConceptIds = 900000010, + deleteCovariatesSmallCount = 100) + covariates <- FeatureExtraction::getDbCovariateData(connection = conn, + oracleTempSchema = oracleTempSchema, + cdmDatabaseSchema = cdmDatabaseSchema, + cdmVersion = 5, + cohortTable = ""#exposure_cohorts"", + cohortTableIsTemp = TRUE, + rowIdField = ""row_id"", + covariateSettings = covariateSettings, + normalize = TRUE) + FeatureExtraction::saveCovariateData(covariates, file.path(workFolder, ""allCovariates"")) + + writeLines(""Retrieving cohorts"") + sql <- SqlRender::loadRenderTranslateSql(""GetExposureCohorts.sql"", + ""LargeScalePopEst"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable) + cohorts <- DatabaseConnector::querySql.ffdf(conn, sql) + colnames(cohorts) <- SqlRender::snakeCaseToCamelCase(colnames(cohorts)) + ffbase::save.ffdf(cohorts, dir = file.path(workFolder, ""allCohorts"")) + ff::close.ffdf(cohorts) + + writeLines(""Retrieving outcomes"") + sql <- SqlRender::loadRenderTranslateSql(""GetOutcomes.sql"", + ""LargeScalePopEst"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + outcome_database_schema = workDatabaseSchema, + outcome_table = studyCohortTable, + outcome_ids = outcomeIds) + outcomes <- DatabaseConnector::querySql.ffdf(conn, sql) + colnames(outcomes) <- SqlRender::snakeCaseToCamelCase(colnames(outcomes)) + ffbase::save.ffdf(outcomes, dir = file.path(workFolder, ""allOutcomes"")) + ff::close.ffdf(outcomes) + + writeLines(""Retrieving filter concepts"") + sql <- SqlRender::loadRenderTranslateSql(""GetFilterConcepts.sql"", + ""LargeScalePopEst"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + exposure_concept_ids = exposureConceptIds) + filterConcepts <- DatabaseConnector::querySql(conn, sql) + colnames(filterConcepts) <- SqlRender::snakeCaseToCamelCase(colnames(filterConcepts)) + filterConcepts <- merge(filterConcepts, exposureIdToConceptId, by.x = ""exposureConceptId"", by.y = ""conceptId"") + filterConcepts$exposureConceptId <- NULL + saveRDS(filterConcepts, file.path(workFolder, ""filterConceps.rds"")) + + DBI::dbDisconnect(conn) +} + +constructCohortMethodDataObject <- function(targetId, + comparatorId, + targetConceptId, + comparatorConceptId, + workFolder) { + # Subsetting cohorts + ffbase::load.ffdf(dir = file.path(workFolder, ""allCohorts"")) + ff::open.ffdf(cohorts, readonly = TRUE) + idx <- cohorts$cohortDefinitionId == targetId | cohorts$cohortDefinitionId == comparatorId + cohorts <- ff::as.ram(cohorts[ffbase::ffwhich(idx, idx == TRUE), ]) + cohorts$treatment <- 0 + cohorts$treatment[cohorts$cohortDefinitionId == targetId] <- 1 + cohorts$cohortDefinitionId <- NULL + treatedPersons <- length(unique(cohorts$subjectId[cohorts$treatment == 1])) + comparatorPersons <- length(unique(cohorts$subjectId[cohorts$treatment == 0])) + treatedExposures <- length(cohorts$subjectId[cohorts$treatment == 1]) + comparatorExposures <- length(cohorts$subjectId[cohorts$treatment == 0]) + counts <- data.frame(description = ""Starting cohorts"", + treatedPersons = treatedPersons, + comparatorPersons = comparatorPersons, + treatedExposures = treatedExposures, + comparatorExposures = comparatorExposures) + metaData <- list(targetId = targetId, + comparatorId = comparatorId, + attrition = counts) + attr(cohorts, ""metaData"") <- metaData + + # Subsetting outcomes + ffbase::load.ffdf(dir = file.path(workFolder, ""allOutcomes"")) + ff::open.ffdf(outcomes, readonly = TRUE) + idx <- !is.na(ffbase::ffmatch(outcomes$rowId, ff::as.ff(cohorts$rowId))) + if (ffbase::any.ff(idx)){ + outcomes <- ff::as.ram(outcomes[ffbase::ffwhich(idx, idx == TRUE), ]) + } else { + outcomes <- as.data.frame(outcomes[1, ]) + outcomes <- outcomes[T == F,] + } + # Add injected outcomes + ffbase::load.ffdf(dir = file.path(workFolder, ""injectedOutcomes"")) + ff::open.ffdf(injectedOutcomes, readonly = TRUE) + injectionSummary <- read.csv(file.path(workFolder, ""signalInjectionSummary.csv"")) + injectionSummary <- injectionSummary[injectionSummary$exposureId %in% c(targetConceptId, comparatorConceptId), ] + idx1 <- ffbase::'%in%'(injectedOutcomes$subjectId, cohorts$subjectId) + idx2 <- ffbase::'%in%'(injectedOutcomes$cohortDefinitionId, injectionSummary$newOutcomeId) + idx <- idx1 & idx2 + if (ffbase::any.ff(idx)){ + injectedOutcomes <- ff::as.ram(injectedOutcomes[idx, ]) + colnames(injectedOutcomes)[colnames(injectedOutcomes) == ""cohortStartDate""] <- ""eventDate"" + colnames(injectedOutcomes)[colnames(injectedOutcomes) == ""cohortDefinitionId""] <- ""outcomeId"" + injectedOutcomes <- merge(cohorts[, c(""rowId"", ""subjectId"", ""cohortStartDate"")], injectedOutcomes[, c(""subjectId"", ""outcomeId"", ""eventDate"")]) + injectedOutcomes$daysToEvent = injectedOutcomes$eventDate - injectedOutcomes$cohortStartDate + #any(injectedOutcomes$daysToEvent < 0) + #min(outcomes$daysToEvent[outcomes$outcomeId == 73008]) + outcomes <- rbind(outcomes, injectedOutcomes[, c(""rowId"", ""outcomeId"", ""daysToEvent"")]) + } + metaData <- data.frame(outcomeIds = unique(outcomes$outcomeId)) + attr(outcomes, ""metaData"") <- metaData + + # Subsetting covariates + covariateData <- FeatureExtraction::loadCovariateData(file.path(workFolder, ""allCovariates"")) + idx <- is.na(ffbase::ffmatch(covariateData$covariates$rowId, ff::as.ff(cohorts$rowId))) + covariates <- covariateData$covariates[ffbase::ffwhich(idx, idx == FALSE), ] + + # Filtering covariates + filterConcepts <- readRDS(file.path(workFolder, ""filterConceps.rds"")) + filterConcepts <- filterConcepts[filterConcepts$exposureId %in% c(targetId, comparatorId),] + filterConceptIds <- unique(filterConcepts$filterConceptId) + idx <- is.na(ffbase::ffmatch(covariateData$covariateRef$conceptId, ff::as.ff(filterConceptIds))) + covariateRef <- covariateData$covariateRef[ffbase::ffwhich(idx, idx == TRUE), ] + filterCovariateIds <- covariateData$covariateRef$covariateId[ffbase::ffwhich(idx, idx == FALSE), ] + idx <- is.na(ffbase::ffmatch(covariates$covariateId, filterCovariateIds)) + covariates <- covariates[ffbase::ffwhich(idx, idx == TRUE), ] + + result <- list(cohorts = cohorts, + outcomes = outcomes, + covariates = covariates, + covariateRef = covariateRef, + metaData = covariateData$metaData) + + class(result) <- ""cohortMethodData"" + return(result) +} + +#' Construct all cohortMethodData object +#' +#' @details +#' This function constructs all cohortMethodData objects using the data +#' fetched earlier using the \code{\link{fetchAllDataFromServer}} function. +#' +#' @param workFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' +#' @export +generateAllCohortMethodDataObjects <- function(workFolder) { + writeLines(""Constructing cohortMethodData objects"") + start <- Sys.time() + exposureSummary <- read.csv(file.path(workFolder, ""exposureSummaryFilteredBySize.csv"")) + pb <- txtProgressBar(style = 3) + for (i in 1:nrow(exposureSummary)) { + targetId <- exposureSummary$tprimeCohortDefinitionId[i] + comparatorId <- exposureSummary$cprimeCohortDefinitionId[i] + targetConceptId <- exposureSummary$tCohortDefinitionId[i] + comparatorConceptId <- exposureSummary$cCohortDefinitionId[i] + folderName <- file.path(workFolder, ""cmOutput"", paste0(""CmData_l1_t"", targetId, ""_c"", comparatorId)) + if (!file.exists(folderName)) { + cmData <- constructCohortMethodDataObject(targetId = targetId, + comparatorId = comparatorId, + targetConceptId = targetConceptId, + comparatorConceptId = comparatorConceptId, + workFolder = workFolder) + CohortMethod::saveCohortMethodData(cmData, folderName) + } + setTxtProgressBar(pb, i/nrow(exposureSummary)) + } + close(pb) + delta <- Sys.time() - start + writeLines(paste(""Generating all CohortMethodData objects took"", signif(delta, 3), attr(delta, ""units""))) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","LargeScalePopEst/R/Main.R",".R","5416","99","# Copyright 2017 Observational Health Data Sciences and Informatics +# +# This file is part of LargeScalePopEst +# +# 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. + +#' Execute OHDSI Large-Scale Population-Level Evidence Generation study +#' +#' @details +#' This function executes the OHDSI Large-Scale Population-Level Evidence Generation study. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param workDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param studyCohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param exposureCohortSummaryTable The name of the table that will be created in the work database schema. +#' This table will hold summary data on the exposure cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param workFolder Name of local folder to place results; make sure to use forward slashes +#' (/). Do not use a folder on a network drive since this greatly impacts +#' performance. +#' @param createCohorts Create the studyCohortTable and exposureCohortSummaryTable tables with the exposure and outcome cohorts? +#' @param fetchAllDataFromServer Fetch all relevant data from the server? +#' @param injectSignals Inject signals to create synthetic controls? +#' @param generateAllCohortMethodDataObjects Create the cohortMethodData objects from the fetched data and injected signals? +#' @param runCohortMethod Run the CohortMethod package to produce the outcome models. +#' @param maxCores How many parallel cores should be used? If more cores are made available +#' this can speed up the analyses. +#' +#' @export +execute <- function(connectionDetails, + cdmDatabaseSchema, + oracleTempSchema, + workDatabaseSchema, + studyCohortTable, + exposureCohortSummaryTable, + workFolder, + maxCores, + createCohorts = TRUE, + fetchAllDataFromServer = TRUE, + injectSignals = TRUE, + generateAllCohortMethodDataObjects = TRUE, + runCohortMethod = TRUE) { + if (createCohorts) { + createCohorts(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + workDatabaseSchema = workDatabaseSchema, + studyCohortTable = studyCohortTable, + exposureCohortSummaryTable = exposureCohortSummaryTable, + workFolder = workFolder) + + filterByExposureCohortsSize(workFolder = workFolder) + } + if (fetchAllDataFromServer) { + fetchAllDataFromServer(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + workDatabaseSchema = workDatabaseSchema, + studyCohortTable = studyCohortTable, + workFolder = workFolder) + } + if (injectSignals) { + injectSignals(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + workDatabaseSchema = workDatabaseSchema, + studyCohortTable = studyCohortTable, + oracleTempSchema = oracleTempSchema, + workFolder = workFolder, + maxCores = maxCores) + } + if (generateAllCohortMethodDataObjects) { + generateAllCohortMethodDataObjects(workFolder) + } + if (runCohortMethod) { + runCohortMethod(workFolder, maxCores = maxCores) + } +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","LargeScalePopEst/R/FiguresAndTables.R",".R","12789","218","# Copyright 2017 Observational Health Data Sciences and Informatics +# +# This file is part of LargeScalePopEst +# +# 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. + +#' Analyse propensity score distributions +#' +#' @details +#' This function plots all propensity score distributions, and computes AUC +#' and equipoise for every exposure pair. +#' +#' @param workFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' +#' @export +analysePsDistributions <- function(workFolder) { + writeLines(""Plotting propensity score distributions"") + figuresAndTablesFolder <- file.path(workFolder, ""figuresAndtables"") + if (!file.exists(figuresAndTablesFolder)) { + dir.create(figuresAndTablesFolder) + } + psResultsFolder <- file.path(figuresAndTablesFolder, ""ps"") + if (!file.exists(psResultsFolder)) { + dir.create(psResultsFolder) + } + + exposureSummary <- read.csv(file.path(workFolder, ""exposureSummaryFilteredBySize.csv"")) + #exposureSummary <- exposureSummary[exposureSummary$tCohortDefinitionName == ""duloxetine"" & exposureSummary$cCohortDefinitionName == ""Sertraline"",] + outcomeModelReference <- readRDS(file.path(workFolder, ""cmOutput"", ""outcomeModelReference.rds"")) + matrix1 <- data.frame(cohortId1 = exposureSummary$tprimeCohortDefinitionId, + cohortName1 = exposureSummary$tCohortDefinitionName, + cohortId2 = exposureSummary$cprimeCohortDefinitionId, + cohortName2 = exposureSummary$cCohortDefinitionName, + equipoise = 0, + auc = 1) + matrix2 <- data.frame(cohortId1 = exposureSummary$cprimeCohortDefinitionId, + cohortName1 = exposureSummary$cCohortDefinitionName, + cohortId2 = exposureSummary$tprimeCohortDefinitionId, + cohortName2 = exposureSummary$tCohortDefinitionName, + equipoise = 0, + auc = 1) + matrix <- rbind(matrix1, matrix2) + for (i in 1:nrow(exposureSummary)) { + treatmentId <- exposureSummary$tprimeCohortDefinitionId[i] + comparatorId <- exposureSummary$cprimeCohortDefinitionId[i] + psFileName <- outcomeModelReference$sharedPsFile[outcomeModelReference$targetId == treatmentId & outcomeModelReference$comparatorId == comparatorId & outcomeModelReference$analysisId == 3][1] + ### REMOVE THIS ### + psFileName <- gsub(""^s:"", ""R:"", psFileName) + if (file.exists(psFileName)){ + ps <- readRDS(psFileName) + + plotFileName <- file.path(psResultsFolder, paste0(""ps_t"", treatmentId, ""_c"", comparatorId, "".png"")) + CohortMethod::plotPs(ps, + treatmentLabel = as.character(exposureSummary$tCohortDefinitionName[i]), + comparatorLabel = as.character(exposureSummary$cCohortDefinitionName[i]), + fileName = plotFileName) + + ps$treatment <- 1 - ps$treatment + ps$propensityScore <- 1 - ps$propensityScore + plotFileName <- file.path(psResultsFolder, paste0(""ps_t"", comparatorId, ""_c"", treatmentId, "".png"")) + CohortMethod::plotPs(ps, + treatmentLabel = as.character(exposureSummary$cCohortDefinitionName[i]), + comparatorLabel = as.character(exposureSummary$tCohortDefinitionName[i]), + fileName = plotFileName) + idx <- (matrix$cohortId1 == treatmentId & matrix$cohortId2 == comparatorId) | + (matrix$cohortId2 == treatmentId & matrix$cohortId1 == comparatorId) + matrix$auc[idx] <- CohortMethod::computePsAuc(ps, confidenceIntervals = FALSE) + prefScore <- computePreferenceScore(ps) + matrix$equipoise[idx] <- mean(prefScore$preferenceScore >= 0.3 & prefScore$preferenceScore < 0.7) + } + } + psSummaryFileName <- file.path(psResultsFolder, ""psSummary.csv"") + write.csv(matrix, psSummaryFileName, row.names = FALSE) +} + +computePreferenceScore <- function(data) { + proportion <- sum(data$treatment)/nrow(data) + propensityScore <- data$propensityScore + propensityScore[propensityScore > 0.9999999] <- 0.9999999 + x <- exp(log(propensityScore/(1 - propensityScore)) - log(proportion/(1 - proportion))) + data$preferenceScore <- x/(x + 1) + return(data) +} + +#' @export +plotControlDistributions <- function(workFolder) { + writeLines(""Plotting control distributions"") + figuresAndTablesFolder <- file.path(workFolder, ""figuresAndtables"") + if (!file.exists(figuresAndTablesFolder)) { + dir.create(figuresAndTablesFolder) + } + controlsFolder <- file.path(figuresAndTablesFolder, ""controls"") + if (!file.exists(controlsFolder)) { + dir.create(controlsFolder) + } + + exposureSummary <- read.csv(file.path(workFolder, ""exposureSummaryFilteredBySize.csv"")) + #exposureSummary <- exposureSummary[exposureSummary$tCohortDefinitionName == ""duloxetine"" & exposureSummary$cCohortDefinitionName == ""Sertraline"",] + analysesSum <- read.csv(file.path(workFolder, ""analysisSummary.csv"")) + signalInjectionSum <- read.csv(file.path(workFolder, ""signalInjectionSummary.csv"")) + negativeControlIds <- unique(signalInjectionSum$outcomeId) + for (i in 1:nrow(exposureSummary)) { + treatmentId <- exposureSummary$tprimeCohortDefinitionId[i] + comparatorId <- exposureSummary$cprimeCohortDefinitionId[i] + treatmentConceptId <- exposureSummary$tCohortDefinitionId[i] + comparatorConceptId <- exposureSummary$cCohortDefinitionId[i] + treatmentName <- exposureSummary$tCohortDefinitionName[i] + comparatorName <- exposureSummary$cCohortDefinitionName[i] + for (analysisId in c(1,3)){ + estimates <- analysesSum[analysesSum$analysisId == analysisId & + analysesSum$targetId == treatmentId & + analysesSum$comparatorId == comparatorId, ] + + negControls <- estimates[estimates$outcomeId %in% negativeControlIds, ] + fileName <- file.path(controlsFolder, paste0(""negControls_a"", analysisId, ""_t"", treatmentId, ""_c"", comparatorId, "".png"")) + analysisLabel <- ""Crude"" + if (analysisId != 1) { + analysisLabel <- ""Adjusted"" + } + title <- paste(treatmentName, ""vs."", comparatorName, ""-"", analysisLabel) + plotEstimates(logRrNegatives = negControls$logRr, + seLogRrNegatives = negControls$seLogRr, + title = title, + xLabel = ""Hazard ratio"", + fileName = fileName) + fileName <- file.path(controlsFolder, paste0(""negControls_a"", analysisId, ""_t"", comparatorId, ""_c"", treatmentId, "".png"")) + title <- paste(comparatorName, ""vs."", treatmentName, ""-"", analysisLabel) + plotEstimates(logRrNegatives = -negControls$logRr, + seLogRrNegatives = negControls$seLogRr, + title = title, + xLabel = ""Hazard ratio"", + fileName = fileName) + + injectedSignals <- signalInjectionSum[signalInjectionSum$exposureId == treatmentConceptId & signalInjectionSum$injectedOutcomes != 0, ] + negativeControlIdSubsets <- unique(injectedSignals$outcomeId) + injectedSignals <- data.frame(outcomeId = injectedSignals$newOutcomeId, + trueLogRr = log(injectedSignals$targetEffectSize)) + negativeControls <- data.frame(outcomeId = negativeControlIdSubsets, + trueLogRr = 0) + data <- rbind(injectedSignals, negativeControls) + data <- merge(data, estimates[, c(""outcomeId"", ""logRr"", ""seLogRr"")]) + fileName <- file.path(controlsFolder, paste0(""trueAndObs_a"", analysisId, ""_t"", treatmentId, ""_c"", comparatorId, "".png"")) + analysisLabel <- ""Crude"" + if (analysisId != 1) { + analysisLabel <- ""Adjusted"" + } + title <- paste(treatmentName, ""vs."", comparatorName, ""-"", analysisLabel) + EmpiricalCalibration::plotTrueAndObserved(logRr = data$logRr, + seLogRr = data$seLogRr, + trueLogRr = data$trueLogRr, + xLabel = ""Hazard ratio"", + title = title, + fileName = fileName) + injectedSignals <- signalInjectionSum[signalInjectionSum$exposureId == comparatorConceptId & signalInjectionSum$injectedOutcomes != 0, ] + negativeControlIdSubsets <- unique(injectedSignals$outcomeId) + injectedSignals <- data.frame(outcomeId = injectedSignals$newOutcomeId, + trueLogRr = log(injectedSignals$targetEffectSize)) + negativeControls <- data.frame(outcomeId = negativeControlIdSubsets, + trueLogRr = 0) + data <- rbind(injectedSignals, negativeControls) + data <- merge(data, estimates[, c(""outcomeId"", ""logRr"", ""seLogRr"")]) + fileName <- file.path(controlsFolder, paste0(""trueAndObs_a"", analysisId, ""_t"", comparatorId, ""_c"", treatmentId, "".png"")) + title <- paste(comparatorName, ""vs."", treatmentName, ""-"", analysisLabel) + EmpiricalCalibration::plotTrueAndObserved(logRr = -data$logRr, + seLogRr = data$seLogRr, + trueLogRr = data$trueLogRr, + xLabel = ""Hazard ratio"", + title = title, + fileName = fileName) + } + } +} + +plotEstimates <- function (logRrNegatives, seLogRrNegatives, xLabel = ""Relative risk"", title, fileName = NULL) { + + x <- exp(seq(log(0.25), log(10), by = 0.01)) + seTheoretical <- sapply(x, FUN = function(x) { + abs(log(x))/qnorm(0.975) + }) + breaks <- c(0.25, 0.5, 1, 2, 4, 6, 8, 10) + theme <- ggplot2::element_text(colour = ""#000000"", size = 12) + themeRA <- ggplot2::element_text(colour = ""#000000"", size = 12, + hjust = 1) + plot <- ggplot2::ggplot(data.frame(x, seTheoretical), ggplot2::aes(x = x, y = seTheoretical), environment = environment()) + + ggplot2::geom_vline(xintercept = breaks, colour = ""#AAAAAA"", lty = 1, size = 0.5) + + ggplot2::geom_vline(xintercept = 1, size = 1) + + ggplot2::geom_area(fill = rgb(0, 0, 0), colour = rgb(0, 0, 0, alpha = 0.1), alpha = 0.1) + + ggplot2::geom_line(colour = rgb(0, 0, 0), linetype = ""dashed"", size = 1, alpha = 0.5) + + ggplot2::geom_point(shape = 21, ggplot2::aes(x, y), data = data.frame(x = exp(logRrNegatives), y = seLogRrNegatives), size = 2, fill = rgb(0, 0, 1, alpha = 0.5), colour = rgb(0, 0, 0.8)) + + ggplot2::geom_hline(yintercept = 0) + + ggplot2::scale_x_continuous(xLabel, trans = ""log10"", limits = c(0.25, 10), breaks = breaks, labels = breaks) + + ggplot2::scale_y_continuous(""Standard Error"", limits = c(0, 1.5)) + + ggplot2::theme(panel.grid.minor = ggplot2::element_blank(), + panel.background = ggplot2::element_rect(fill = ""#FAFAFA"", colour = NA), panel.grid.major = ggplot2::element_blank(), + axis.ticks = ggplot2::element_blank(), axis.text.y = themeRA, + axis.text.x = theme, legend.key = ggplot2::element_blank(), + strip.text.x = theme, strip.background = ggplot2::element_blank(), + legend.position = ""none"") + if (!missing(title)) { + plot <- plot + ggplot2::ggtitle(title) + } + if (!is.null(fileName)) + ggplot2::ggsave(fileName, plot, width = 6, height = 4.5, + dpi = 400) + return(plot) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","LargeScalePopEst/R/CreateCohorts.R",".R","9304","153","# Copyright 2017 Observational Health Data Sciences and Informatics +# +# This file is part of LargeScalePopEst +# +# 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. + + +#' Create the exposure and outcome cohorts +#' +#' @details +#' This function will create the exposure and outcome cohorts following the definitions included in +#' this package. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param workDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param studyCohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param exposureCohortSummaryTable The name of the table that will be created in the work database schema. +#' This table will hold the summary of the exposure cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param workFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' +#' @export +createCohorts <- function(connectionDetails, + cdmDatabaseSchema, + workDatabaseSchema, + studyCohortTable = ""ohdsi_cohorts"", + exposureCohortSummaryTable = ""ohdsi_cohort_summary"", + oracleTempSchema, + workFolder) { + if (!file.exists(workFolder)) { + dir.create(workFolder) + } + conn <- DatabaseConnector::connect(connectionDetails) + + # Create study cohort table structure: + sql <- SqlRender::loadRenderTranslateSql(""CreateCohortTable.sql"", + ""LargeScalePopEst"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable) + DatabaseConnector::executeSql(conn, sql, progressBar = FALSE, reportOverallTime = FALSE) + + writeLines(""- Creating exposure cohorts"") + sql <- SqlRender::loadRenderTranslateSql(""ExposureCohorts.sql"", + ""LargeScalePopEst"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + washout_period = 365) + DatabaseConnector::executeSql(conn, sql) + + writeLines(""- Creating exposure cohort pairs"") + sql <- SqlRender::loadRenderTranslateSql(""CreateCohortPairs.sql"", + ""LargeScalePopEst"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable, + target_cohort_summary_table = exposureCohortSummaryTable) + DatabaseConnector::executeSql(conn, sql) + + sql <- ""SELECT * FROM @target_database_schema.@target_cohort_summary_table"" + sql <- SqlRender::renderSql(sql,target_database_schema = workDatabaseSchema, + target_cohort_summary_table = exposureCohortSummaryTable)$sql + sql <- SqlRender::translateSql(sql, targetDialect = connectionDetails$dbms)$sql + exposureSummary <- DatabaseConnector::querySql(conn, sql) + colnames(exposureSummary) <- SqlRender::snakeCaseToCamelCase(colnames(exposureSummary)) + write.csv(exposureSummary, file.path(workFolder, ""exposureSummary.csv""), row.names = FALSE) + + writeLines(""- Creating negative control cohorts"") + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""LargeScalePopEst"") + negativeControls <- read.csv(pathToCsv) + sql <- SqlRender::loadRenderTranslateSql(""NegativeControls.sql"", + ""LargeScalePopEst"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable, + outcome_ids = negativeControls$conceptId) + DatabaseConnector::executeSql(conn, sql) + + writeLines(""- Creating health outcomes of interest cohorts"") + pathToCsv <- system.file(""settings"", ""OutcomesOfInterest.csv"", package = ""LargeScalePopEst"") + outcomes <- read.csv(pathToCsv) + for (i in 1:nrow(outcomes)) { + writeLines(paste("" -"", outcomes$name[i])) + sql <- SqlRender::loadRenderTranslateSql(paste0(outcomes$name[i], "".sql""), + ""LargeScalePopEst"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable, + target_cohort_id = outcomes$cohortDefinitionId[i]) + DatabaseConnector::executeSql(conn, sql) + } + + # Check number of subjects per cohort: + sql <- ""SELECT cohort_definition_id, COUNT(*) AS count FROM @work_database_schema.@study_cohort_table GROUP BY cohort_definition_id"" + sql <- SqlRender::renderSql(sql, + work_database_schema = workDatabaseSchema, + study_cohort_table = studyCohortTable)$sql + sql <- SqlRender::translateSql(sql, targetDialect = connectionDetails$dbms)$sql + counts <- DatabaseConnector::querySql(conn, sql) + names(counts) <- SqlRender::snakeCaseToCamelCase(names(counts)) + + cohortNames <- data.frame() + cohortNames <- rbind(cohortNames, data.frame(cohortDefinitionId = exposureSummary$tprimeCohortDefinitionId, + name = exposureSummary$tCohortDefinitionName, + type = ""targetExposure"")) + cohortNames <- rbind(cohortNames, data.frame(cohortDefinitionId = exposureSummary$cprimeCohortDefinitionId, + name = exposureSummary$cCohortDefinitionName, + type = ""comparatorExposure"")) + cohortNames <- rbind(cohortNames, data.frame(cohortDefinitionId = outcomes$cohortDefinitionId, + name = outcomes$name, + type = ""outcome"")) + cohortNames <- rbind(cohortNames, data.frame(cohortDefinitionId = negativeControls$conceptId, + name = negativeControls$name, + type = ""negativeControl"")) + write.csv(cohortNames, file.path(workFolder, ""cohortNames.csv""), row.names = FALSE) + + counts <- merge(counts, cohortNames) + write.csv(counts, file.path(workFolder, ""cohortCounts.csv""), row.names = FALSE) + print(counts) + + RJDBC::dbDisconnect(conn) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","LargeScalePopEst/R/FilterByExposureCohortsSize.R",".R","1402","30","# Copyright 2017 Observational Health Data Sciences and Informatics +# +# This file is part of LargeScalePopEst +# +# 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. + +#' Filter exposure pairs by size of the cohorts +#' +#' @param workFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' @param minCohortsSize Minimum number of people that have to be in each cohort to keep a pair of +#' cohorts. +#' +#' @export +filterByExposureCohortsSize <- function(workFolder, minCohortsSize = 2500) { + exposureSummary <- read.csv(file.path(workFolder, ""exposureSummary.csv"")) + filtered <- exposureSummary[exposureSummary$tprimeNumPersons > minCohortsSize & exposureSummary$cprimeNumPersons > minCohortsSize, ] + write.csv(filtered, file.path(workFolder, ""exposureSummaryFilteredBySize.csv""), row.names = FALSE) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","LargeScalePopEst/R/CohortMethod.R",".R","10777","171","# Copyright 2017 Observational Health Data Sciences and Informatics +# +# This file is part of LargeScalePopEst +# +# 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. + +#' Run the cohort method package +#' +#' @details +#' Runs the cohort method package to produce propensity scores and outcome models. +#' +#' @param workFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' @param maxCores How many parallel cores should be used? If more cores are made available +#' this can speed up the analyses. +#' +#' @export +runCohortMethod <- function(workFolder, maxCores = 4) { + cmFolder <- file.path(workFolder, ""cmOutput"") + exposureSummary <- read.csv(file.path(workFolder, ""exposureSummaryFilteredBySize.csv"")) + createDcos <- function(i, exposureSummary) { + # originalTargetId <- exposureSummary$tCohortDefinitionId[i] + # originalComparatorId <- exposureSummary$cCohortDefinitionId[i] + targetId <- exposureSummary$tprimeCohortDefinitionId[i] + comparatorId <- exposureSummary$cprimeCohortDefinitionId[i] + folderName <- file.path(cmFolder, paste0(""CmData_l1_t"", targetId, ""_c"", comparatorId)) + cmData <- CohortMethod::loadCohortMethodData(folderName, readOnly = TRUE) + outcomeIds <- attr(cmData$outcomes, ""metaData"")$outcomeIds + dco <- CohortMethod::createDrugComparatorOutcomes(targetId = targetId, + comparatorId = comparatorId, + outcomeIds = outcomeIds) + return(dco) + } + dcos <- lapply(1:nrow(exposureSummary), createDcos, exposureSummary) + cmAnalysisListFile <- system.file(""settings"", + ""cmAnalysisList.txt"", + package = ""LargeScalePopEst"") + cmAnalysisList <- CohortMethod::loadCmAnalysisList(cmAnalysisListFile) + + pathToCsv <- system.file(""settings"", ""OutcomesOfInterest.csv"", package = ""LargeScalePopEst"") + hois <- read.csv(pathToCsv) + + CohortMethod::runCmAnalyses(connectionDetails = NULL, + cdmDatabaseSchema = NULL, + exposureDatabaseSchema = NULL, + exposureTable = NULL, + outcomeDatabaseSchema = NULL, + outcomeTable = NULL, + outputFolder = cmFolder, + oracleTempSchema = NULL, + cmAnalysisList = cmAnalysisList, + cdmVersion = 5, + drugComparatorOutcomesList = dcos, + getDbCohortMethodDataThreads = 1, + createStudyPopThreads = 1,#min(4, maxCores), + createPsThreads = max(1, round(maxCores/10)), + psCvThreads = min(10, maxCores), + trimMatchStratifyThreads = min(4, maxCores), + fitOutcomeModelThreads = min(6, maxCores), + outcomeCvThreads = min(2, maxCores), + refitPsForEveryOutcome = FALSE, + outcomeIdsOfInterest = hois$cohortDefinitionId) + outcomeModelReference <- readRDS(file.path(workFolder, ""cmOutput"", ""outcomeModelReference.rds"")) + analysesSum <- CohortMethod::summarizeAnalyses(outcomeModelReference) + write.csv(analysesSum, file.path(workFolder, ""analysisSummary.csv""), row.names = FALSE) +} + +#' Create the analyses details +#' +#' @details +#' This function creates files specifying the analyses that will be performed. +#' +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes (/) +#' +#' @export +createAnalysesDetails <- function(outputFolder) { + # dummy args, will never be used because data objects have already been created: + getDbCmDataArgs <- CohortMethod::createGetDbCohortMethodDataArgs(covariateSettings = FeatureExtraction::createCovariateSettings()) + + createStudyPopArgs <- CohortMethod::createCreateStudyPopulationArgs(removeDuplicateSubjects = FALSE, + removeSubjectsWithPriorOutcome = TRUE, + riskWindowStart = 0, + riskWindowEnd = 0, + addExposureDaysToEnd = TRUE, + minDaysAtRisk = 1) + # Fixing seed for reproducability + # Ignoring high correlation with mental disorder covariates. These appear highly predictive when comparing nortriptyline to + # psychotherapy, which is probably correct (Many nortriptyline users appear to use the drug for headache-related conditions) + createPsArgs <- CohortMethod::createCreatePsArgs(control = Cyclops::createControl(noiseLevel = ""silent"", + cvType = ""auto"", + tolerance = 2e-07, + cvRepetitions = 1, + startingVariance = 0.01, + seed = 123), + stopOnError = FALSE) + + # matchOnPsArgs <- CohortMethod::createMatchOnPsArgs(maxRatio = 1) + + stratifyByPsArgs <- CohortMethod::createStratifyByPsArgs(numberOfStrata = 10) + + fitOutcomeModelArgs1 <- CohortMethod::createFitOutcomeModelArgs(stratified = FALSE, + useCovariates = FALSE, + modelType = ""cox"") + + fitOutcomeModelArgs2 <- CohortMethod::createFitOutcomeModelArgs(stratified = TRUE, + useCovariates = FALSE, + modelType = ""cox"") + + + cmAnalysis1 <- CohortMethod::createCmAnalysis(analysisId = 1, + description = ""Crude: no propensity scores"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = createStudyPopArgs, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + # cmAnalysis2 <- CohortMethod::createCmAnalysis(analysisId = 2, + # description = ""1-on-1 matching plus conditioned outcome model"", + # getDbCohortMethodDataArgs = getDbCmDataArgs, + # createStudyPopArgs = createStudyPopArgs, + # createPs = TRUE, + # createPsArgs = createPsArgs, + # matchOnPs = TRUE, + # matchOnPsArgs = matchOnPsArgs, + # fitOutcomeModel = TRUE, + # fitOutcomeModelArgs = fitOutcomeModelArgs2) + + cmAnalysis3 <- CohortMethod::createCmAnalysis(analysisId = 3, + description = ""PS stratification plus conditioned outcome model: Per-protocol"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = createStudyPopArgs, + createPs = TRUE, + createPsArgs = createPsArgs, + stratifyByPs = TRUE, + stratifyByPsArgs = stratifyByPsArgs, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs2) + + createStudyPopArgsItt <- CohortMethod::createCreateStudyPopulationArgs(removeDuplicateSubjects = FALSE, + removeSubjectsWithPriorOutcome = TRUE, + riskWindowStart = 0, + riskWindowEnd = 99999, + minDaysAtRisk = 1) + + cmAnalysis4 <- CohortMethod::createCmAnalysis(analysisId = 4, + description = ""PS stratification plus conditioned outcome model: ITT"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = createStudyPopArgsItt, + createPs = TRUE, + createPsArgs = createPsArgs, + stratifyByPs = TRUE, + stratifyByPsArgs = stratifyByPsArgs, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs2) + + # cmAnalysisList <- list(cmAnalysis1, cmAnalysis2, cmAnalysis3) + cmAnalysisList <- list(cmAnalysis1, cmAnalysis3, cmAnalysis4) + + CohortMethod::saveCmAnalysisList(cmAnalysisList, file.path(outputFolder, ""cmAnalysisList.txt"")) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","LargeScalePopEst/R/SignalInjection.R",".R","13069","219","# Copyright 2017 Observational Health Data Sciences and Informatics +# +# This file is part of LargeScalePopEst +# +# 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. + +#' Inject outcomes on top of negative controls +#' +#' @details +#' This function injects outcomes on top of negative controls to create controls with predefined relative risks greater than one. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param workDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param studyCohortTable The name of the study cohort table in the work database schema. +#' @param exposureCohortSummaryTable The name of the exposure summary table in the work database schema. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param workFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' @param maxCores How many parallel cores should be used? If more cores are made available +#' this can speed up the analyses. +#' +#' @export +injectSignals <- function(connectionDetails, + cdmDatabaseSchema, + workDatabaseSchema, + studyCohortTable = ""ohdsi_cohorts"", + oracleTempSchema, + workFolder, + exposureOutcomePairs = NULL, + maxCores = 4) { + signalInjectionFolder <- file.path(workFolder, ""signalInjection"") + if (!file.exists(signalInjectionFolder)) + dir.create(signalInjectionFolder) + + + createSignalInjectionDataFiles(workFolder, signalInjectionFolder) + + exposureSummary <- read.csv(file.path(workFolder, ""exposureSummaryFilteredBySize.csv"")) + + exposureCohortIds <- unique(c(exposureSummary$tCohortDefinitionId, exposureSummary$cCohortDefinitionId)) + + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""LargeScalePopEst"") + negativeControls <- read.csv(pathToCsv) + negativeControlIds <- negativeControls$conceptId + if (is.null(exposureOutcomePairs)) { + exposureOutcomePairs <- data.frame(exposureId = rep(exposureCohortIds, each = length(negativeControlIds)), + outcomeId = rep(negativeControlIds, length(exposureCohortIds))) + } + summ <- MethodEvaluation::injectSignals(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = cdmDatabaseSchema, + outcomeDatabaseSchema = workDatabaseSchema, + outcomeTable = studyCohortTable, + outputDatabaseSchema = workDatabaseSchema, + outputTable = studyCohortTable, + createOutputTable = FALSE, + exposureOutcomePairs = exposureOutcomePairs, + modelType = ""survival"", + buildOutcomeModel = TRUE, + buildModelPerExposure = FALSE, + minOutcomeCountForModel = 100, + minOutcomeCountForInjection = 25, + prior = Cyclops::createPrior(""laplace"", exclude = 0, useCrossValidation = TRUE), + control = Cyclops::createControl(cvType = ""auto"", + startingVariance = 0.01, + tolerance = 2e-07, + cvRepetitions = 1, + noiseLevel = ""silent"", + threads = min(10, maxCores)), + firstExposureOnly = TRUE, + washoutPeriod = 183, + riskWindowStart = 0, + riskWindowEnd = 0, + addExposureDaysToEnd = TRUE, + firstOutcomeOnly = TRUE, + removePeopleWithPriorOutcomes = TRUE, + maxSubjectsForModel = 250000, + effectSizes = c(1.5, 2, 4), + precision = 0.01, + outputIdOffset = 10000, + workFolder = signalInjectionFolder, + cdmVersion = ""5"", + modelThreads = max(1, round(maxCores/10)), + generationThreads = min(6, maxCores)) + # summ <- readRDS(file.path(signalInjectionFolder, ""summary.rds"")) + write.csv(summ, file.path(workFolder, ""signalInjectionSummary.csv""), row.names = FALSE) + + ffbase::load.ffdf(dir = file.path(workFolder, ""allCohorts"")) + subjectIds <- ffbase::unique.ff(cohorts$subjectId) + subjectIds <- data.frame(subject_id = ff::as.ram(subjectIds)) + conn <- DatabaseConnector::connect(connectionDetails) + DatabaseConnector::insertTable(connection = conn, + tableName = ""#subjects"", + data = subjectIds, + dropTableIfExists = TRUE, + createTable = TRUE, + tempTable = TRUE, + oracleTempSchema = oracleTempSchema) + sql <- SqlRender::loadRenderTranslateSql(""GetInjectedOutcomes.sql"", + ""LargeScalePopEst"", + dbms = connectionDetails$dbms, + output_database_schema = workDatabaseSchema, + output_table = studyCohortTable, + min_id = min(summ$newOutcomeId), + max_id = max(summ$newOutcomeId)) + injectedOutcomes <- DatabaseConnector::querySql.ffdf(conn, sql) + colnames(injectedOutcomes) <- SqlRender::snakeCaseToCamelCase(colnames(injectedOutcomes)) + injectedOutcomesFolder <- file.path(workFolder, ""injectedOutcomes"") + if (file.exists(injectedOutcomesFolder)) { + unlink(injectedOutcomesFolder, recursive = TRUE) + } + ffbase::save.ffdf(injectedOutcomes, dir = injectedOutcomesFolder) +} + +createSignalInjectionDataFiles <- function(workFolder, signalInjectionFolder) { + # Creating all data files needed by MethodEvaluation::injectSignals from our big data fetch. + exposureSummary <- read.csv(file.path(workFolder, ""exposureSummaryFilteredBySize.csv"")) + cohortDefinitionIdToConceptId <- rbind(data.frame(cohortDefinitionId = exposureSummary$tprimeCohortDefinitionId, + conceptId = exposureSummary$tCohortDefinitionId), + data.frame(cohortDefinitionId = exposureSummary$cprimeCohortDefinitionId, + conceptId = exposureSummary$cCohortDefinitionId)) + + + + # Create exposures file: + ffbase::load.ffdf(dir = file.path(workFolder, ""allCohorts"")) + exposures <- merge(cohorts, ff::as.ffdf(cohortDefinitionIdToConceptId)) + conceptIds <- unique(cohortDefinitionIdToConceptId$conceptId) + dedupe <- function(exposureId, data) { + data <- data[data$conceptId == exposureId,] + data <- ff::as.ram(data) + data <- data[order(data$rowId), ] + data <- data[!duplicated(data$rowId), ] + return(data) + } + exposures <- sapply(conceptIds, dedupe, data = exposures, simplify = FALSE) + exposures <- do.call(""rbind"", exposures) + exposures$daysToCohortEnd[exposures$daysToCohortEnd > exposures$daysToObsEnd] <- exposures$daysToObsEnd[exposures$daysToCohortEnd > exposures$daysToObsEnd] + + colnames(exposures)[colnames(exposures) == ""daysToCohortEnd""] <- ""daysAtRisk"" + colnames(exposures)[colnames(exposures) == ""conceptId""] <- ""exposureId"" + colnames(exposures)[colnames(exposures) == ""subjectId""] <- ""personId"" + exposures$eraNumber <- 1 + exposures <- exposures[, c(""rowId"", ""exposureId"", ""personId"", ""cohortStartDate"", ""daysAtRisk"", ""eraNumber"")] + saveRDS(exposures, file.path(signalInjectionFolder, ""exposures.rds"")) + + # Create outcomes file: + ffbase::load.ffdf(dir = file.path(workFolder, ""allOutcomes"")) + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""LargeScalePopEst"") + negativeControls <- read.csv(pathToCsv) + negativeControlIds <- negativeControls$conceptId + negativeControlOutcomes <- outcomes[ffbase::`%in%`(outcomes$outcomeId, negativeControlIds),] + negativeControlOutcomes <- merge(negativeControlOutcomes, ff::as.ffdf(exposures[, c(""rowId"", ""daysAtRisk"")])) + + dedupeAndCount <- function(outcomeId, data) { + if (!ffbase::any.ff(data$outcomeId == outcomeId)) { + return(data.frame()) + } + data <- ff::as.ram(data[data$outcomeId == outcomeId, ]) + data <- data[data$daysToEvent >= 0 & data$daysToEvent <= data$daysAtRisk, ] + if (nrow(data) == 0) { + return(data.frame()) + } + y <- aggregate(outcomeId ~ rowId, data, length) + colnames(y)[colnames(y) == ""outcomeId""] <- ""y"" + timeToEvent <- aggregate(daysToEvent ~ rowId, data, min) + colnames(timeToEvent)[colnames(timeToEvent) == ""daysToEvent""] <- ""timeToEvent"" + result <- merge(y, timeToEvent) + result$outcomeId <- outcomeId + return(result) + } + outcomes2 <- sapply(negativeControlIds, dedupeAndCount, data = negativeControlOutcomes, simplify = FALSE) + outcomes2 <- do.call(""rbind"", outcomes2) + saveRDS(outcomes2, file.path(signalInjectionFolder, ""outcomes.rds"")) + + priorOutcomes <- negativeControlOutcomes[negativeControlOutcomes$daysToEvent < 0, c(""rowId"", ""outcomeId"")] + dedupe <- function(outcomeId, data) { + if (!ffbase::any.ff(data$outcomeId == outcomeId)) { + return(data.frame()) + } + data <- data[data$outcomeId == outcomeId, ] + rowIds <- ff::as.ram(ffbase::unique.ff(data$rowId)) + return(data.frame(rowId = rowIds, outcomeId = outcomeId)) + } + priorOutcomes <- sapply(negativeControlIds, dedupe, data = priorOutcomes, simplify = FALSE) + priorOutcomes <- do.call(""rbind"", priorOutcomes) + saveRDS(priorOutcomes, file.path(signalInjectionFolder, ""priorOutcomes.rds"")) + + # Clone covariate data: + covariatesFolder <- file.path(signalInjectionFolder, ""covariates"") + if (file.exists(covariatesFolder)) { + unlink(covariatesFolder, recursive = TRUE) + } + covariateData <- FeatureExtraction::loadCovariateData(file.path(workFolder, ""allCovariates"")) + covariateDataClone <- list(covariates = ff::clone.ffdf(covariateData$covariates), + covariateRef = ff::clone.ffdf(covariateData$covariateRef), + metaData = covariateData$metaData) + class(covariateDataClone) = class(covariateData) + FeatureExtraction::saveCovariateData(covariateDataClone, covariatesFolder) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","LargeScalePopEst/R/LargeScalePopEst.R",".R","1575","43","# Copyright 2017 Observational Health Data Sciences and Informatics +# +# This file is part of LargeScalePopEst +# +# 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. + +#' LargeScalePopEst +#' +#' @docType package +#' @name LargeScalePopEst +#' @import DatabaseConnector +NULL + +.onLoad <- function(libname, pkgname) { + missing(libname) # suppresses R CMD check note + missing(pkgname) # suppresses R CMD check note + # Copied this from the ff package: + if (is.null(getOption(""ffmaxbytes""))) { + # memory.limit is windows specific + if (.Platform$OS.type == ""windows"") { + if (getRversion() >= ""2.6.0"") + options(ffmaxbytes = 0.5 * utils::memory.limit() * (1024^2)) else options(ffmaxbytes = 0.5 * utils::memory.limit()) + } else { + # some magic constant + options(ffmaxbytes = 0.5 * 1024^3) + } + } + + # Workaround for problem with ff on machines with lots of memory (see + # https://github.com/edwindj/ffbase/issues/37) + options(ffmaxbytes = min(getOption(""ffmaxbytes""), .Machine$integer.max * 12)) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","LargeScalePopEst/R/Calibration.R",".R","13547","235","# @file Calibration.R +# +# Copyright 2017 Observational Health Data Sciences and Informatics +# +# This file is part of LargeScalePopEst +# +# 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. + +#' Created calibrated confidence intervals, estimates, and p-values. +#' +#' @param workFolder Name of local folder to place results; make sure to use forward slashes +#' (/). Do not use a folder on a network drive since this greatly impacts +#' performance. +#' +#' @export +calibrateEstimatesAndPvalues <- function(workFolder) { + figuresAndTablesFolder <- file.path(workFolder, ""figuresAndtables"") + if (!file.exists(figuresAndTablesFolder)) { + dir.create(figuresAndTablesFolder) + } + calibrationFolder <- file.path(figuresAndTablesFolder, ""calibration"") + if (!file.exists(calibrationFolder)) { + dir.create(calibrationFolder) + } + + exposureSummary <- read.csv(file.path(workFolder, ""exposureSummaryFilteredBySize.csv"")) + # exposureSummary <- exposureSummary[exposureSummary$tCohortDefinitionName != ""Psychotherapy"" & exposureSummary$tCohortDefinitionName != + # ""Electroconvulsive therapy"" & exposureSummary$cCohortDefinitionName != ""Psychotherapy"" & exposureSummary$cCohortDefinitionName != + # ""Electroconvulsive therapy"", ] + analysesSum <- read.csv(file.path(workFolder, ""analysisSummary.csv"")) + analysesSumRev <- data.frame(analysisId = analysesSum$analysisId, + targetId = analysesSum$comparatorId, + comparatorId = analysesSum$targetId, + outcomeId = analysesSum$outcomeId, + rr = 1/analysesSum$rr, + ci95lb = 1/analysesSum$ci95ub, + ci95ub = 1/analysesSum$ci95lb, + p = analysesSum$p, + treated = analysesSum$comparator, + comparator = analysesSum$treated, + treatedDays = analysesSum$comparatorDays, + comparatorDays = analysesSum$treatedDays, + eventsTreated = analysesSum$eventsComparator, + eventsComparator = analysesSum$eventsTreated, + logRr = -analysesSum$logRr, + seLogRr = analysesSum$seLogRr) + results <- rbind(analysesSum, analysesSumRev) + results$calP <- NA + results$calPlb <- NA + results$calPub <- NA + results$calLogRr <- NA + results$calSeLogRr <- NA + results$calRr <- NA + results$calCi95lb <- NA + results$calCi95ub <- NA + signalInjectionSum <- read.csv(file.path(workFolder, ""signalInjectionSummary.csv"")) + negativeControlIds <- unique(signalInjectionSum$outcomeId) + # i <- which(exposureSummary$tprimeCohortDefinitionId == 4327941136) + for (i in 1:nrow(exposureSummary)) { + treatmentId <- exposureSummary$tprimeCohortDefinitionId[i] + comparatorId <- exposureSummary$cprimeCohortDefinitionId[i] + treatmentConceptId <- exposureSummary$tCohortDefinitionId[i] + comparatorConceptId <- exposureSummary$cCohortDefinitionId[i] + treatmentName <- exposureSummary$tCohortDefinitionName[i] + comparatorName <- exposureSummary$cCohortDefinitionName[i] + for (analysisId in c(1, 3, 4)) { + estimates <- analysesSum[analysesSum$analysisId == analysisId & analysesSum$targetId == treatmentId & + analysesSum$comparatorId == comparatorId, ] + + negControls <- estimates[estimates$outcomeId %in% negativeControlIds, ] + null <- EmpiricalCalibration::fitMcmcNull(logRr = negControls$logRr, + seLogRr = negControls$seLogRr) + calibratedP <- EmpiricalCalibration::calibrateP(null = null, + logRr = estimates$logRr, + seLogRr = estimates$seLogRr) + idx <- which(results$analysisId == analysisId & results$targetId == treatmentId & results$comparatorId == + comparatorId) + idx <- idx[match(estimates$outcomeId, results$outcomeId[idx])] + results$calP[idx] <- calibratedP$p + results$calPlb[idx] <- calibratedP$lb95ci + results$calPub[idx] <- calibratedP$ub95ci + idx <- which(results$analysisId == analysisId & results$targetId == comparatorId & results$comparatorId == + treatmentId) + idx <- idx[match(estimates$outcomeId, results$outcomeId[idx])] + results$calP[idx] <- calibratedP$p + results$calPlb[idx] <- calibratedP$lb95ci + results$calPub[idx] <- calibratedP$ub95ci + + fileName <- file.path(calibrationFolder, paste0(""negControls_a"", + analysisId, + ""_t"", + treatmentId, + ""_c"", + comparatorId, + "".png"")) + + if (analysisId == 1) { + analysisLabel <- ""Crude"" + } else if (analysisId == 3) { + analysisLabel <- ""Adjusted"" + } else if (analysisId == 4) { + analysisLabel <- ""ITT"" + } + title <- paste(treatmentName, ""vs."", comparatorName, ""-"", analysisLabel) + EmpiricalCalibration::plotCalibrationEffect(logRrNegatives = negControls$logRr, + seLogRrNegatives = negControls$seLogRr, + title = title, + xLabel = ""Hazard ratio"", + fileName = fileName) + fileName <- file.path(calibrationFolder, paste0(""negControls_a"", + analysisId, + ""_t"", + comparatorId, + ""_c"", + treatmentId, + "".png"")) + title <- paste(comparatorName, ""vs."", treatmentName, ""-"", analysisLabel) + EmpiricalCalibration::plotCalibrationEffect(logRrNegatives = -negControls$logRr, + seLogRrNegatives = negControls$seLogRr, + title = title, + xLabel = ""Hazard ratio"", + fileName = fileName) + + injectedSignals <- signalInjectionSum[signalInjectionSum$exposureId == treatmentConceptId & + signalInjectionSum$injectedOutcomes != 0, ] + negativeControlIdSubsets <- unique(injectedSignals$outcomeId) + injectedSignals <- data.frame(outcomeId = injectedSignals$newOutcomeId, + trueLogRr = log(injectedSignals$targetEffectSize)) + negativeControls <- data.frame(outcomeId = negativeControlIds, trueLogRr = 0) + data <- rbind(injectedSignals, negativeControls) + data <- merge(data, estimates[, c(""outcomeId"", ""logRr"", ""seLogRr"")]) + if (length(unique(data$trueLogRr)) > 1) { + model <- EmpiricalCalibration::fitSystematicErrorModel(logRr = data$logRr, + seLogRr = data$seLogRr, + trueLogRr = data$trueLogRr, + estimateCovarianceMatrix = FALSE) + calibratedCi <- EmpiricalCalibration::calibrateConfidenceInterval(logRr = estimates$logRr, + seLogRr = estimates$seLogRr, + model = model) + idx <- which(results$analysisId == analysisId & results$targetId == treatmentId & results$comparatorId == + comparatorId) + idx <- idx[match(estimates$outcomeId, results$outcomeId[idx])] + results$calLogRr[idx] <- calibratedCi$logRr + results$calSeLogRr[idx] <- calibratedCi$seLogRr + results$calRr[idx] <- exp(calibratedCi$logRr) + results$calCi95lb[idx] <- exp(calibratedCi$logLb95Rr) + results$calCi95ub[idx] <- exp(calibratedCi$logUb95Rr) + + calibratedCi$outcomeId <- estimates$outcomeId + data <- rbind(injectedSignals, + negativeControls[negativeControls$outcomeId %in% negativeControlIdSubsets, + ]) + data <- merge(data, calibratedCi) + fileName <- file.path(calibrationFolder, paste0(""trueAndObs_a"", + analysisId, + ""_t"", + treatmentId, + ""_c"", + comparatorId, + "".png"")) + analysisLabel <- ""Crude"" + if (analysisId != 1) { + analysisLabel <- ""Adjusted"" + } + title <- paste(treatmentName, ""vs."", comparatorName, ""-"", analysisLabel) + EmpiricalCalibration::plotTrueAndObserved(logRr = data$logRr, + seLogRr = data$seLogRr, + trueLogRr = data$trueLogRr, + xLabel = ""Hazard ratio"", + title = title, + fileName = fileName) + } + + injectedSignals <- signalInjectionSum[signalInjectionSum$exposureId == comparatorConceptId & + signalInjectionSum$injectedOutcomes != 0, ] + negativeControlIdSubsets <- unique(injectedSignals$outcomeId) + injectedSignals <- data.frame(outcomeId = injectedSignals$newOutcomeId, + trueLogRr = log(injectedSignals$targetEffectSize)) + negativeControls <- data.frame(outcomeId = negativeControlIds, + trueLogRr = rep(0, length(negativeControlIds))) + data <- rbind(injectedSignals, negativeControls) + data <- merge(data, estimates[, c(""outcomeId"", ""logRr"", ""seLogRr"")]) + if (length(unique(data$trueLogRr)) > 1) { + model <- EmpiricalCalibration::fitSystematicErrorModel(logRr = -data$logRr, + seLogRr = data$seLogRr, + trueLogRr = data$trueLogRr, + estimateCovarianceMatrix = FALSE) + calibratedCi <- EmpiricalCalibration::calibrateConfidenceInterval(logRr = -estimates$logRr, + seLogRr = estimates$seLogRr, + model = model) + idx <- which(results$analysisId == analysisId & results$targetId == comparatorId & results$comparatorId == + treatmentId) + idx <- idx[match(estimates$outcomeId, results$outcomeId[idx])] + results$calLogRr[idx] <- calibratedCi$logRr + results$calSeLogRr[idx] <- calibratedCi$seLogRr + results$calRr[idx] <- exp(calibratedCi$logRr) + results$calCi95lb[idx] <- exp(calibratedCi$logLb95Rr) + results$calCi95ub[idx] <- exp(calibratedCi$logUb95Rr) + + calibratedCi$outcomeId <- estimates$outcomeId + data <- rbind(injectedSignals, + negativeControls[negativeControls$outcomeId %in% negativeControlIdSubsets, + ]) + data <- merge(data, calibratedCi) + + fileName <- file.path(calibrationFolder, paste0(""trueAndObs_a"", + analysisId, + ""_t"", + comparatorId, + ""_c"", + treatmentId, + "".png"")) + title <- paste(comparatorName, ""vs."", treatmentName, ""-"", analysisLabel) + EmpiricalCalibration::plotTrueAndObserved(logRr = data$logRr, + seLogRr = data$seLogRr, + trueLogRr = data$trueLogRr, + xLabel = ""Hazard ratio"", + title = title, + fileName = fileName) + } + } + } + write.csv(results, file.path(workFolder, ""calibratedEstimates.csv""), row.names = FALSE) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","LargeScalePopEst/extras/PackageMaintenance.R",".R","1452","39","# Copyright 2017 Observational Health Data Sciences and Informatics +# +# This file is part of LargeScalePopEst +# +# 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. + +# Format and check code +OhdsiRTools::formatRFolder() +OhdsiRTools::checkUsagePackage(""LargeScalePopEst"") +OhdsiRTools::updateCopyrightYearFolder() + +# Create manual +shell(""rm extras//LargeScalePopEst.pdf"") +shell(""R CMD Rd2pdf ./ --output=extras/LargeScalePopEst.pdf"") + +# Import outcome definitions +pathToCsv <- system.file(""settings"", ""OutcomesOfInterest.csv"", package = ""LargeScalePopEst"") +outcomes <- read.csv(pathToCsv) +for (i in 1:nrow(outcomes)) { + writeLines(paste0(""Inserting HOI: "", outcomes$name[i])) + OhdsiRTools::insertCohortDefinitionInPackage(outcomes$cohortDefinitionId[i], outcomes$name[i]) +} + +# Create analysis details +createAnalysesDetails(""inst/settings/"") + +# Store environment in which the study was executed +OhdsiRTools::insertEnvironmentSnapshotInPackage(""LargeScalePopEst"") +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","LargeScalePopEst/extras/LargeScaleCleanup.R",".R","1254","34","workFolder <- ""R:/PopEstDepression_MDCD"" + +badIds <- c(4030840, 4327941) + +findFiles <- function(id, files) { + nameOnly <- gsub(""^.*/"", """", files) + return(files[grepl(id, nameOnly)]) +} + +findFilesInFolder <- function(folder, badIds) { + files <- list.files(path = folder, recursive = TRUE, include.dirs = TRUE) + toDel <- unique(do.call(""c"", sapply(badIds, findFiles, files))) + toDel <- toDel[order(toDel)] + toDel <- file.path(folder, toDel) + return(toDel) +} +toDel <- findFilesInFolder(file.path(workFolder, ""cmOutput""), badIds) + +unlink(toDel, recursive = TRUE) + +unlink(file.path(workFolder, ""signalInjection""), recursive = TRUE) +unlink(file.path(workFolder, ""injectedOutcomes""), recursive = TRUE) +unlink(file.path(workFolder, ""allCohorts""), recursive = TRUE) +unlink(file.path(workFolder, ""allCovariates""), recursive = TRUE) +unlink(file.path(workFolder, ""allOutcomes""), recursive = TRUE) + + +# Reuse PS models --------------------------------------------------------- + +workFolder <- ""R:/PopEstDepression_MDCD"" +files <- list.files(path = file.path(workFolder, ""cmOutput""), pattern = ""Ps_l1_s1_p2_t[0-9]+_c[0-9]+.rds"") +newFiles <- gsub(""_s1_"", ""_s2_"", files) +file.copy(file.path(workFolder, ""cmOutput"", files), file.path(workFolder, ""cmOutput"", newFiles)) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","LargeScalePopEst/extras/ExtractEstimateSet.R",".R","5376","107","workFolder <- ""R:/PopEstDepression_Ccae"" + +dbs <- c(""CCAE"", ""MDCD"", ""MDCR"", ""Optum"") + +exposures <- read.csv(paste0(workFolder, ""/exposureSummaryFilteredBySize.csv"")) +exposures1 <- data.frame(targetId = exposures$tprimeCohortDefinitionId, + comparatorId = exposures$cprimeCohortDefinitionId, + targetName = exposures$tCohortDefinitionName, + comparatorName = exposures$cCohortDefinitionName) +exposures2 <- data.frame(targetId = exposures$cprimeCohortDefinitionId, + comparatorId = exposures$tprimeCohortDefinitionId, + targetName = exposures$cCohortDefinitionName, + comparatorName = exposures$tCohortDefinitionName) +exposures <- rbind(exposures1, exposures2) + +pathToCsv <- system.file(""settings"", ""OutcomesOfInterest.csv"", package = ""LargeScalePopEst"") +hois <- read.csv(pathToCsv) +hois <- data.frame(outcomeId = hois$cohortDefinitionId, + outcomeName = hois$name, + outcomeType = ""hoi"", + trueRr = NA) + +pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""LargeScalePopEst"") +negativeControls <- read.csv(pathToCsv) +negativeControls <- data.frame(outcomeId = negativeControls$conceptId, + outcomeName = negativeControls$name, + outcomeType = ""negative control"", + trueRr = 1) + +calibrated <- data.frame() +for (db in dbs) { + temp <- read.csv(paste0(""R:/PopEstDepression_"", db, ""/calibratedEstimates.csv"")) + temp$db <- db + temp <- merge(temp, exposures) + + tempHois <- merge(temp, hois) + tempNegativeControls <- merge(temp, negativeControls) + + positiveControls <- read.csv(paste0(""R:/PopEstDepression_"", db, ""/signalInjectionSummary.csv"")) + positiveControls <- merge(positiveControls, negativeControls[, c(""outcomeId"", ""outcomeName"")]) + positiveControls <- data.frame(outcomeId = positiveControls$newOutcomeId, + exposureId = positiveControls$exposureId, + outcomeName = paste0(positiveControls$outcomeName, ""_rr"", positiveControls$targetEffectSize), + outcomeType = ""positive control"", + trueRr = positiveControls$targetEffectSize) + tempPositiveControls <- temp + tempPositiveControls$exposureId <- as.character(tempPositiveControls$targetId) + tempPositiveControls$exposureId <- substr(tempPositiveControls$exposureId, 1, nchar(tempPositiveControls$exposureId)-3) + tempPositiveControls$exposureId <- as.numeric(tempPositiveControls$exposureId) + tempPositiveControls <- merge(tempPositiveControls, positiveControls) + tempPositiveControls$exposureId <- NULL + + calibrated <- rbind(calibrated, tempHois, tempNegativeControls, tempPositiveControls) +} +#temp[temp$outcomeId == 436634 & temp$targetId == 710062026 & temp$analysisId == 3, ] + +#calibrated <- calibrated[!(calibrated$targetName %in% c(""Psychotherapy"" , ""Electroconvulsive therapy"")) & !(calibrated$comparatorName %in% c(""Psychotherapy"" , ""Electroconvulsive therapy"")), ] +## Rewrite calibrated SE to take asymmetry of CI into account: +temp <- calibrated$calSeLogRr +idx <- !is.na(calibrated$calLogRr) & calibrated$calLogRr > 0 +calibrated$calSeLogRr[idx] <- (log(calibrated$calCi95lb[idx]) - calibrated$calLogRr[idx]) / qnorm(0.025) +idx <- !is.na(calibrated$calLogRr) & calibrated$calLogRr < 0 +calibrated$calSeLogRr[idx] <- (log(calibrated$calCi95ub[idx]) - calibrated$calLogRr[idx]) / qnorm(0.975) + +write.csv(calibrated, ""r:/DepressionResults.csv"", row.names = FALSE) + + + + +# Dataset checks ---------------------------------------------------------- +#result <- calibrated +result <- read.csv(""r:/DepressionResults.csv"") +# Are all rows unique? +nrow(result) == nrow(unique(result[, c(""analysisId"", ""db"", ""targetName"", ""comparatorName"", ""outcomeName"")])) + +# Symmetrical? +half1 <- result[result$targetId < result$comparatorId & result$outcomeType == ""hoi"", ] +half2 <- result[result$targetId > result$comparatorId & result$outcomeType == ""hoi"", ] +nrow(half1) == nrow(half2) + +# All DBs? +aggregate(analysisId ~ db, data = result, length) + +#Negative SEs? +!any(result$calSeLogRr < 0, na.rm = TRUE) + +# calibrated and uncalibrated are correlated? +library(ggplot2) +plot <- ggplot(result, aes(x = rr, y = calRr)) + + geom_point() + + scale_x_log10(limits = c(0.1,10)) + + scale_y_log10(limits = c(0.1,10)) + + facet_wrap(~db) +ggsave(""r:/temp/corr.png"", plot, width = 5, height = 5, dpi = 300) + +# A to B correlated with B to A? +half1 <- result[result$targetId < result$comparatorId & result$outcomeType == ""hoi"", c(""targetId"", ""comparatorId"", ""outcomeId"", ""analysisId"", ""db"", ""calRr"")] +half2 <- result[result$targetId > result$comparatorId & result$outcomeType == ""hoi"", c(""targetId"", ""comparatorId"", ""outcomeId"", ""analysisId"", ""db"", ""calRr"")] +d <- merge(half1, half2, by.x = c(""targetId"", ""comparatorId"", ""outcomeId"", ""analysisId"", ""db""), by.y = c(""comparatorId"", ""targetId"", ""outcomeId"", ""analysisId"", ""db"")) +library(ggplot2) +plot <- ggplot(d, aes(x = calRr.x, y = calRr.y)) + + geom_point() + + scale_x_log10(limits = c(0.1,10)) + + scale_y_log10(limits = c(0.1,10)) + + facet_wrap(~db) +ggsave(""r:/temp/corr2.png"", plot, width = 5, height = 5, dpi = 300) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","LargeScalePopEst/extras/PlotsForSymposium.R",".R","33706","520","workFolder <- ""R:/PopEstDepression_Ccae"" +workFolder <- ""s:/PopEstDepression_Ccae"" +symposiumFolder <- file.path(workFolder, ""symposium"") +if (!file.exists(symposiumFolder)) { + dir.create(symposiumFolder) +} +exposureSummary <- read.csv(file.path(workFolder, ""exposureSummaryFilteredBySize.csv"")) +outcomeModelReference <- readRDS(file.path(workFolder, ""cmOutput"", ""outcomeModelReference.rds"")) +analysesSum <- read.csv(file.path(workFolder, ""analysisSummary.csv"")) +signalInjectionSum <- read.csv(file.path(workFolder, ""signalInjectionSummary.csv"")) +negativeControlIds <- unique(signalInjectionSum$outcomeId) + +row <- exposureSummary[exposureSummary$tCohortDefinitionName == ""duloxetine"" & exposureSummary$cCohortDefinitionName == + ""Sertraline"", ] +treatmentId <- row$tprimeCohortDefinitionId +comparatorId <- row$cprimeCohortDefinitionId +estimates <- analysesSum[analysesSum$targetId == treatmentId & analysesSum$comparatorId == comparatorId, ] +calibrated <- read.csv(file.path(workFolder, ""calibratedEstimates.csv"")) + +########################################################################### Get PS plot # +psFile <- outcomeModelReference$sharedPsFile[outcomeModelReference$analysisId == 3 & outcomeModelReference$targetId == + treatmentId & outcomeModelReference$comparatorId == comparatorId][1] +ps <- readRDS(psFile) +fileName <- file.path(symposiumFolder, ""Ps.png"") +CohortMethod::plotPs(ps, + scale = ""preference"", + treatmentLabel = as.character(row$tCohortDefinitionName), + comparatorLabel = as.character(row$cCohortDefinitionName), + fileName = fileName) +file.copy(from = file.path(workFolder, + ""figuresAndtables"", + ""ps"", + paste0(""ps_t"", treatmentId, ""_c"", comparatorId, "".png"")), + to = file.path(symposiumFolder, ""Ps.png""), + overwrite = TRUE) +mean(ps$preferenceScore[ps$treatment == 1] > 0.3 & ps$preferenceScore[ps$treatment == 1] < 0.7) +mean(ps$preferenceScore[ps$treatment == 0] > 0.3 & ps$preferenceScore[ps$treatment == 0] < 0.7) + +########################################################################### Create covariate balance plot # +cohortMethodDataFolder <- outcomeModelReference$cohortMethodDataFolder[outcomeModelReference$targetId == + treatmentId & outcomeModelReference$comparatorId == comparatorId & outcomeModelReference$analysisId == + 3 & outcomeModelReference$outcomeId == 2559] +strataFile <- outcomeModelReference$strataFile[outcomeModelReference$targetId == treatmentId & outcomeModelReference$comparatorId == + comparatorId & outcomeModelReference$analysisId == 3 & outcomeModelReference$outcomeId == 2559] + +cohortMethodDataFolder <- gsub(""^S:"", ""R:"", cohortMethodDataFolder) +strataFile <- gsub(""^S:"", ""R:"", strataFile) + +cohortMethodData <- CohortMethod::loadCohortMethodData(cohortMethodDataFolder) +strata <- readRDS(strataFile) + +balance <- CohortMethod::computeCovariateBalance(strata, cohortMethodData) + +tableFileName <- file.path(workFolder, ""symposium"", ""balance.csv"") +write.csv(balance, tableFileName, row.names = FALSE) + +plotFileName <- file.path(workFolder, ""symposium"", ""balanceScatterPlot.png"") +CohortMethod::plotCovariateBalanceScatterPlot(balance, fileName = plotFileName) + +plotFileName <- file.path(workFolder, ""symposium"", ""balanceTop.png"") +CohortMethod::plotCovariateBalanceOfTopVariables(balance, fileName = plotFileName) + +########################################################################### Get negative control distribution plots # +ingrownNail <- 139099 + +file.copy(from = file.path(workFolder, + ""figuresAndtables"", + ""controls"", + paste0(""negControls_a1_t"", treatmentId, ""_c"", comparatorId, "".png"")), + to = file.path(symposiumFolder, ""negControls_crude.png""), + overwrite = TRUE) + +negControls <- estimates[estimates$outcomeId %in% negativeControlIds & estimates$analysisId == 1, ] +writeLines(paste0(""Crude negative control p < 0.05: "", mean(negControls$p < 0.05))) + +example <- negControls[negControls$outcomeId == ingrownNail, ] +print(example) +plotEstimates(example$logRr, + example$seLogRr, + xLabel = ""Hazard ratio"", + title = ""duloxestine vs. Sertraline - Crude"", + fileName = file.path(symposiumFolder, ""ingrownNail_crude.png"")) + +file.copy(from = file.path(workFolder, + ""figuresAndtables"", + ""controls"", + paste0(""negControls_a3_t"", treatmentId, ""_c"", comparatorId, "".png"")), + to = file.path(symposiumFolder, ""negControls_adjusted.png""), + overwrite = TRUE) + +negControls <- estimates[estimates$outcomeId %in% negativeControlIds & estimates$analysisId == 3, ] +writeLines(paste0(""Adjusted negative control p < 0.05: "", mean(negControls$p < 0.05))) + +example <- negControls[negControls$outcomeId == ingrownNail, ] +print(example) +plotEstimates(example$logRr, + example$seLogRr, + xLabel = ""Hazard ratio"", + title = ""duloxestine vs. Sertraline - Adjusted"", + fileName = file.path(symposiumFolder, ""ingrownNail_adjusted.png"")) + +########################################################################### Get signal injection plot # +file.copy(from = file.path(workFolder, + ""figuresAndtables"", + ""controls"", + paste0(""trueAndObs_a3_t"", treatmentId, ""_c"", comparatorId, "".png"")), + to = file.path(symposiumFolder, ""trueAndObs.png""), + overwrite = TRUE) + +injectedSignals <- signalInjectionSum[signalInjectionSum$exposureId == row$tCohortDefinitionId, ] +injectedSignals <- data.frame(outcomeId = injectedSignals$newOutcomeId, + oldOutcomeId = injectedSignals$outcomeId, + trueLogRr = log(injectedSignals$targetEffectSize)) +negativeControlIdSubsets <- unique(signalInjectionSum$outcomeId[signalInjectionSum$exposureId == row$tCohortDefinitionId & + signalInjectionSum$injectedOutcomes != 0]) +negativeControls <- data.frame(outcomeId = negativeControlIdSubsets, + oldOutcomeId = negativeControlIdSubsets, + trueLogRr = 0) +data <- rbind(injectedSignals, negativeControls) +data <- merge(data, estimates[estimates$analysisId == 3, c(""outcomeId"", ""logRr"", ""seLogRr"")]) +data$trueRr <- exp(data$trueLogRr) +data$logLb <- data$logRr - (data$seLogRr * qnorm(0.975)) +data$logUb <- data$logRr + (data$seLogRr * qnorm(0.975)) +data$covered <- data$trueLogRr >= data$logLb & data$trueLogRr <= data$logUb +aggregate(covered ~ trueRr, data = data, mean) + +ingrownNail <- 139099 +data <- data[order(data$trueRr), ] +data$rr <- exp(data$logRr) +data$lb <- exp(data$logLb) +data$ub <- exp(data$logUb) +round(data[data$oldOutcomeId == ingrownNail, c(""trueRr"", ""rr"", ""lb"", ""ub"")], 2) + +########################################################################### P-value calibration # +file.copy(from = file.path(workFolder, + ""figuresAndtables"", + ""calibration"", + paste0(""negControls_a3_t"", treatmentId, ""_c"", comparatorId, "".png"")), + to = file.path(symposiumFolder, ""pCalEffectPlot.png""), + overwrite = TRUE) + +negControls <- estimates[estimates$outcomeId %in% negativeControlIds & estimates$analysisId == 3, ] +EmpiricalCalibration::plotCalibration(logRr = negControls$logRr, + seLogRr = negControls$seLogRr, + useMcmc = TRUE) +writeLines(paste0(""Adjusted negative control p < 0.05: "", mean(negControls$p < 0.05))) + +negControls <- calibrated[calibrated$analysisId == 3 & calibrated$targetId == treatmentId & calibrated$comparatorId == + comparatorId & calibrated$outcomeId %in% negativeControlIds, ] +writeLines(paste0(""Calibrated negative control p < 0.05: "", mean(negControls$calP < 0.05))) + +########################################################################### CI calibration # +file.copy(from = file.path(workFolder, + ""figuresAndtables"", + ""calibration"", + paste0(""trueAndObs_a3_t"", treatmentId, ""_c"", comparatorId, "".png"")), + to = file.path(symposiumFolder, ""trueAndObsCali.png""), + overwrite = TRUE) + +injectedSignals <- signalInjectionSum[signalInjectionSum$exposureId == row$tCohortDefinitionId, ] +injectedSignals <- data.frame(outcomeId = injectedSignals$newOutcomeId, + trueLogRr = log(injectedSignals$targetEffectSize)) +negativeControlIdSubsets <- unique(signalInjectionSum$outcomeId[signalInjectionSum$exposureId == row$tCohortDefinitionId & + signalInjectionSum$injectedOutcomes != 0]) +negativeControls <- data.frame(outcomeId = negativeControlIdSubsets, trueLogRr = 0) +data <- rbind(injectedSignals, negativeControls) +data <- merge(data, + calibrated[calibrated$analysisId == 3 & calibrated$targetId == treatmentId & calibrated$comparatorId == + comparatorId, c(""outcomeId"", ""calRr"", ""calCi95lb"", ""calCi95ub"", ""logRr"", ""seLogRr"")]) +data$trueRr <- exp(data$trueLogRr) +data$covered <- data$trueRr >= data$calCi95lb & data$trueRr <= data$calCi95ub +aggregate(covered ~ trueRr, data = data, mean) + +ingrownNail <- 139099 +data[data$outcomeId == ingrownNail, ] + +model <- EmpiricalCalibration::fitSystematicErrorModel(data$logRr, data$seLogRr, log(data$trueRr)) + + +########################################################################### Get estimate for stroke # +estimate <- calibrated[calibrated$analysisId == 3 & calibrated$targetId == treatmentId & calibrated$comparatorId == + comparatorId & calibrated$outcomeId == 2559, ] +print(estimate) + +# Get estimates across databases +dbs <- c(""CCAE"", ""MDCD"", ""MDCR"", ""Optum"") +calibrated <- data.frame() +for (db in dbs) { + temp <- read.csv(paste0(""R:/PopEstDepression_"", db, ""/calibratedEstimates.csv"")) + temp$db <- db + calibrated <- rbind(calibrated, temp) +} +estimate <- calibrated[calibrated$analysisId == 3 & calibrated$targetId == treatmentId & calibrated$comparatorId == + comparatorId & calibrated$outcomeId == 2559, ] +print(estimate) +d1 <- data.frame(logRr = estimate$logRr, + seLogRr = estimate$seLogRr, + database = estimate$db, + type = ""Uncalibrated"") +d2 <- data.frame(logRr = estimate$calLogRr, + seLogRr = estimate$calSeLogRr, + database = estimate$db, + type = ""Calibrated"") + +d <- rbind(d1, d2) +d$logLb95Rr <- d$logRr + qnorm(0.025) * d$seLogRr +d$logUb95Rr <- d$logRr + qnorm(0.975) * d$seLogRr +d$significant <- d$logLb95Rr > 0 | d$logUb95Rr < 0 + +breaks <- c(0.25, 0.5, 1, 2, 4, 6, 8, 10) +theme <- ggplot2::element_text(colour = ""#000000"", size = 9) +themeRA <- ggplot2::element_text(colour = ""#000000"", size = 9, hjust = 1) +col <- c(rgb(0, 0, 0.8, alpha = 1), rgb(0.8, 0.4, 0, alpha = 1)) +colFill <- c(rgb(0, 0, 1, alpha = 0.5), rgb(1, 0.4, 0, alpha = 0.5)) +d$database <- as.factor(d$database) +d$database <- factor(d$database, levels = rev(levels(d$database))) +ggplot2::ggplot(d, + ggplot2::aes(x = database, + y = exp(logRr), + ymin = exp(logLb95Rr), + ymax = exp(logUb95Rr), + colour = significant, + fill = significant), + environment = environment()) + ggplot2::geom_hline(yintercept = breaks, + colour = ""#AAAAAA"", + lty = 1, + size = 0.2) + ggplot2::geom_hline(yintercept = 1, size = 0.5) + ggplot2::geom_pointrange(shape = 23, size = 0.5) + ggplot2::scale_colour_manual(values = col) + ggplot2::scale_fill_manual(values = colFill) + ggplot2::coord_flip(ylim = c(0.25, 10)) + ggplot2::scale_y_continuous(""Hazard ratio"", trans = ""log10"", breaks = breaks, labels = breaks) + ggplot2::facet_grid(~type) + ggplot2::theme(panel.grid.minor = ggplot2::element_blank(), panel.background = ggplot2::element_rect(fill = ""#FAFAFA"", colour = NA), panel.grid.major = ggplot2::element_line(colour = ""#EEEEEE""), axis.ticks = ggplot2::element_blank(), axis.title.y = ggplot2::element_blank(), axis.title.x = ggplot2::element_blank(), axis.text.y = themeRA, axis.text.x = theme, legend.key = ggplot2::element_blank(), strip.text.x = theme, strip.background = ggplot2::element_blank(), legend.position = ""none"") + +ggplot2::ggsave(filename = file.path(symposiumFolder, + ""stroke4Db.png""), width = 5, height = 1.5, dpi = 300) + +########################################################################### Get estimate for all outcomes # + +pathToCsv <- system.file(""settings"", ""OutcomesOfInterest.csv"", package = ""LargeScalePopEst"") +outcomes <- read.csv(pathToCsv) +dbs <- c(""CCAE"", ""MDCD"", ""MDCR"", ""Optum"") +calibrated <- data.frame() +for (db in dbs) { + temp <- read.csv(paste0(""R:/PopEstDepression_"", db, ""/calibratedEstimates.csv"")) + temp$db <- db + calibrated <- rbind(calibrated, temp) +} + +estimate <- calibrated[calibrated$analysisId == 3 & calibrated$targetId == treatmentId & calibrated$comparatorId == + comparatorId & calibrated$outcomeId %in% outcomes$cohortDefinitionId, ] +estimate <- merge(estimate, outcomes, by.x = ""outcomeId"", by.y = ""cohortDefinitionId"") +# d1 <- data.frame(logRr = estimate$logRr, seLogRr = estimate$seLogRr, database = estimate$db, +# outcome = estimate$name, type = 'Uncalibrated') +d2 <- data.frame(logRr = estimate$calLogRr, + seLogRr = estimate$calSeLogRr, + database = estimate$db, + outcome = estimate$name, + type = ""Calibrated"") + +# d <- rbind(d1, d2) +d <- d2 +alpha <- 0.05/22 +d$logLb95Rr <- d$logRr + qnorm(alpha/2) * d$seLogRr +d$logUb95Rr <- d$logRr + qnorm(1 - (alpha/2)) * d$seLogRr +d$significant <- d$logLb95Rr > 0 | d$logUb95Rr < 0 + +breaks <- c(0.25, 0.5, 1, 2, 4, 6, 8, 10) +theme <- ggplot2::element_text(colour = ""#000000"", size = 9) +themeRA <- ggplot2::element_text(colour = ""#000000"", size = 9, hjust = 1) +col <- c(rgb(0, 0, 0.8, alpha = 1), rgb(0.8, 0.4, 0, alpha = 1)) +colFill <- c(rgb(0, 0, 1, alpha = 0.5), rgb(1, 0.4, 0, alpha = 0.5)) +d$database <- as.factor(d$database) +d$database <- factor(d$database, levels = rev(levels(d$database))) +d$outcome <- as.character(d$outcome) +d$outcome[d$outcome == ""Ventricular arrhythmia and sudden cardiac death""] <- ""Vent. arr. & SCD"" +d$outcome[d$outcome == ""Suicide and suicidal ideation""] <- ""Suicide & SI"" +d$outcome[d$outcome == ""Gastrointestinal hemhorrage""] <- ""GI hemhorrage"" +d$outcome[d$outcome == ""Acute liver injury""] <- ""ALI"" +d$outcome[d$outcome == ""Acute myocardial infarction""] <- ""Acute MI"" +d$outcome[d$outcome == ""Open-angle glaucoma""] <- ""OA glaucoma"" +d$outcome <- as.factor(d$outcome) +d$outcome <- factor(d$outcome, levels = rev(levels(d$outcome))) + +ggplot2::ggplot(d[as.numeric(d$outcome) <= 11, + ], + ggplot2::aes(x = database, + y = exp(logRr), + ymin = exp(logLb95Rr), + ymax = exp(logUb95Rr), + colour = significant, + fill = significant), + environment = environment()) + ggplot2::geom_hline(yintercept = breaks, + colour = ""#AAAAAA"", + lty = 1, + size = 0.2) + ggplot2::geom_hline(yintercept = 1, size = 0.5) + ggplot2::geom_pointrange(shape = 23, size = 0.5) + ggplot2::scale_colour_manual(values = col) + ggplot2::scale_fill_manual(values = colFill) + ggplot2::coord_flip(ylim = c(0.25, 10)) + ggplot2::scale_y_continuous(""Hazard ratio"", trans = ""log10"", breaks = breaks, labels = breaks) + ggplot2::facet_grid(outcome ~ type) + ggplot2::theme(panel.grid.minor = ggplot2::element_blank(), panel.background = ggplot2::element_rect(fill = ""#FAFAFA"", colour = NA), panel.grid.major = ggplot2::element_line(colour = ""#EEEEEE""), axis.ticks = ggplot2::element_blank(), axis.title.y = ggplot2::element_blank(), axis.title.x = ggplot2::element_blank(), axis.text.y = themeRA, axis.text.x = theme, legend.key = ggplot2::element_blank(), strip.text.x = theme, strip.background = ggplot2::element_blank(), legend.position = ""none"", strip.text.y = element_text(size = 9, angle = 0, hjust = 0)) + +ggplot2::ggsave(filename = file.path(symposiumFolder, + ""1st11Hois4Db.png""), width = 4.5, height = 6, dpi = 300) + +ggplot2::ggplot(d[as.numeric(d$outcome) > 11, + ], + ggplot2::aes(x = database, + y = exp(logRr), + ymin = exp(logLb95Rr), + ymax = exp(logUb95Rr), + colour = significant, + fill = significant), + environment = environment()) + ggplot2::geom_hline(yintercept = breaks, + colour = ""#AAAAAA"", + lty = 1, + size = 0.2) + ggplot2::geom_hline(yintercept = 1, size = 0.5) + ggplot2::geom_pointrange(shape = 23, size = 0.5) + ggplot2::scale_colour_manual(values = col) + ggplot2::scale_fill_manual(values = colFill) + ggplot2::coord_flip(ylim = c(0.25, 10)) + ggplot2::scale_y_continuous(""Hazard ratio"", trans = ""log10"", breaks = breaks, labels = breaks) + ggplot2::facet_grid(outcome ~ type) + ggplot2::theme(panel.grid.minor = ggplot2::element_blank(), panel.background = ggplot2::element_rect(fill = ""#FAFAFA"", colour = NA), panel.grid.major = ggplot2::element_line(colour = ""#EEEEEE""), axis.ticks = ggplot2::element_blank(), axis.title.y = ggplot2::element_blank(), axis.title.x = ggplot2::element_blank(), axis.text.y = themeRA, axis.text.x = theme, legend.key = ggplot2::element_blank(), strip.text.x = theme, strip.background = ggplot2::element_blank(), legend.position = ""none"", strip.text.y = element_text(size = 9, angle = 0, hjust = 0)) + +ggplot2::ggsave(filename = file.path(symposiumFolder, + ""2nd11Hois4Db.png""), width = 4.5, height = 6, dpi = 300) + +########################################################################### Create big plot with all estimates # +dbs <- c(""CCAE"", ""MDCD"", ""MDCR"", ""Optum"") +dbs <- c(""MDCD"", ""MDCR"") +calibrated <- data.frame() +for (db in dbs) { + temp <- read.csv(paste0(""R:/PopEstDepression_"", db, ""/calibratedEstimates.csv"")) + temp$db <- db + calibrated <- rbind(calibrated, temp) +} +pathToCsv <- system.file(""settings"", ""OutcomesOfInterest.csv"", package = ""LargeScalePopEst"") +outcomes <- read.csv(pathToCsv) + + +est <- calibrated[calibrated$analysisId == 3 & calibrated$outcomeId %in% outcomes$cohortDefinitionId, ] +require(ggplot2) +breaks <- c(0.25, 0.5, 1, 2, 4, 6, 8, 10) +theme <- element_text(colour = ""#000000"", size = 12) +themeRA <- element_text(colour = ""#000000"", size = 12, hjust = 1) +themeLA <- element_text(colour = ""#000000"", size = 12, hjust = 0) +ggplot(est, aes(x = calLogRr, + y = calSeLogRr), environment = environment()) + geom_vline(xintercept = log(breaks), + colour = ""#AAAAAA"", + lty = 1, + size = 0.5) + geom_abline(slope = 1/qnorm(0.025), + colour = rgb(0.8, 0, 0), + linetype = ""dashed"", + size = 1, + alpha = 0.5) + geom_abline(slope = 1/qnorm(0.975), colour = rgb(0.8, 0, 0), linetype = ""dashed"", size = 1, alpha = 0.5) + geom_point(size = 1, alpha = 0.2, color = rgb(0, 0, 0, alpha = 0.2), shape = 16) + geom_hline(yintercept = 0) + scale_x_continuous(""Effect size"", limits = log(c(0.25, 10)), breaks = log(breaks), labels = breaks) + scale_y_continuous(""Standard Error"", limits = c(0, 1)) + theme(panel.grid.minor = element_blank(), panel.background = element_rect(fill = ""#FAFAFA"", colour = NA), panel.grid.major = element_blank(), axis.ticks = element_blank(), axis.text.y = themeRA, axis.text.x = theme, legend.key = element_blank(), strip.text.x = theme, strip.background = element_blank(), legend.position = ""none"") +ggsave(file.path(symposiumFolder, ""All.png""), width = 8, height = 5, dpi = 500) +nrow(est) +est <- est[!is.na(est$calSeLogRr), ] +mean(est$calCi95lb > 1 | est$calCi95ub < 1) +mean(est$calP < 0.05) + +########################################################################### Highlight two example # +set.seed(0) +workFolders <- c(""R:/PopEstDepression_Mdcr"", ""R:/PopEstDepression_Mdcd"") +temp <- read.csv(file.path(workFolders[1], ""exposureSummaryFilteredBySize.csv"")) +rnd <- est[sample.int(nrow(temp), 2), ] +rnd <- data.frame(tprimeCohortDefinitionId = c(755695129, 725131097), + cprimeCohortDefinitionId = c(4327941129, 797617097), + outcomeId = c(2820, 2826)) # suicide ideation, constipation + +merge(rnd, exposureSummary)[, c(""tCohortDefinitionName"", ""cCohortDefinitionName"")] + +for (i in 1:length(rnd)) { + print(paste(""Target: "", + exposureSummary$tCohortDefinitionName[exposureSummary$tprimeCohortDefinitionId == + rnd$tprimeCohortDefinitionId[i]])) + print(paste(""Comparator: "", + exposureSummary$cCohortDefinitionName[exposureSummary$cprimeCohortDefinitionId == + rnd$cprimeCohortDefinitionId[i]])) + treatmentId <- rnd$tprimeCohortDefinitionId[i] + comparatorId <- rnd$cprimeCohortDefinitionId[i] + outcomeId <- rnd$outcomeId[i] + file.copy(from = file.path(workFolders[i], + ""figuresAndtables"", + ""ps"", + paste0(""ps_t"", treatmentId, ""_c"", comparatorId, "".png"")), + to = file.path(symposiumFolder, paste0(""Ps_example"", i, "".png"")), + overwrite = TRUE) + + omr <- readRDS(file.path(workFolders[i], ""cmOutput"", ""outcomeModelReference.rds"")) + + cohortMethodDataFolder <- omr$cohortMethodDataFolder[outcomeModelReference$targetId == treatmentId & + outcomeModelReference$comparatorId == comparatorId & outcomeModelReference$analysisId == 3 & + outcomeModelReference$outcomeId == outcomeId] + strataFile <- outcomeModelReference$strataFile[outcomeModelReference$targetId == treatmentId & outcomeModelReference$comparatorId == + comparatorId & outcomeModelReference$analysisId == 3 & outcomeModelReference$outcomeId == outcomeId] + + cohortMethodDataFolder <- gsub(""^[sS]:"", ""R:"", cohortMethodDataFolder) + strataFile <- gsub(""^[sS]:"", ""R:"", strataFile) + + cohortMethodData <- CohortMethod::loadCohortMethodData(cohortMethodDataFolder) + strata <- readRDS(strataFile) + + balance <- CohortMethod::computeCovariateBalance(strata, cohortMethodData) + + plotFileName <- file.path(workFolder, + ""symposium"", + paste0(""balanceScatterPlot_example"", i, "".png"")) + CohortMethod::plotCovariateBalanceScatterPlot(balance, fileName = plotFileName) + + file.copy(from = file.path(workFolders[i], + ""figuresAndtables"", + ""calibration"", + paste0(""negControls_a3_t"", treatmentId, ""_c"", comparatorId, "".png"")), + to = file.path(symposiumFolder, paste0(""negControls_example"", i, "".png"")), + overwrite = TRUE) + + file.copy(from = file.path(workFolders[i], + ""figuresAndtables"", + ""controls"", + paste0(""trueAndObs_a3_t"", treatmentId, ""_c"", comparatorId, "".png"")), + to = file.path(symposiumFolder, paste0(""trueAndObs_example"", i, "".png"")), + overwrite = TRUE) + + file.copy(from = file.path(workFolders[i], + ""figuresAndtables"", + ""calibration"", + paste0(""trueAndObs_a3_t"", treatmentId, ""_c"", comparatorId, "".png"")), + to = file.path(symposiumFolder, paste0(""trueAndObsCali_example"", i, "".png"")), + overwrite = TRUE) + + temp <- read.csv(file.path(workFolders[i], ""calibratedEstimates.csv"")) + temp <- temp[temp$targetId == treatmentId & temp$comparatorId == comparatorId & temp$analysisId == + 3 & temp$outcomeId == outcomeId, c(""calRr"", ""calCi95lb"", ""calCi95ub"", ""calLogRr"", ""calSeLogRr"")] + print(temp) + + require(ggplot2) + breaks <- c(0.25, 0.5, 1, 2, 4, 6, 8, 10) + theme <- element_text(colour = ""#000000"", size = 12) + themeRA <- element_text(colour = ""#000000"", size = 12, hjust = 1) + themeLA <- element_text(colour = ""#000000"", size = 12, hjust = 0) + ggplot(est, + aes(x = calLogRr, y = calSeLogRr), + environment = environment()) + geom_vline(xintercept = log(breaks), + colour = ""#AAAAAA"", + lty = 1, + size = 0.5) + geom_abline(slope = 1/qnorm(0.025), + colour = rgb(0.8, 0, 0), + linetype = ""dashed"", + size = 1, + alpha = 0.5) + geom_abline(slope = 1/qnorm(0.975), colour = rgb(0.8, 0, 0), linetype = ""dashed"", size = 1, alpha = 0.5) + geom_point(size = 1, alpha = 0.2, color = rgb(0, 0, 0, alpha = 0.2), shape = 16) + geom_point(size = 4, fill = rgb(1, 1, 0), shape = 23, data = temp) + geom_hline(yintercept = 0) + scale_x_continuous(""Effect size"", limits = log(c(0.25, 10)), breaks = log(breaks), labels = breaks) + scale_y_continuous(""Standard Error"", limits = c(0, 1)) + theme(panel.grid.minor = element_blank(), panel.background = element_rect(fill = ""#FAFAFA"", colour = NA), panel.grid.major = element_blank(), axis.ticks = element_blank(), axis.text.y = themeRA, axis.text.x = theme, legend.key = element_blank(), strip.text.x = theme, strip.background = element_blank(), legend.position = ""none"") + ggsave(file.path(symposiumFolder, + paste0(""All_example"", i, "".png"")), width = 8, height = 5, dpi = 500) +} + +########################################################################### Overview of PS plots # +exposureSummary <- read.csv(file.path(workFolder, ""exposureSummaryFilteredBySize.csv"")) +outcomeModelReference <- readRDS(file.path(workFolder, ""cmOutput"", ""outcomeModelReference.rds"")) +datas <- list() +for (i in 1:nrow(exposureSummary)) { + treatmentId <- exposureSummary$tprimeCohortDefinitionId[i] + comparatorId <- exposureSummary$cprimeCohortDefinitionId[i] + psFileName <- outcomeModelReference$sharedPsFile[outcomeModelReference$targetId == treatmentId & + outcomeModelReference$comparatorId == comparatorId & outcomeModelReference$analysisId == 3][1] + ps <- readRDS(psFileName) + if (min(ps$propensityScore) < max(ps$propensityScore)) { + ps <- CohortMethod:::computePreferenceScore(ps) + + d1 <- density(ps$preferenceScore[ps$treatment == 1], from = 0, to = 1, n = 100) + d0 <- density(ps$preferenceScore[ps$treatment == 0], from = 0, to = 1, n = 100) + + d <- data.frame(x = c(d1$x, d0$x), y = c(d1$y, d0$y), treatment = c(rep(1, length(d1$x)), + rep(0, length(d0$x)))) + d$y <- d$y/max(d$y) + d$treatmentName <- exposureSummary$tCohortDefinitionName[i] + d$comparatorName <- exposureSummary$cCohortDefinitionName[i] + datas[[length(datas) + 1]] <- d + + d$x <- 1 - d$x + d$treatment <- 1 - d$treatment + d$treatmentName <- exposureSummary$cCohortDefinitionName[i] + d$comparatorName <- exposureSummary$tCohortDefinitionName[i] + datas[[length(datas) + 1]] <- d + } +} +data <- do.call(""rbind"", datas) +saveRDS(data, file.path(symposiumFolder, ""ps.rds"")) +# data <- ps +data$GROUP <- ""Target"" +data$GROUP[data$treatment == 0] <- ""Comparator"" +data$GROUP <- factor(data$GROUP, levels = c(""Target"", ""Comparator"")) +library(ggplot2) +ggplot(data, aes(x = x, + y = y, + color = GROUP, + group = GROUP, + fill = GROUP)) + geom_density(stat = ""identity"") + scale_fill_manual(values = c(rgb(0.8, 0, 0, alpha = 0.5), rgb(0, 0, 0.8, alpha = 0.5))) + scale_color_manual(values = c(rgb(0.8, 0, 0, alpha = 0.5), rgb(0, 0, 0.8, alpha = 0.5))) + scale_x_continuous(""Preference score"", limits = c(0, 1)) + scale_y_continuous(""Density"") + facet_grid(treatmentName ~ comparatorName) + theme(legend.title = element_blank(), axis.title.x = element_blank(), axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.title.y = element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), strip.text.y = element_text(size = 8, angle = 0), panel.margin = unit(0.1, ""lines""), legend.position = ""none"") +ggsave(filename = file.path(symposiumFolder, ""allPs.png""), width = 15, height = 9, dpi = 300) + + + + +########################################################################### Example error distribution plots # + + +require(ggplot2) +x <- seq(from = 0.25, to = 10, by = 0.01) +y <- dnorm(log(x), mean = log(1.5), sd = 0.25) +d <- data.frame(x = x, logX = log(x), y = y) + +breaks <- c(0.25, 0.5, 1, 2, 4, 6, 8, 10) +theme <- element_text(colour = ""#000000"", size = 12) +themeRA <- element_text(colour = ""#000000"", size = 12, hjust = 1) +themeLA <- element_text(colour = ""#000000"", size = 12, hjust = 0) +ggplot(d, aes(x = logX, y = y), environment = environment()) + geom_vline(xintercept = log(breaks), + colour = ""#AAAAAA"", + lty = 1, + size = 0.5) + geom_density(stat = ""identity"", + color = rgb(0, 0, 0.8), + fill = rgb(0, 0, 0.8, alpha = 0.5)) + geom_hline(yintercept = 0) + geom_vline(xintercept = 0) + scale_x_continuous(""Effect size"", limits = log(c(0.25, 10)), breaks = log(breaks), labels = breaks) + theme(panel.grid.minor = element_blank(), panel.background = element_rect(fill = ""#FAFAFA"", colour = NA), panel.grid.major = element_blank(), axis.ticks = element_blank(), axis.text.y = element_blank(), axis.title.y = element_blank(), axis.text.x = theme, legend.key = element_blank(), strip.text.x = theme, strip.background = element_blank(), legend.position = ""none"") +ggsave(file.path(symposiumFolder, ""ErrorDistExample1.png""), width = 5, height = 2, dpi = 500) + +y <- dnorm(log(x), mean = log(2.5), sd = 0.35) +d <- data.frame(x = x, logX = log(x), y = y) + +breaks <- c(0.25, 0.5, 1, 2, 4, 6, 8, 10) +theme <- element_text(colour = ""#000000"", size = 12) +themeRA <- element_text(colour = ""#000000"", size = 12, hjust = 1) +themeLA <- element_text(colour = ""#000000"", size = 12, hjust = 0) +ggplot(d, aes(x = logX, y = y), environment = environment()) + geom_vline(xintercept = log(breaks), + colour = ""#AAAAAA"", + lty = 1, + size = 0.5) + geom_density(stat = ""identity"", + color = rgb(0, 0, 0.8), + fill = rgb(0, 0, 0.8, alpha = 0.5)) + geom_hline(yintercept = 0) + geom_vline(xintercept = log(2)) + scale_x_continuous(""Effect size"", limits = log(c(0.25, 10)), breaks = log(breaks), labels = breaks) + theme(panel.grid.minor = element_blank(), panel.background = element_rect(fill = ""#FAFAFA"", colour = NA), panel.grid.major = element_blank(), axis.ticks = element_blank(), axis.text.y = element_blank(), axis.title.y = element_blank(), axis.text.x = theme, legend.key = element_blank(), strip.text.x = theme, strip.background = element_blank(), legend.position = ""none"") +ggsave(file.path(symposiumFolder, ""ErrorDistExample2.png""), width = 5, height = 2, dpi = 500) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","LargeScalePopEst/extras/TestCode.R",".R","5971","170","# @file TestCode.R +# +# Copyright 2017 Observational Health Data Sciences and Informatics +# +# This file is part of LargeScalePopEst +# +# 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. + +library(LargeScalePopEst) +options(fftempdir = ""R:/fftemp"") +# options('fftempdir' = 'S:/fftemp') +# install.packages(""C:/Users/mschuemi/Downloads/FeatureExtraction_1.0.2.tar.gz"", repos = NULL, type=""source"") +# install.packages(""C:/Users/mschuemi/Downloads/CohortMethod_2.1.1.tar.gz"", repos = NULL, type=""source"") +# install.packages(""C:/Users/mschuemi/Downloads/MethodEvaluation_0.0.4.tar.gz"", repos = NULL, type=""source"") + +pw <- NULL +dbms <- ""pdw"" +user <- NULL +server <- ""JRDUSAPSCTL01"" +cdmDatabaseSchema <- ""CDM_Truven_MDCD_V464.dbo"" +oracleTempSchema <- NULL +workDatabaseSchema <- ""scratch.dbo"" +studyCohortTable <- ""mschuemie_depression_cohorts_mdcd"" +exposureCohortSummaryTable <- ""mschuemie_depression_exposure_summary_mdcd"" +port <- 17001 +workFolder <- ""R:/PopEstDepression_Mdcd"" +# workFolder <- 'S:/PopEstDepression_Mdcd' +maxCores <- 15 + +pw <- NULL +dbms <- ""pdw"" +user <- NULL +server <- ""JRDUSAPSCTL01"" +cdmDatabaseSchema <- ""CDM_Truven_CCAE_V483.dbo"" +oracleTempSchema <- NULL +workDatabaseSchema <- ""scratch.dbo"" +studyCohortTable <- ""mschuemie_depression_cohorts_ccae"" +exposureCohortSummaryTable <- ""mschuemie_t2dm_exposure_summary_ccae"" +port <- 17001 +workFolder <- ""R:/PopEstDepression_Ccae"" +maxCores <- 30 + +pw <- NULL +dbms <- ""pdw"" +user <- NULL +server <- ""JRDUSAPSCTL01"" +cdmDatabaseSchema <- ""CDM_Truven_MDCR_V489.dbo"" +oracleTempSchema <- NULL +workDatabaseSchema <- ""scratch.dbo"" +studyCohortTable <- ""mschuemie_depression_cohorts_mdcr"" +exposureCohortSummaryTable <- ""mschuemie_t2dm_exposure_summary_mdcr"" +port <- 17001 +workFolder <- ""r:/PopEstDepression_Mdcr"" +maxCores <- 20 + +pw <- NULL +dbms <- ""pdw"" +user <- NULL +server <- ""JRDUSAPSCTL01"" +cdmDatabaseSchema <- ""cdm_optum_extended_ses_v486.dbo"" +oracleTempSchema <- NULL +workDatabaseSchema <- ""scratch.dbo"" +studyCohortTable <- ""mschuemie_depression_cohorts_optum"" +exposureCohortSummaryTable <- ""mschuemie_t2dm_exposure_summary_optum"" +port <- 17001 +workFolder <- ""r:/PopEstDepression_Optum"" +maxCores <- 20 + +connectionDetails <- DatabaseConnector::createConnectionDetails(dbms = dbms, + server = server, + user = user, + password = pw, + port = port) + +execute(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + workDatabaseSchema = workDatabaseSchema, + studyCohortTable = studyCohortTable, + exposureCohortSummaryTable = exposureCohortSummaryTable, + workFolder = workFolder, + maxCores = maxCores, + createCohorts = FALSE, + fetchAllDataFromServer = FALSE, + injectSignals = FALSE, + generateAllCohortMethodDataObjects = FALSE, + runCohortMethod = TRUE) + +workFolder <- ""R:/PopEstDepression_Mdcd"" +calibrateEstimatesAndPvalues(workFolder) +workFolder <- ""R:/PopEstDepression_Ccae"" +calibrateEstimatesAndPvalues(workFolder) +workFolder <- ""R:/PopEstDepression_Mdcr"" +calibrateEstimatesAndPvalues(workFolder) +workFolder <- ""R:/PopEstDepression_Optum"" +calibrateEstimatesAndPvalues(workFolder) + +analysePsDistributions(workFolder) + +plotControlDistributions(workFolder) + +calibrateEstimatesAndPvalues(workFolder) + +createCohorts(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + workDatabaseSchema = workDatabaseSchema, + studyCohortTable = studyCohortTable, + exposureCohortSummaryTable = exposureCohortSummaryTable, + workFolder = workFolder) + +filterByExposureCohortsSize(workFolder = workFolder) + +fetchAllDataFromServer(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + workDatabaseSchema = workDatabaseSchema, + studyCohortTable = studyCohortTable, + workFolder = workFolder) + +injectSignals(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + workDatabaseSchema = workDatabaseSchema, + studyCohortTable = studyCohortTable, + oracleTempSchema = oracleTempSchema, + workFolder = workFolder, + maxCores = maxCores) + +generateAllCohortMethodDataObjects(workFolder) + +runCohortMethod(workFolder, maxCores = maxCores) + +analysePsDistributions(workFolder) + +CohortMethod::plotPs(ps) + + +eq <- read.csv(file.path(figuresAndTablesFolder, ""Equipoise.csv""), stringsAsFactors = FALSE) +names <- unique(c(eq$cohortName1, eq$cohortName2)) +names <- names[order(names)] +m <- combn(names, 2) +m <- data.frame(cohortName1 = m[1, ], cohortName2 = m[2, ]) +m <- merge(m, eq[, c(""cohortName1"", ""cohortName2"", ""equipoise"")], all.x = TRUE) + + +m$equipoise[is.na(m$equipoise)] <- 0 +m <- m[order(m$cohortName1, m$cohortName2), ] +d1 <- 1 - m$equipoise +attr(d1, ""Size"") <- length(names) +attr(d1, ""Labels"") <- names +attr(d1, ""Diag"") <- FALSE +attr(d1, ""Upper"") <- TRUE +attr(d1, ""method"") <- ""binary"" +class(d1) <- ""dist"" + +hc <- hclust(d1) +png(""s:/temp/dendo.png"") +plot(hc) +dev.off() +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","LargeScalePopEst/extras/DataForShiny.R",".R","9748","214","dataFolder <- ""S:/Temp/ShinyApp/data"" + +# Some-by-some data ------------------------------------------------------- + +calibrated <- read.csv(""r:/DepressionResults.csv"") + +normName <- function(name) { + return(gsub("" "", ""_"", tolower(name))) +} + +# Full data overview: +d <- calibrated[calibrated$analysisId == 3, ] +fullSet <- d[d$outcomeType == ""hoi"", c(""targetName"", ""comparatorName"", ""outcomeName"", ""db"", ""calLogRr"", ""calSeLogRr"", ""calRr"", ""calCi95lb"", ""calCi95ub"")] +colnames(fullSet)[colnames(fullSet) == ""calLogRr""] <- ""logRr"" +colnames(fullSet)[colnames(fullSet) == ""calSeLogRr""] <- ""seLogRr"" +colnames(fullSet)[colnames(fullSet) == ""calRr""] <- ""rr"" +colnames(fullSet)[colnames(fullSet) == ""calCi95lb""] <- ""ci95lb"" +colnames(fullSet)[colnames(fullSet) == ""calCi95ub""] <- ""ci95ub"" +saveRDS(fullSet, file.path(dataFolder, normName(""fullset.rds""))) + +# Data per target-comparator: +tcs <- unique(d[, c(""targetId"", ""comparatorId"")]) +for (i in 1:nrow(tcs)) { + tc <- tcs[i,] + + # Main analysis: + subset <- d[d$targetId == tc$targetId & d$comparatorId == tc$comparatorId & d$outcomeType == ""hoi"", ] + targetName <- subset$targetName[1] + comparatorName <- subset$comparatorName[1] + subset$targetName <- NULL + subset$targetId <- NULL + subset$comparatorName <- NULL + subset$outcomeId <- NULL + subset$comparatorId <- NULL + subset$analysisId <- NULL + subset$outcomeType <- NULL + subset$trueRr <- NULL + fileName <- file.path(dataFolder, normName(paste0(""est_"", targetName, ""_"", comparatorName, "".rds""))) + saveRDS(subset, normName(fileName)) + + # Sensitivity analysis: + subset <- calibrated[calibrated$analysisId == 4 & calibrated$targetId == tc$targetId & calibrated$comparatorId == tc$comparatorId & calibrated$outcomeType == ""hoi"", ] + targetName <- subset$targetName[1] + comparatorName <- subset$comparatorName[1] + subset$targetName <- NULL + subset$targetId <- NULL + subset$comparatorName <- NULL + subset$outcomeId <- NULL + subset$comparatorId <- NULL + subset$analysisId <- NULL + subset$outcomeType <- NULL + subset$trueRr <- NULL + fileName <- file.path(dataFolder, normName(paste0(""sens_"", targetName, ""_"", comparatorName, "".rds""))) + saveRDS(subset, normName(fileName)) +} + +# Data per target-comparator-database: +source(""extras/SharedPlots.R"") +dbs <- unique(d$db) +for (db in dbs) { + omr <- readRDS(file.path(paste0(""R:/PopEstDepression_"", db), ""cmOutput"", ""outcomeModelReference.rds"")) + omr <- omr[omr$analysisId == 3, ] + tcs <- unique(d[d$db == db, c(""targetId"", ""targetName"", ""comparatorId"", ""comparatorName"")]) + omr <- merge(omr, tcs) + tcs <- unique(omr[, c(""targetId"", ""targetName"", ""comparatorId"", ""comparatorName"")]) + for (i in 1:nrow(tcs)) { + tc <- tcs[i,] + + omrRow <- omr[omr$targetId == tc$targetId & omr$comparatorId == tc$comparatorId,] + + tcData <- list() + ctData <- list() + + ### PS plot ### + psFile <- omrRow$sharedPsFile[1] + psFile <- sub(""^[sS]:/"", ""r:/"", psFile) + ps <- readRDS(psFile) + if (min(ps$propensityScore) < max(ps$propensityScore)) { + ps <- CohortMethod:::computePreferenceScore(ps) + + d1 <- density(ps$preferenceScore[ps$treatment == 1], from = 0, to = 1, n = 100) + d0 <- density(ps$preferenceScore[ps$treatment == 0], from = 0, to = 1, n = 100) + + ps <- data.frame(x = c(d1$x, d0$x), y = c(d1$y, d0$y), treatment = c(rep(1, length(d1$x)), + rep(0, length(d0$x)))) + tcData$ps <- ps + + ps$x <- 1 - ps$x + ps$treatment <- 1 - ps$treatment + ctData$ps <- ps + } + + ### Evalutuation distributions ### + controls <- d[d$targetId == tc$targetId & d$comparatorId == tc$comparatorId & d$db == db & !is.na(d$trueRr), ] + controls <- data.frame(trueRr = controls$trueRr, + logRr = controls$logRr, + ci95lb = controls$ci95lb, + ci95ub = controls$ci95ub, + seLogRr = controls$seLogRr) + tcData$evaluationPlot <- plotScatter(controls, size = 2) + + controls <- d[d$targetId == tc$comparatorId & d$comparatorId == tc$targetId & d$db == db & !is.na(d$trueRr), ] + controls <- data.frame(trueRr = controls$trueRr, + logRr = controls$logRr, + ci95lb = controls$ci95lb, + ci95ub = controls$ci95ub, + seLogRr = controls$seLogRr) + ctData$evaluationPlot <- plotScatter(controls, size = 2) + + ### Calibration distribution ### + controls <- d[d$targetId == tc$targetId & d$comparatorId == tc$comparatorId & d$db == db & !is.na(d$trueRr), ] + controls <- data.frame(trueRr = controls$trueRr, + logRr = controls$calLogRr, + ci95lb = controls$calCi95lb, + ci95ub = controls$calCi95ub, + seLogRr = controls$calSeLogRr) + tcData$calibrationPlot <- plotScatter(controls, size = 2) + + controls <- d[d$targetId == tc$comparatorId & d$comparatorId == tc$targetId & d$db == db & !is.na(d$trueRr), ] + controls <- data.frame(trueRr = controls$trueRr, + logRr = controls$calLogRr, + ci95lb = controls$calCi95lb, + ci95ub = controls$calCi95ub, + seLogRr = controls$calSeLogRr) + ctData$calibrationPlot <- plotScatter(controls, size = 2) + + ### Save to file ### + fileName <- file.path(dataFolder, paste0(""details_"", tc$targetName, ""_"", tc$comparatorName, ""_"", db, "".rds"")) + saveRDS(tcData, normName(fileName)) + fileName <- file.path(dataFolder, paste0(""details_"", tc$comparatorName, ""_"", tc$targetName, ""_"", db, "".rds"")) + saveRDS(ctData, normName(fileName)) + } +} + +### Balance files (saved separately because they're big) +library(OhdsiRTools) +library(CohortMethod) +options(fftempdir = ""R:/fftemp"") +dbs <- unique(d$db) +for (db in dbs) { + omr <- readRDS(file.path(paste0(""R:/PopEstDepression_"", db), ""cmOutput"", ""outcomeModelReference.rds"")) + omr <- omr[omr$analysisId == 3, ] + tcs <- unique(d[d$db == db, c(""targetId"", ""targetName"", ""comparatorId"", ""comparatorName"")]) + omr <- merge(omr, tcs) + tcs <- unique(omr[, c(""targetId"", ""targetName"", ""comparatorId"", ""comparatorName"")]) + + fun <- function(i, tcs, db, omr, dataFolder){ + tc <- tcs[i,] + omrRow <- omr[omr$targetId == tc$targetId & omr$comparatorId == tc$comparatorId,] + + normName <- function(name) { + return(gsub("" "", ""_"", tolower(name))) + } + tcFileName <- normName(file.path(dataFolder, paste0(""balance_"", tc$targetName, ""_"", tc$comparatorName, ""_"", db, "".rds""))) + if (file.exists(tcFileName)) { + return(NULL) + } + writeLines(paste0(""Computing balance for "", tc$targetName, "" and "", tc$comparatorName)) + ### Balance ### + cohortMethodDataFolder <- omrRow$cohortMethodDataFolder[1] + cohortMethodDataFolder <- sub(""^[sS]:/"", ""r:/"", cohortMethodDataFolder) + cmData <- CohortMethod::loadCohortMethodData(cohortMethodDataFolder) + strataFile <- omrRow$strataFile[1] + strataFile <- sub(""^[sS]:/"", ""r:/"", strataFile) + strata <- readRDS(strataFile) + balance <- CohortMethod::computeCovariateBalance(strata, cmData) + balance <- balance[, c(""beforeMatchingStdDiff"", ""afterMatchingStdDiff"", ""covariateName"")] + saveRDS(balance, tcFileName) + } + cluster <- makeCluster(8) + clusterRequire(cluster, ""CohortMethod"") + clusterApply(cluster, 1:nrow(tcs), fun, tcs = tcs, db = db, omr = omr, dataFolder = dataFolder) + #clusterApply(cluster, 1:3, fun, tcs = tcs, db = db, omr = omr, dataFolder = dataFolder) + OhdsiRTools::stopCluster(cluster) +} + +# Literature data --------------------------------------------------------- + +litData <- read.csv(""C:/home/Research/PublicationBias/AnalysisJitter.csv"") + +### Full data overview ### +seFromCI <- (log(litData$EffectEstimate_jitter)-log(litData$CI.LB_jitter))/qnorm(0.975) +seFromP <- abs(log(litData$EffectEstimate_jitter)/qnorm(litData$P.value_jitter)) +litData$seLogRr <- seFromCI +litData$seLogRr[is.na(litData$seLogRr)] <- seFromP[is.na(litData$seLogRr)] +litData <- litData[!is.na(litData$seLogRr), ] +litData <- litData[litData$EffectEstimate_jitter > 0, ] +litData$logRr <- log(litData$EffectEstimate_jitter) +fullSet <- litData[, c(""PMID"", ""Year"", ""Depression"", ""EffectEstimate"", ""CI.LB"", ""CI.UB"", ""P.value"", ""logRr"", ""seLogRr"", ""StartPos"", ""EndPos"", ""Title"")] +#fullSet$Depression <- as.logical(fullSet$Depression) +fullSet$Depression <- as.logical(litData$DepressionTreatment) +colnames(fullSet)[colnames(fullSet) == ""EffectEstimate""] <- ""rr"" +colnames(fullSet)[colnames(fullSet) == ""CI.LB""] <- ""ci95lb"" +colnames(fullSet)[colnames(fullSet) == ""CI.UB""] <- ""ci95ub"" +saveRDS(fullSet, file.path(dataFolder, ""fullSetLit.rds"")) + +### Abstracts ### +pmids <- unique(litData$PMID) +hashes <- pmids %% 1000 +readAbstract <- function(pmid) { + fileName <- file.path(""r:/abstracts"", paste0(""pmid_"", pmid, "".txt"")) + return(readLines(fileName, encoding = ""UTF-8"")) +} +createFile <- function(hash, hashes, pmids) { + subset <- pmids[hashes == hash] + contents <- lapply(subset, readAbstract) + names(contents) <- subset + fileName <- file.path(dataFolder, paste0(""pmids_ending_with_"", hash, "".rds"")) + saveRDS(contents, fileName) +} +dummy <- sapply(unique(hashes), createFile, hashes = hashes, pmids = pmids) + + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","LargeScalePopEst/extras/PlotsForPaper.R",".R","46284","1015","workFolder <- ""R:/PopEstDepression_Ccae"" + +paperFolder <- ""R:/SomeBySomePaper"" +if (!file.exists(paperFolder)) { + dir.create(paperFolder) +} + +# Plot evaluation --------------------------------------------------------- +calibrated <- read.csv(""r:/DepressionResults.csv"") + +source(""extras/SharedPlots.R"") +d <- calibrated[calibrated$analysisId == 3 & !is.na(calibrated$trueRr), ] +d <- data.frame(trueRr = d$trueRr, + logRr = d$logRr, + ci95lb = d$ci95lb, + ci95ub = d$ci95ub, + seLogRr = d$seLogRr) +plotScatter(d, size = 0.5) +ggsave(file.path(paperFolder, ""Eval.png""), width = 13.5, height = 3, dpi = 500) + + + +# Plot calibration -------------------------------------------------------- + +calibrated <- read.csv(""r:/DepressionResults.csv"") + +source(""extras/SharedPlots.R"") +d <- calibrated[calibrated$analysisId == 3 & !is.na(calibrated$trueRr), ] +d <- data.frame(trueRr = d$trueRr, + logRr = d$calLogRr, + ci95lb = d$calCi95lb, + ci95ub = d$calCi95ub, + seLogRr = d$calSeLogRr) +plotScatter(d) +ggsave(file.path(paperFolder, ""EvalCal.png""), width = 13.5, height = 3, dpi = 500) + + +# Plot evaluation and calibration as one plot ----------------------------- +calibrated <- read.csv(""r:/DepressionResults.csv"") + +source(""extras/SharedPlots.R"") +d <- calibrated[calibrated$analysisId == 3 & !is.na(calibrated$trueRr), ] +d1 <- data.frame(trueRr = d$trueRr, + logRr = d$logRr, + ci95lb = d$ci95lb, + ci95ub = d$ci95ub, + seLogRr = d$seLogRr, + yGroup = ""Uncalibrated"") + +d2 <- data.frame(trueRr = d$trueRr, + logRr = d$calLogRr, + ci95lb = d$calCi95lb, + ci95ub = d$calCi95ub, + seLogRr = d$calSeLogRr, + yGroup = ""Calibrated"") +d <- rbind(d1, d2) +d$yGroup <- factor(d$yGroup, levels = c(""Uncalibrated"", ""Calibrated"")) +plotScatter(d, yPanelGroup = TRUE, size = 0.5) + +ggsave(file.path(paperFolder, ""EvalCalCombined.png""), width = 14.5, height = 4.5, dpi = 500) + + + +# Plot results for literature and our depression study --------------------------------------------- + +library(ggplot2) +calibrated <- read.csv(""r:/DepressionResults.csv"") +d1 <- calibrated[calibrated$analysisId == 3 & calibrated$outcomeType == ""hoi"", ] +d1$Significant <- d1$calCi95lb > 1 | d1$calCi95ub < 1 + +d2 <- read.csv(""C:/home/Research/PublicationBias/AnalysisJitter.csv"") +d2$Significant <- !(is.na(d2$P.value) | d2$P.value >= 0.05) | !(is.na(d2$CI.LB) | (d2$CI.LB <= 1 & d2$CI.UB >= 1)) +seFromCI <- (log(d2$EffectEstimate_jitter)-log(d2$CI.LB_jitter))/qnorm(0.975) +seFromP <- abs(log(d2$EffectEstimate_jitter)/qnorm(d2$P.value_jitter)) +d2$seLogRr <- seFromCI +d2$seLogRr[is.na(d2$seLogRr)] <- seFromP[is.na(d2$seLogRr)] +d2 <- d2[!is.na(d2$seLogRr), ] +d2 <- d2[d2$EffectEstimate_jitter > 0, ] +#d3 <- d2[d2$Depression == 1, ] +d3 <- d2[d2$DepressionTreatment == 1, ] + +pmids <- read.csv(""C:/home/Research/PublicationBias/Pmids_main.txt"") +writeLines(paste(""Total number of hits on query: "", nrow(pmids))) + +writeLines(paste(""Total number of estimates: "", nrow(d2))) +writeLines(paste(""Total number of abstracts: "", length(unique(d2$PMID)))) + +writeLines(paste(""Total estimates for our results: "", nrow(d1))) +writeLines(paste(""Total estimates significant for our results: "", sum(d1$Significant, na.rm = TRUE))) +writeLines(paste(""Total significant expected when null is true for all: "", nrow(d1)*0.05)) + +d <- rbind(data.frame(logRr = d1$calLogRr, + seLogRr = d1$calSeLogRr, + Group = ""C\nOur large-scale study on depression treatments"", + Significant = d1$Significant, + dummy = 1), + data.frame(logRr = log(d2$EffectEstimate_jitter), + seLogRr = d2$seLogRr, + Group = ""A\nAll observational literature"", + Significant = d2$Significant, + dummy = 1), + data.frame(logRr = log(d3$EffectEstimate_jitter), + seLogRr = d3$seLogRr, + Group = ""B\nObservational literature on depression treatments"", + Significant = d3$Significant, + dummy = 1)) + +d$Group <- factor(d$Group, levels = c(""A\nAll observational literature"", ""B\nObservational literature on depression treatments"", ""C\nOur large-scale study on depression treatments"")) + +temp1 <- aggregate(dummy ~ Group, data = d, length) +temp1$nLabel <- paste0(formatC(temp1$dummy, big.mark = "",""), "" estimates"") +temp1$dummy <- NULL +temp2 <- aggregate(Significant ~ Group, data = d, mean) +temp2$meanLabel <- paste0(formatC(100 * (1-temp2$Significant), digits = 1, format = ""f""), ""% of CIs include 1"") +temp2$Significant <- NULL +dd <- merge(temp1, temp2) + +#breaks <- c(0.25, 0.5, 1, 2, 4, 6, 8, 10) +breaks <- c(0.1, 0.25, 0.5, 1, 2, 4, 6, 8, 10) +theme <- element_text(colour = ""#000000"", size = 12) +themeRA <- element_text(colour = ""#000000"", size = 12, hjust = 1) +themeLA <- element_text(colour = ""#000000"", size = 12, hjust = 0) + +# One plot +plot <- ggplot(d, aes(x=logRr, y=seLogRr, alpha = Group), environment=environment())+ + geom_vline(xintercept=log(breaks), colour =""#AAAAAA"", lty=1, size=0.5) + + geom_abline(slope = 1/qnorm(0.025), colour=rgb(0.8,0,0), linetype=""dashed"", size=1,alpha=0.5) + + geom_abline(slope = 1/qnorm(0.975), colour=rgb(0.8,0,0), linetype=""dashed"", size=1,alpha=0.5) + + geom_point(size=0.5, color = rgb(0,0,0), shape = 16) + + geom_hline(yintercept=0) + + geom_label(x = log(0.11), y = 0.99, alpha = 1, hjust = ""left"", aes(label = nLabel), size = 5, data = dd) + + geom_label(x = log(0.11), y = 0.88, alpha = 1, hjust = ""left"", aes(label = meanLabel), size = 5, data = dd) + + scale_x_continuous(""Effect size"",limits = log(c(0.1,10)), breaks=log(breaks),labels=breaks) + + scale_y_continuous(""Standard Error"",limits = c(0,1)) + + scale_alpha_manual(values = c(0.1, 0.8, 0.2)) + + facet_grid(.~Group) + + theme( + panel.grid.minor = element_blank(), + panel.background= element_blank(), + panel.grid.major= element_blank(), + axis.ticks = element_blank(), + axis.text.y = themeRA, + axis.text.x = theme, + legend.key= element_blank(), + strip.text.x = theme, + strip.text.y = theme, + strip.background = element_blank(), + legend.position = ""none"" + ) +ggsave(plot = plot, file.path(paperFolder, ""LitVsUs.png""), width = 15, height = 3.5, dpi = 500) + +# Two plots +subset <- c(""A\nAll observational literature"", ""B\nObservational literature on depression treatments"") +alpha <- c(0.1, 0.8) +size <- 0.5 +labelY <- 0.85 + +subset <- c(""C\nOur large-scale study on depression treatments"") +alpha <- c(0.2) +size <- 1 +labelY <- 0.92 +n <- nrow(d[d$Group %in% subset, ]) +plot <- ggplot(d[d$Group %in% subset, ], aes(x=logRr, y=seLogRr, alpha = Group), environment=environment())+ + geom_vline(xintercept=log(breaks), colour =""#AAAAAA"", lty=1, size=0.5) + + geom_abline(slope = 1/qnorm(0.025/n), colour=rgb(0.8,0,0), linetype=""dashed"", size=1,alpha=0.5) + + geom_abline(slope = 1/qnorm(1-0.025/n), colour=rgb(0.8,0,0), linetype=""dashed"", size=1,alpha=0.5) + + geom_point(size=size, color = rgb(0,0,0), shape = 16) + + geom_hline(yintercept=0) + + geom_label(x = log(0.11), y = 0.99, alpha = 1, hjust = ""left"", aes(label = nLabel), size = 4, data = dd[dd$Group %in% subset, ]) + + geom_label(x = log(0.11), y = labelY, alpha = 1, hjust = ""left"", aes(label = meanLabel), size = 4, data = dd[dd$Group %in% subset, ]) + + scale_x_continuous(""Effect size"",limits = log(c(0.1,10)), breaks=log(breaks),labels=breaks) + + scale_y_continuous(""Standard Error"",limits = c(0,1)) + + scale_alpha_manual(values = alpha) + + facet_grid(.~Group) + + theme( + panel.grid.minor = element_blank(), + panel.background= element_blank(), + panel.grid.major= element_blank(), + axis.ticks = element_blank(), + axis.text.y = themeRA, + axis.text.x = theme, + legend.key= element_blank(), + strip.text.x = theme, + strip.text.y = theme, + strip.background = element_blank(), + legend.position = ""none"" + ) + +ggsave(plot = plot, file.path(paperFolder, ""Lit.png""), width = 10, height = 3.2, dpi = 400) + +ggsave(plot = plot, file.path(paperFolder, ""UsBonf.png""), width = 10, height =5.2, dpi = 400) + + +tempd <- d +tempdd <- dd +d <- d[d$Group == ""B\nAll observational literature"", ] +dd <- dd[dd$Group == ""B\nAll observational literature"", ] +ggsave(plot = plot, file.path(paperFolder, ""Lit.png""), width = 8, height = 4.5, dpi = 500) + +# Treatment dendogram ----------------------------------------------------- + +library(meta) +library(ggplot2) +library(ggdendro) + +calibrated <- read.csv(""r:/DepressionResults.csv"") +d <- calibrated[calibrated$analysisId == 3 & calibrated$outcomeType == ""hoi"", ] + +names <- as.character(unique(d$targetName)) +names <- names[names != ""Electroconvulsive therapy""] +names <- names[order(names)] +m <- combn(names, 2) +m <- data.frame(cohortName1 = m[1, ], + cohortName2 = m[2, ], + stringsAsFactors = FALSE) + +computeDistance <- function(i, m, d) { + subset <- d[(d$targetName == m$cohortName1[i] & d$comparatorName == m$cohortName2[i]) | + (d$targetName == m$cohortName2[i] & d$comparatorName == m$cohortName1[i]), + c(""calLogRr"", ""calSeLogRr"")] + if (nrow(subset) == 0) + return(NA) + subset <- subset[!is.na(subset$calSeLogRr), ] + meta <- metagen(subset$calLogRr, subset$calSeLogRr, sm = ""RR"") + return(meta$tau) +} + +m$distance <- sapply(1:nrow(m), computeDistance, m, d) +m <- m[order(m$cohortName1, m$cohortName2), ] +d1 <- m$distance +attr(d1, ""Size"") <- length(names) +attr(d1, ""Labels"") <- names +attr(d1, ""Diag"") <- FALSE +attr(d1, ""Upper"") <- TRUE +attr(d1, ""method"") <- ""binary"" +class(d1) <- ""dist"" + +model <- hclust(d1, method = ""ward.D2"") +dhc <- as.dendrogram(model) +ddata <- dendro_data(dhc, type = ""rectangle"") +pathToCsv <- system.file(""settings"", ""ExposuresOfInterest.csv"", package = ""LargeScalePopEst"") +exposuresOfInterest <- read.csv(pathToCsv, stringsAsFactors = FALSE) +classes <- merge(ddata$labels, exposuresOfInterest, by.x = ""label"", by.y = ""name"") + +ggplot(segment(ddata)) + + geom_segment(aes(x = x, y = y, xend = xend, yend = yend)) + + geom_text(data = ddata$labels, + aes(x = x, y = y-0.01, label = label), size = 3, hjust = 0) + + geom_point(data = classes, + aes(x = x, y = y, shape = class, color = class, fill = class), size = 2) + + coord_flip() + + scale_y_reverse(expand = c(0.2, 0)) + + scale_shape_manual(values = c(21, 22, 23, 24, 25,26)) + + theme_dendro() +ggsave(""r:/temp/Dendo.png"", width = 7, height = 4, dpi = 300) + +# Within versus between class --------------------------------------------- + +library(meta) +library(ggplot2) + +calibrated <- read.csv(""r:/DepressionResults.csv"") +d <- calibrated[calibrated$analysisId == 3 & calibrated$outcomeType == ""hoi"", ] + +pathToCsv <- system.file(""settings"", ""ExposuresOfInterest.csv"", package = ""LargeScalePopEst"") +eoi <- read.csv(pathToCsv, stringsAsFactors = FALSE) +eoi <- eoi[eoi$class %in% c(""TCA"", ""SSRI"", ""SNRI""), ] +d <- merge(d, data.frame(targetName = eoi$name, targetClass = eoi$class)) +d <- merge(d, data.frame(comparatorName = eoi$name, comparatorClass = eoi$class)) + +names <- as.character(unique(d$targetClass)) +names <- names[order(names)] +m <- combn(names, 2) +m <- data.frame(class1 = c(m[1, ], names), + class2 = c(m[2, ], names), + stringsAsFactors = FALSE) + +computeDistance <- function(i, m, d) { + subset <- d[(d$targetClass == m$class1[i] & d$comparatorClass == m$class2[i]) | + (d$targetClass == m$class2[i] & d$comparatorClass == m$class1[i]),] + + subset <- subset[!is.na(subset$calSeLogRr), ] + + # meta <- metagen(subset$calLogRr, subset$calSeLogRr, sm = ""RR"") + # return(meta$tau) + + sign <- subset$calCi95lb > 1 | subset$calCi95ub < 1 + return(sum(sign) / length(sign)) +} + +m$distance <- sapply(1:nrow(m), computeDistance, m, d) + +mSym <- rbind(m, data.frame(class1 = m$class2, class2 = m$class1, distance = m$distance)) +ggplot(mSym, aes(class1, class2)) + + geom_tile(aes(fill = distance), colour = ""white"") + + geom_text(aes(label = formatC(distance, digits = 2,format = ""f"" )), size = 3) + + scale_fill_gradient(low = ""white"", high = ""red"") + + theme(plot.background = element_blank(), + panel.background = element_blank(), + axis.title = element_blank(), + legend.position = ""none"") + +ggsave(file.path(paperFolder, ""ClassSim.png""), width = 2, height = 2, dpi = 300) + + +# Transitivity (significance) ------------------------------------------------------------ + +calibrated <- read.csv(""r:/DepressionResults.csv"") +d <- calibrated[calibrated$analysisId == 3 & calibrated$outcomeType == ""hoi"", ] +d <- d[!is.na(d$calRr), ] +d$sign <- d$calCi95lb > 1 | d$calCi95ub < 1 +sign <- d[d$sign, ] +ab <- data.frame(nameA = sign$targetName, + nameB = sign$comparatorName, + outcome = sign$outcomeName, + db = sign$db, + increase = sign$calRr > 1, + rrAB = sign$calRr, + lbAB = sign$calCi95lb, + ubAB = sign$calCi95ub) +bc <- data.frame(nameB = sign$targetName, + nameC = sign$comparatorName, + outcome = sign$outcomeName, + db = sign$db, + increase = sign$calRr > 1, + rrBC = sign$calRr, + lbBC = sign$calCi95lb, + ubBC = sign$calCi95ub) +abc <- merge(ab, bc) +ac <- data.frame(nameA = d$targetName, + nameC = d$comparatorName, + outcome = d$outcomeName, + db = d$db, + rrAC = d$calRr, + lbAC = d$calCi95lb, + ubAC = d$calCi95ub) +abcPlusAc <- merge(abc, ac) + +agree <- (abcPlusAc$increase & abcPlusAc$lbAC > 1) | (!abcPlusAc$increase & abcPlusAc$ubAC < 1) +mean(agree) +length(agree) +sum(agree) +expected <- 2 * 0.025 * 0.025 * 180852 + + +# Transitivity (estimate) ------------------------------------------------- + +calibrated <- read.csv(""r:/DepressionResults.csv"") +d <- calibrated[calibrated$analysisId == 3 & calibrated$outcomeType == ""hoi"", ] +d <- d[!is.na(d$calRr), ] + +ab <- data.frame(nameA = d$targetName, + nameB = d$comparatorName, + outcome = d$outcomeName, + db = d$db, + rrAB = d$calRr, + lbAB = d$calCi95lb, + ubAB = d$calCi95ub, + seLogRrAB = d$calSeLogRr) +bc <- data.frame(nameB = d$targetName, + nameC = d$comparatorName, + outcome = d$outcomeName, + db = d$db, + rrBC = d$calRr, + lbBC = d$calCi95lb, + ubBC = d$calCi95ub, + seLogRrBC = d$calSeLogRr) +abc <- merge(ab, bc) +abc$rrACInferred <- abc$rrAB * abc$rrBC +abc$seLogRrACInferred <- sqrt(abc$seLogRrAB^2 + abc$seLogRrBC^2) +abc$lbACInferred <- exp(log(abc$rrACInferred) + qnorm(0.025) * abc$seLogRrACInferred) +abc$ubACInferred <- exp(log(abc$rrACInferred) + qnorm(0.975) * abc$seLogRrACInferred) +ac <- data.frame(nameA = d$targetName, + nameC = d$comparatorName, + outcome = d$outcomeName, + db = d$db, + rrAC = d$calRr, + lbAC = d$calCi95lb, + ubAC = d$calCi95ub, + seLogRrAC = d$calSeLogRr) +abcPlusAc <- merge(abc, ac) +z <- (log(abcPlusAc$rrAC) - log(abcPlusAc$rrACInferred)) / sqrt(abcPlusAc$seLogRrAC^2 + abcPlusAc$seLogRrACInferred^2) +diff <- abs(z) > qnorm(0.975) +mean(diff) + + +# P-value calibration effect ------------------------------------------------------ + +calibrated <- read.csv(""r:/DepressionResults.csv"") +d <- calibrated[calibrated$outcomeType == ""hoi"" | calibrated$outcomeType == ""negative control"", ] +d <- d[!is.na(d$calP), ] +d$sign <- d$p < 0.05 +d$calSign <- d$calP < 0.05 +dUncal <- aggregate(sign ~ outcomeType + analysisId, data = d, mean) +dUncal$estimateType <- ""Uncalibrated"" +dCal <- aggregate(calSign ~ outcomeType + analysisId, data = d, mean) +names(dCal)[names(dCal) == ""calSign""] <- ""sign"" +dCal$estimateType <- ""Calibrated"" + +dd <- rbind(dUncal, dCal) +dd$analysis <- ""Crude"" +dd$analysis[dd$analysisId == 3] <- ""Adjusted"" +dd$analysis <- factor(dd$analysis, levels = c(""Crude"", ""Adjusted"")) +dd$estimateType <- factor(dd$estimateType, levels = c(""Uncalibrated"", ""Calibrated"")) +dd$outcome <- ""Negative controls"" +dd$outcome[dd$outcomeType == ""hoi""] <- ""Outcomes of interest"" +dd$label <- paste0(formatC(dd$sign*100, digits = 1,format = ""f"" ),""%"") +dd$textY <- dd$sign +dd$textY[dd$outcome == ""Negative controls"" & dd$estimateType == ""Calibrated"" & dd$analysis == ""Crude""] <- 0.04 +dd$textY[dd$outcome == ""Negative controls"" & dd$estimateType == ""Calibrated"" & dd$analysis == ""Adjusted""] <- 0.06 +library(ggplot2) +breaks <- c(0.05, 0.1, 0.2, 0.3, 0.4) +labels <- paste0(breaks*100, ""%"") +ggplot(dd, aes(x = estimateType, y = sign, color = analysis, group = analysis, shape = analysis, fill = analysis)) + + geom_hline(yintercept = 0.05, linetype = ""dashed"") + + geom_line(alpha = 0.6) + + geom_point(alpha = 0.6) + + geom_text(data = dd[dd$estimateType == ""Uncalibrated"",], aes(label = label, y = textY), hjust = 1, nudge_x = -0.1, show.legend = FALSE) + + geom_text(data = dd[dd$estimateType == ""Calibrated"",], aes(label = label, y = textY), hjust = 0, nudge_x = 0.1, show.legend = FALSE) + + scale_y_continuous(""Percent significant"", breaks = breaks, labels = labels) + + scale_color_manual(values = c(rgb(0.8,0,0), rgb(0,0,0.8))) + + scale_fill_manual(values = c(rgb(0.8,0,0), rgb(0,0,0.8))) + + facet_wrap(~outcome) + + theme(axis.title.x = element_blank(), + panel.background = element_blank(), + panel.grid.major.y = element_line(color = rgb(0.25,0.25,0.25, alpha = 0.2)), + panel.grid.major.x = element_blank()) + +ggsave(""r:/temp/RCali.png"", width = 6, height = 3, dpi=300) + + +# Between database heterogeneity ------------------------------------------ + +library(meta) +library(ggplot2) +calibrated <- read.csv(""r:/DepressionResults.csv"") +d <- calibrated[calibrated$outcomeType == ""hoi"" & calibrated$analysisId == 3, ] +dd <- aggregate(calLogRr ~ targetName + comparatorName + outcomeName, data = d, length) +dd <- dd[dd$calLogRr == 4, ] +dd$calLogRr <- NULL +nrow(dd) + +computeI2 <- function(i, dd, d, calibrated = TRUE) { + triplet <- dd[i,] + studies <- d[d$targetName == triplet$targetName & d$comparatorName == triplet$comparatorName & d$outcomeName == triplet$outcomeName, ] + if (calibrated) { + meta <- metagen(studies$calLogRr, studies$calSeLogRr, sm = ""RR"") + } else { + meta <- metagen(studies$logRr, studies$seLogRr, sm = ""RR"") + } + return( meta$I2) + #forest(meta) +} + +i2Cal <- sapply(1:nrow(dd), computeI2, dd = dd, d = d, calibrated = TRUE) +i2 <- sapply(1:nrow(dd), computeI2, dd = dd, d = d, calibrated = FALSE) + +ddd <- data.frame(i2 = c(i2, i2Cal), + group = c(rep(""Uncalibrated"", length(i2)), rep(""Calibrated"", length(i2Cal)))) + +# ggplot(ddd, aes(x=i2, group = group, color = group, fill = group)) + +# geom_density() + +# scale_fill_manual(values = c(rgb(0.8, 0, 0, alpha = 0.5), rgb(0, 0, 0.8, alpha = 0.5))) + +# scale_color_manual(values = c(rgb(0.8, 0, 0, alpha = 0.5), rgb(0, 0, 0.8, alpha = 0.5))) + +# theme(legend.title = ggplot2::element_blank()) + +ggplot(ddd, aes(x=i2, group = group, color = group, fill = group)) + + geom_histogram(binwidth = 0.05, boundary = 0, position = ""identity"") + + scale_fill_manual(values = c(rgb(0.8, 0, 0, alpha = 0.5), rgb(0, 0, 0.8, alpha = 0.4))) + + scale_color_manual(values = c(rgb(0.8, 0, 0, alpha = 0.5), rgb(0, 0, 0.8, alpha = 0.4))) + + scale_x_continuous(expression(i^2)) + + scale_y_continuous(""TCO triplets"") + + theme(legend.title = ggplot2::element_blank(), + panel.background = element_blank(), + panel.grid.major.y = element_line(color = rgb(0.25,0.25,0.25, alpha = 0.2)), + panel.grid.major.x = element_line(color = rgb(0.25,0.25,0.25, alpha = 0.2))) + +ggsave(file.path(paperFolder, ""I2.png""), width = 4.5, height = 2, dpi=300) +length(i2Cal) +mean(i2Cal < 0.25) +mean(i2 <0.25) + + + +# Exemplar study: duloxetine vs sertraline for stroke in CCAE ------------- + +workFolder <- ""R:/PopEstDepression_Ccae"" +exposureSummary <- read.csv(file.path(workFolder, ""exposureSummaryFilteredBySize.csv"")) +outcomeModelReference <- readRDS(file.path(workFolder, ""cmOutput"", ""outcomeModelReference.rds"")) +analysesSum <- read.csv(file.path(workFolder, ""analysisSummary.csv"")) +signalInjectionSum <- read.csv(file.path(workFolder, ""signalInjectionSummary.csv"")) +negativeControlIds <- unique(signalInjectionSum$outcomeId) + +row <- exposureSummary[exposureSummary$tCohortDefinitionName == ""duloxetine"" & exposureSummary$cCohortDefinitionName == ""Sertraline"", ] +treatmentId <- row$tprimeCohortDefinitionId +comparatorId <- row$cprimeCohortDefinitionId +estimates <- analysesSum[analysesSum$targetId == treatmentId & analysesSum$comparatorId == comparatorId, ] +calibrated <- read.csv(file.path(workFolder, ""calibratedEstimates.csv"")) +calibrated <- calibrated[calibrated$analysisId == 3 & calibrated$targetId == treatmentId & calibrated$comparatorId == comparatorId, ] + +########################################################################### Get PS plot # +psFile <- outcomeModelReference$sharedPsFile[outcomeModelReference$analysisId == 3 & outcomeModelReference$targetId == + treatmentId & outcomeModelReference$comparatorId == comparatorId][1] +ps <- readRDS(psFile) +fileName <- file.path(paperFolder, ""PsExamplar.png"") +plotPs(ps, + scale = ""propensity"", + treatmentLabel = ""Duloxetine"", + comparatorLabel = ""Sertraline"", + legenPosition = ""top"", + fileName = fileName) + +########################################################################### Create covariate balance plot # +cohortMethodDataFolder <- outcomeModelReference$cohortMethodDataFolder[outcomeModelReference$targetId == + treatmentId & outcomeModelReference$comparatorId == comparatorId & outcomeModelReference$analysisId == + 3 & outcomeModelReference$outcomeId == 2559] +strataFile <- outcomeModelReference$strataFile[outcomeModelReference$targetId == treatmentId & outcomeModelReference$comparatorId == + comparatorId & outcomeModelReference$analysisId == 3 & outcomeModelReference$outcomeId == 2559] + +cohortMethodDataFolder <- gsub(""^S:"", ""R:"", cohortMethodDataFolder) +strataFile <- gsub(""^S:"", ""R:"", strataFile) +cohortMethodData <- CohortMethod::loadCohortMethodData(cohortMethodDataFolder) +strata <- readRDS(strataFile) +balance <- CohortMethod::computeCovariateBalance(strata, cohortMethodData) +nrow(balance) +tableFileName <- file.path(paperFolder, ""balance.csv"") +write.csv(balance, tableFileName, row.names = FALSE) +# balance <- read.csv(tableFileName) +plotFileName <- file.path(paperFolder, ""balanceScatterPlot.png"") +balance$beforeMatchingStdDiff <- abs(balance$beforeMatchingStdDiff) +balance$afterMatchingStdDiff <- abs(balance$afterMatchingStdDiff) +limits <- c(min(c(balance$beforeMatchingStdDiff, balance$afterMatchingStdDiff), na.rm = TRUE), + max(c(balance$beforeMatchingStdDiff, balance$afterMatchingStdDiff), na.rm = TRUE)) +plot <- ggplot2::ggplot(balance, + ggplot2::aes(x = beforeMatchingStdDiff, y = afterMatchingStdDiff)) + + ggplot2::geom_point(color = rgb(0, 0, 0.8, alpha = 0.3), shape = 16) + + ggplot2::geom_abline(slope = 1, intercept = 0, linetype = ""dashed"") + + ggplot2::geom_hline(yintercept = 0) + + ggplot2::geom_vline(xintercept = 0) + + #ggplot2::ggtitle(""Standardized difference of mean"") + + ggplot2::scale_x_continuous(""SDM before stratification"", limits = limits) + + ggplot2::scale_y_continuous(""SDM after stratification"", limits = c(limits[1], limits[2]/2)) + +plot <- plot + ggplot2::geom_hline(yintercept = 0.1, alpha = 0.5, linetype = ""dotted"") + +ggplot2::ggsave(plotFileName, plot, width = 5, height = 2.5, dpi = 400) + + +###################################################################### Get signal injection and calibration plots # + +injectedSignals <- signalInjectionSum[signalInjectionSum$exposureId == row$tCohortDefinitionId, ] +injectedSignals <- data.frame(outcomeId = injectedSignals$newOutcomeId, + oldOutcomeId = injectedSignals$outcomeId, + trueLogRr = log(injectedSignals$targetEffectSize)) +# negativeControlIdSubsets <- unique(signalInjectionSum$outcomeId[signalInjectionSum$exposureId == row$tCohortDefinitionId & +# signalInjectionSum$injectedOutcomes != 0]) +negativeControls <- data.frame(outcomeId = negativeControlIds, + oldOutcomeId = negativeControlIds, + trueLogRr = 0) + +source(""extras/SharedPlots.R"") + +d1 <- rbind(injectedSignals, negativeControls) +d1 <- merge(d1, estimates[estimates$analysisId == 3, ]) +d1$trueRr <- exp(d1$trueLogRr) +d1$yGroup <- ""Uncalibrated"" + +d2 <- rbind(injectedSignals, negativeControls) +d2 <- merge(d2, calibrated[calibrated$analysisId == 3, ]) +d2$logRr <- d2$calLogRr +d2$seLogRr <- d2$calSeLogRr +d2$ci95lb <- d2$calCi95lb +d2$ci95ub <- d2$calCi95ub +d2$trueRr <- exp(d2$trueLogRr) +d2$Group <- as.factor(d2$trueRr) +d2$yGroup <- ""Calibrated"" +d <- rbind(d1[, c(""logRr"", ""seLogRr"", ""ci95lb"", ""ci95ub"", ""yGroup"", ""trueRr"")], + d2[, c(""logRr"", ""seLogRr"", ""ci95lb"", ""ci95ub"", ""yGroup"", ""trueRr"")]) +d$yGroup <- factor(d$yGroup, levels = c(""Uncalibrated"", ""Calibrated"")) +plotScatter(d, yPanelGroup = TRUE, labelY = 0.65, size = 2) +ggsave(file.path(paperFolder, ""exemplarEvalCali.png""), width = 12.5, height = 3.5, dpi = 500) + +calibrated <- read.csv(file.path(workFolder, ""calibratedEstimates.csv"")) + +calibrated[calibrated$outcomeId == 2559 & calibrated$targetId == treatmentId & calibrated$comparatorId == comparatorId,] + + +# Leave-one-out cross-validation ------------------------------------------ +calibrated <- read.csv(""r:/DepressionResults.csv"") +library(ggplot2) +d <- calibrated[calibrated$analysisId == 3 & !is.na(calibrated$trueRr),] +d$group <- sub(""_.*"", """", d$outcomeName) +source(""extras/SharedPlots.R"") +plotCiCalibration(d) +ggsave(file.path(paperFolder, ""leaveOneOutCv.png""), width = 9, height = 3.5, dpi = 500) + + +# Supplementary table S1 -------------------------------------------------- +calibrated <- read.csv(""r:/DepressionResults.csv"") +d <- calibrated[calibrated$analysisId == 3 | calibrated$analysisId == 4,] +d$analysis <- ""Main"" +d$analysis[d$analysisId == 4] <- ""Sensitivity"" +d <- d[, c(""analysis"", ""targetName"", ""comparatorName"", ""outcomeName"", ""outcomeType"", ""trueRr"", ""db"", ""treated"", ""comparator"", ""treatedDays"", ""comparatorDays"", ""eventsTreated"", ""eventsComparator"", ""rr"", ""ci95lb"", ""ci95ub"", ""p"", ""calRr"", ""calCi95lb"", ""calCi95ub"", ""calP"")] +names(d) <- c(""Analysis"", ""Target"", ""Comparator"", ""Outcome"", ""Outcome type"", ""True hazard ratio"", ""Database"", ""Target persons"", ""Comparator persons"", ""Target days"", ""Comparator days"", ""Target events"", ""Comparator events"", ""Hazard ratio"", ""Lower bound 95% CI"", ""Upper bound 95% CI"", ""P-value"", ""Calibrated hazard ratio"", ""Calibrated lower bound 95% CI"", ""Calibrated upper bound 95% CI"", ""Calibrated P-value"") +write.csv(d, file.path(paperFolder, ""SupplementaryTableS1.csv""), row.names = FALSE) + +# Supplementary table S2 -------------------------------------------------- +literature <- read.csv(""C:/home/Research/PublicationBias/AnalysisJitter.csv"") +d <- literature +seFromCI <- (log(d$EffectEstimate_jitter)-log(d$CI.LB_jitter))/qnorm(0.975) +seFromP <- abs(log(d$EffectEstimate_jitter)/qnorm(d$P.value_jitter)) +d$seLogRr <- seFromCI +d$seLogRr[is.na(d$seLogRr)] <- seFromP[is.na(d$seLogRr)] +d <- d[!is.na(d$seLogRr), ] +d <- d[d$EffectEstimate_jitter > 0, ] +d <- d[, c(""PMID"", ""Year"", ""DepressionTreatment"", ""EffectEstimate"", ""CI.LB"", ""CI.UB"", ""P.value"")] +names(d) <- c(""PMID"", ""Year"", ""Depression treatment"", ""Effect estimate"", ""Lower bound 95% CI"", ""Upper bound 95% CI"", ""P-value"") + +write.csv(d, file.path(paperFolder, ""SupplementaryTableS2.csv""), row.names = FALSE) + + + + + +data$trueRr <- exp(data$trueLogRr) +data$logLb <- data$logRr - (data$seLogRr * qnorm(0.975)) +data$logUb <- data$logRr + (data$seLogRr * qnorm(0.975)) +data$covered <- data$trueLogRr >= data$logLb & data$trueLogRr <= data$logUb +aggregate(covered ~ trueRr, data = data, mean) + +ingrownNail <- 139099 +data <- data[order(data$trueRr), ] +data$rr <- exp(data$logRr) +data$lb <- exp(data$logLb) +data$ub <- exp(data$logUb) +round(data[data$oldOutcomeId == ingrownNail, c(""trueRr"", ""rr"", ""lb"", ""ub"")], 2) + +########################################################################### P-value calibration # +file.copy(from = file.path(workFolder, + ""figuresAndtables"", + ""calibration"", + paste0(""negControls_a3_t"", treatmentId, ""_c"", comparatorId, "".png"")), + to = file.path(symposiumFolder, ""pCalEffectPlot.png""), + overwrite = TRUE) + +negControls <- estimates[estimates$outcomeId %in% negativeControlIds & estimates$analysisId == 3, ] +EmpiricalCalibration::plotCalibration(logRr = negControls$logRr, + seLogRr = negControls$seLogRr, + useMcmc = TRUE) +writeLines(paste0(""Adjusted negative control p < 0.05: "", mean(negControls$p < 0.05))) + +negControls <- calibrated[calibrated$analysisId == 3 & calibrated$targetId == treatmentId & calibrated$comparatorId == + comparatorId & calibrated$outcomeId %in% negativeControlIds, ] +writeLines(paste0(""Calibrated negative control p < 0.05: "", mean(negControls$calP < 0.05))) + +########################################################################### CI calibration # +file.copy(from = file.path(workFolder, + ""figuresAndtables"", + ""calibration"", + paste0(""trueAndObs_a3_t"", treatmentId, ""_c"", comparatorId, "".png"")), + to = file.path(symposiumFolder, ""trueAndObsCali.png""), + overwrite = TRUE) + +injectedSignals <- signalInjectionSum[signalInjectionSum$exposureId == row$tCohortDefinitionId, ] +injectedSignals <- data.frame(outcomeId = injectedSignals$newOutcomeId, + trueLogRr = log(injectedSignals$targetEffectSize)) +negativeControlIdSubsets <- unique(signalInjectionSum$outcomeId[signalInjectionSum$exposureId == row$tCohortDefinitionId & + signalInjectionSum$injectedOutcomes != 0]) +negativeControls <- data.frame(outcomeId = negativeControlIdSubsets, trueLogRr = 0) +data <- rbind(injectedSignals, negativeControls) +data <- merge(data, + calibrated[calibrated$analysisId == 3 & calibrated$targetId == treatmentId & calibrated$comparatorId == + comparatorId, c(""outcomeId"", ""calRr"", ""calCi95lb"", ""calCi95ub"", ""logRr"", ""seLogRr"")]) +data$trueRr <- exp(data$trueLogRr) +data$covered <- data$trueRr >= data$calCi95lb & data$trueRr <= data$calCi95ub +aggregate(covered ~ trueRr, data = data, mean) + +ingrownNail <- 139099 +data[data$outcomeId == ingrownNail, ] + +model <- EmpiricalCalibration::fitSystematicErrorModel(data$logRr, data$seLogRr, log(data$trueRr)) + + + + + + + + + + + + + + + + + +### Fit mixture model ### + +fitMix <- function(logRr, seLogRr) { + if (any(is.infinite(seLogRr))) { + warning(""Estimate(s) with infinite standard error detected. Removing before fitting null distribution"") + logRr <- logRr[!is.infinite(seLogRr)] + seLogRr <- seLogRr[!is.infinite(seLogRr)] + } + if (any(is.infinite(logRr))) { + warning(""Estimate(s) with infinite logRr detected. Removing before fitting null distribution"") + seLogRr <- seLogRr[!is.infinite(logRr)] + logRr <- logRr[!is.infinite(logRr)] + } + if (any(is.na(seLogRr))) { + warning(""Estimate(s) with NA standard error detected. Removing before fitting null distribution"") + logRr <- logRr[!is.na(seLogRr)] + seLogRr <- seLogRr[!is.na(seLogRr)] + } + if (any(is.na(logRr))) { + warning(""Estimate(s) with NA logRr detected. Removing before fitting null distribution"") + seLogRr <- seLogRr[!is.na(logRr)] + logRr <- logRr[!is.na(logRr)] + } + + gaussianProduct <- function(mu1, mu2, sd1, sd2) { + (2 * pi)^(-1/2) * (sd1^2 + sd2^2)^(-1/2) * exp(-(mu1 - mu2)^2/(2 * (sd1^2 + sd2^2))) + } + + # Use logit function to prevent mixture fraction from straying from [0,1] + link <- function(x) { + return(exp(x)/(exp(x) + 1)) + } + + LL <- function(theta, estimate, se) { + result <- 0 + for (i in 1:length(estimate)) { + result <- result - log(link(theta[1]) * gaussianProduct(estimate[i], + theta[2], + se[i], + exp(theta[3])) + (1 - link(theta[1])) * gaussianProduct(estimate[i], + theta[4], + se[i], + exp(theta[5]))) + } + if (is.infinite(result)) + result <- 99999 + result + } + theta <- c(0, 0, -2, 1, -0.5) + fit <- optim(theta, LL, estimate = logRr, se = seLogRr) + + result <- data.frame(mix = link(fit$par[1]), + mean1 = fit$par[2], + sd1 = exp(fit$par[3]), + mean2 = fit$par[4], + sd2 = exp(fit$par[5])) + + + return(result) +} + +fitMix(d$logRr, d$seLogRr) + + +fitMixFix1 <- function(logRr, seLogRr) { + if (any(is.infinite(seLogRr))) { + warning(""Estimate(s) with infinite standard error detected. Removing before fitting null distribution"") + logRr <- logRr[!is.infinite(seLogRr)] + seLogRr <- seLogRr[!is.infinite(seLogRr)] + } + if (any(is.infinite(logRr))) { + warning(""Estimate(s) with infinite logRr detected. Removing before fitting null distribution"") + seLogRr <- seLogRr[!is.infinite(logRr)] + logRr <- logRr[!is.infinite(logRr)] + } + if (any(is.na(seLogRr))) { + warning(""Estimate(s) with NA standard error detected. Removing before fitting null distribution"") + logRr <- logRr[!is.na(seLogRr)] + seLogRr <- seLogRr[!is.na(seLogRr)] + } + if (any(is.na(logRr))) { + warning(""Estimate(s) with NA logRr detected. Removing before fitting null distribution"") + seLogRr <- seLogRr[!is.na(logRr)] + logRr <- logRr[!is.na(logRr)] + } + + gaussianProduct <- function(mu1, mu2, sd1, sd2) { + (2 * pi)^(-1/2) * (sd1^2 + sd2^2)^(-1/2) * exp(-(mu1 - mu2)^2/(2 * (sd1^2 + sd2^2))) + } + + # Use logit function to prevent mixture fraction from straying from [0,1] + link <- function(x) { + return(exp(x)/(exp(x) + 1)) + } + + LL <- function(theta, estimate, se) { + result <- 0 + for (i in 1:length(estimate)) { + result <- result - log(link(theta[1]) * dnorm(0, + mean = estimate[i], + sd = se[i]) + (1 - link(theta[1])) * + gaussianProduct(estimate[i], theta[2], se[i], exp(theta[3]))) + } + if (is.infinite(result)) + result <- 99999 + result + } + theta <- c(0, 1, -0.5) + fit <- optim(theta, LL, estimate = logRr, se = seLogRr) + + result <- data.frame(mix = link(fit$par[1]), + mean1 = 0, + sd1 = 0, + mean2 = fit$par[2], + sd2 = exp(fit$par[3])) + + + return(result) +} + +fitMixFix1(d$logRr, d$seLogRr) + +# Comparison against RCTs ------------------------------------------------------------- +library(ggplot2) +calibrated <- read.csv(""r:/DepressionResults.csv"") +subset <- calibrated[calibrated$targetName == ""Sertraline"" & calibrated$outcomeName == ""Diarrhea"" & calibrated$analysisId == 3, ] +subset$comparatorName <- as.character(subset$comparatorName) +subset$comparatorName <- paste0(toupper(substr(subset$comparatorName, 1, 1)), substr(subset$comparatorName, 2, nchar(subset$comparatorName))) +rcts <- read.csv(""extras/SertralineRcts.csv"", stringsAsFactors = FALSE) +subset <- subset[subset$comparatorName %in% rcts$Comparator, ] +obsData <- data.frame(Source = subset$db, + Comparator = subset$comparatorName, + nTarget = formatC(subset$treated, big.mark = "","", format = ""d""), + nComparator = formatC(subset$comparator, big.mark = "","", format = ""d""), + rr = subset$calRr, + ci95lb = subset$calCi95lb, + ci95ub = subset$calCi95ub, + type = ""Observational"", + sortValue = paste(subset$comparatorName, ""Z"", subset$db), + stringsAsFactors = FALSE) +rctData <- data.frame(Source = rcts$Reference, + Comparator = rcts$Comparator, + nTarget = formatC(rcts$nTargetr, big.mark = "","", format = ""d""), + nComparator = formatC(rcts$nComparator, big.mark = "","", format = ""d""), + rr = rcts$rr, + ci95lb = rcts$ci95lb, + ci95ub = rcts$ci95ub, + type = ""RCT"", + sortValue = paste(rcts$Comparator, ""B"", rcts$Reference), + stringsAsFactors = FALSE) +emptyRows <- data.frame(Source = ""AAA"", + Comparator = rep("""", length(unique(rcts$Comparator))), + nTarget = """", + nComparator = """", + rr = NA, + ci95lb = NA, + ci95ub = NA, + type = ""RCT"", + sortValue = paste(unique(rcts$Comparator), ""A""), + stringsAsFactors = FALSE) +vizData <- rbind(obsData, rctData, emptyRows) +vizData <- vizData[order(vizData$sortValue, decreasing = TRUE), ] +vizData$sortValue <- 1:nrow(vizData) + +breaks <- c(0.25, 0.5, 1, 2, 4, 6, 8, 10) +myText <- element_text() +p <- ggplot(vizData,aes(x = rr, y = sortValue, xmin = ci95lb, xmax = ci95ub, color = type, fill = type)) + + geom_vline(xintercept = breaks, colour = ""#AAAAAA"", lty = 1, size = 0.2) + + geom_vline(xintercept = 1, size = 0.5) + + geom_errorbarh(height = 0.15, alpha = 0.7) + + geom_point(size=3, shape = 23, alpha = 0.7) + + scale_color_manual(values = c(rgb(0, 0, 0.8), rgb(0.8, 0, 0))) + + scale_fill_manual(values = c(rgb(0, 0, 0.8), rgb(0.8, 0, 0))) + + scale_x_continuous(""Effect size"", trans = ""log10"", breaks = breaks, labels = breaks) + + coord_cartesian(xlim = c(0.25, 10)) + + theme( + axis.text.x = myText, + axis.title.x = myText, + panel.grid.major = element_blank(), + panel.grid.minor = element_blank(), + panel.background = element_blank(), + legend.position = ""right"", + legend.title = element_blank(), + panel.border = element_blank(), + axis.text.y = element_blank(), + axis.title.y = element_blank(), + axis.ticks = element_blank(), + plot.margin = grid::unit(c(0,0,0.1,0), ""lines"")) + +labels <- paste0(formatC(vizData$rr, digits = 2, format = ""f""), + "" ("", + formatC(vizData$ci95lb, digits = 2, format = ""f""), + ""-"", + formatC(vizData$ci95ub, digits = 2, format = ""f""), + "")"") + +labels <- data.frame(y = rep(vizData$sortValue, 3), + x = rep(1:3, each = nrow(vizData)), + label = c(as.character(vizData$Source), vizData$Comparator, labels), + stringsAsFactors = FALSE) + +labels$label[nrow(vizData)] <- ""Source"" +labels$label[nrow(vizData)*2] <- ""Comparator"" +labels$label[nrow(vizData)*3] <- ""Effect size (95% CI)"" +labels$label[labels$label == ""AAA""] <- """" +labels$label[labels$label == "" NA ( NA- NA)""] <- """" + + +data_table <- ggplot(labels, aes(x = x, y = y, label = label)) + + geom_text(size = 3, hjust=0, vjust=0.5) + + geom_hline(aes(yintercept=nrow(vizData) - 0.5)) + + theme(panel.grid.major = element_blank(), + panel.grid.minor = element_blank(), + legend.position = ""none"", + panel.border = element_blank(), + panel.background = element_blank(), + axis.text.x = element_text(colour=""white""),#element_blank(), + axis.text.y = element_blank(), + axis.ticks = element_line(colour=""white""),#element_blank(), + plot.margin = grid::unit(c(0,0,0.1,0), ""lines"")) + + labs(x="""",y="""") + + coord_cartesian(xlim=c(1,4)) + +plot <- gridExtra::grid.arrange(data_table, p, ncol=2) +ggsave( file.path(paperFolder, ""Sertraline.png""), plot, width = 9, height = 7, dpi = 400) + + +# SSRIs vs TCAs for suicide -------------------------------------------------------------------------------------- +library(ggplot2) +calibrated <- read.csv(""r:/DepressionResults.csv"") +targets <- c(""Sertraline"", ""Fluoxetine"", ""Citalopram"", ""Escitalopram"", ""venlafaxine"") +comparators <- c(""Amitriptyline"", ""Bupropion"") +subset <- calibrated[calibrated$targetName %in% targets & calibrated$comparatorName %in% comparators & calibrated$outcomeName == ""Suicide and suicidal ideation"" & calibrated$analysisId == 3, ] +subset$targetName <- as.character(subset$targetName) +subset$targetName <- paste0(toupper(substr(subset$targetName, 1, 1)), substr(subset$targetName, 2, nchar(subset$targetName))) + +obsData <- data.frame(Source = subset$db, + Target = subset$targetName, + Comparator = subset$comparatorName, + nTarget = formatC(subset$treated, big.mark = "","", format = ""d""), + nComparator = formatC(subset$comparator, big.mark = "","", format = ""d""), + rr = subset$calRr, + ci95lb = subset$calCi95lb, + ci95ub = subset$calCi95ub, + sortValue = paste(subset$targetName, subset$comparatorName, subset$db), + stringsAsFactors = FALSE) +emptyRow <- data.frame(Source = """", + Target = """", + Comparator = """", + nTarget = """", + nComparator = """", + rr = NA, + ci95lb = NA, + ci95ub = NA, + sortValue = ""AAA"", + stringsAsFactors = FALSE) +vizData <- rbind(obsData, emptyRow) +vizData <- vizData[order(vizData$sortValue, decreasing = TRUE), ] +vizData$sortValue <- 1:nrow(vizData) +breaks <- c(0.25, 0.5, 1, 2, 4, 6, 8, 10) +myText <- element_text() +p <- ggplot(vizData,aes(x = rr, y = sortValue, xmin = ci95lb, xmax = ci95ub)) + + geom_vline(xintercept = breaks, colour = ""#AAAAAA"", lty = 1, size = 0.2) + + geom_vline(xintercept = 1, size = 0.5) + + geom_errorbarh(height = 0.15, alpha = 0.7, color = rgb(0, 0, 0.8)) + + geom_point(size=3, shape = 23, alpha = 0.7, color = rgb(0, 0, 0.8), fill = rgb(0, 0, 0.8)) + + scale_x_continuous(""Effect size"", trans = ""log10"", breaks = breaks, labels = breaks) + + coord_cartesian(xlim = c(0.25, 10)) + + theme( + axis.text.x = myText, + axis.title.x = myText, + panel.grid.major = element_blank(), + panel.grid.minor = element_blank(), + panel.background = element_blank(), + legend.position = ""right"", + legend.title = element_blank(), + panel.border = element_blank(), + axis.text.y = element_blank(), + axis.title.y = element_blank(), + axis.ticks = element_blank(), + plot.margin = grid::unit(c(0,0,0.1,0), ""lines"")) + +labels <- paste0(formatC(vizData$rr, digits = 2, format = ""f""), + "" ("", + formatC(vizData$ci95lb, digits = 2, format = ""f""), + ""-"", + formatC(vizData$ci95ub, digits = 2, format = ""f""), + "")"") + +labels <- data.frame(y = rep(vizData$sortValue, 4), + x = rep(1:4, each = nrow(vizData)), + label = c(as.character(vizData$Source), as.character(vizData$Target), as.character(vizData$Comparator), labels), + stringsAsFactors = FALSE) + +labels$label[nrow(vizData)] <- ""Database"" +labels$label[nrow(vizData)*2] <- ""Target"" +labels$label[nrow(vizData)*3] <- ""Comparator"" +labels$label[nrow(vizData)*4] <- ""HR (95% CI)"" + +data_table <- ggplot(labels, aes(x = x, y = y, label = label)) + + geom_text(size = 3.5, hjust=0, vjust=0.5) + + geom_hline(aes(yintercept=nrow(vizData) - 0.5)) + + theme(panel.grid.major = element_blank(), + panel.grid.minor = element_blank(), + legend.position = ""none"", + panel.border = element_blank(), + panel.background = element_blank(), + axis.text.x = element_text(colour=""white""),#element_blank(), + axis.text.y = element_blank(), + axis.ticks = element_line(colour=""white""),#element_blank(), + plot.margin = grid::unit(c(0,0,0.1,0), ""lines"")) + + labs(x="""",y="""") + + coord_cartesian(xlim=c(1,5)) + +plot <- gridExtra::grid.arrange(data_table, p, ncol=2) +ggsave( file.path(paperFolder, ""Suicide.png""), plot, width = 9, height = 7, dpi = 400) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","LargeScalePopEst/extras/DetectUnfittablePsModels.R",".R","6629","113","# This code is used to find propensity models that are unfittable and currently take days to (try to) fit + + +library(CohortMethod) + +fitAllPsModels <- function(workFolder, fitThreads = 1) { + writeLines(""Fitting propensity models"") + exposureSummary <- read.csv(file.path(workFolder, ""exposureSummaryFilteredBySize.csv"")) + tasks <- list() + for (i in 1:nrow(exposureSummary)) { + targetId <- exposureSummary$tprimeCohortDefinitionId[i] + comparatorId <- exposureSummary$cprimeCohortDefinitionId[i] + folderName <- file.path(workFolder, + ""cmOutput"", + paste0(""CmData_l1_t"", targetId, ""_c"", comparatorId)) + fileName <- file.path(workFolder, + ""cmOutput"", + paste0(""Ps_l1_s1_p2_t"", targetId, ""_c"", comparatorId, "".rds"")) + if (!file.exists(fileName)) { + task <- data.frame(folderName = folderName, fileName = fileName, stringsAsFactors = FALSE) + tasks[[length(tasks) + 1]] <- task + } + } + + fitPropensityModel <- function(task) { + cmData <- CohortMethod::loadCohortMethodData(task$folderName) + studyPop <- CohortMethod::createStudyPopulation(cohortMethodData = cmData, + firstExposureOnly = FALSE, + washoutPeriod = 0, + removeDuplicateSubjects = FALSE, + removeSubjectsWithPriorOutcome = FALSE, + priorOutcomeLookback = 99999, + minDaysAtRisk = 1, + riskWindowStart = 0, + addExposureDaysToStart = FALSE, + riskWindowEnd = 0, + addExposureDaysToEnd = TRUE) + for (seed in 1:3) { + set.seed(seed) + studyPopSample <- studyPop[sample.int(n = nrow(studyPop), size = 10000, replace = FALSE), ] + if (sum(studyPopSample$treatment == 1) < 1000 || sum(studyPopSample$treatment == 0) < 1000) { + studyPopSample <- studyPop[sample.int(n = nrow(studyPop), size = 25000, replace = FALSE), ] + } + if (sum(studyPopSample$treatment == 1) < 1000 || sum(studyPopSample$treatment == 0) < 1000) { + return() + } + ps <- CohortMethod::createPs(cohortMethodData = cmData, + population = studyPopSample, + stopOnError = FALSE, + control = createControl(noiseLevel = ""quiet"", + cvType = ""auto"", + cvRepetitions = 1, + startingVariance = 0.01, + seed = 1, + threads = 10)) + if (computePsAuc(ps) == 1) { + writeLines(paste(""Model for"", task$fileName, ""is perfectly predictive"")) + studyPop$propensityScore <- studyPop$treatment + studyPop$preferenceScore <- studyPop$treatment + saveRDS(ps, task$fileName) + return() + } + } + } + cluster <- OhdsiRTools::makeCluster(fitThreads) + OhdsiRTools::clusterRequire(cluster, ""Cyclops"") + OhdsiRTools::clusterRequire(cluster, ""CohortMethod"") + dummy <- OhdsiRTools::clusterApply(cluster, tasks, fitPropensityModel, stopOnError = TRUE) + OhdsiRTools::stopCluster(cluster) +} +options(fftempdir = ""r:/fftemp"") +workFolder <- ""r:/PopEstDepression_Ccae"" + +# fitAllPsModels(workFolder, fitThreads = 1) + + + + +cmData <- CohortMethod::loadCohortMethodData(""r:/PopEstDepression_Ccae/cmOutput/CmData_l1_t755695129_c4327941129"") +studyPop <- CohortMethod::createStudyPopulation(cohortMethodData = cmData, + firstExposureOnly = FALSE, + washoutPeriod = 0, + removeDuplicateSubjects = FALSE, + removeSubjectsWithPriorOutcome = FALSE, + priorOutcomeLookback = 99999, + minDaysAtRisk = 1, + riskWindowStart = 0, + addExposureDaysToStart = FALSE, + riskWindowEnd = 0, + addExposureDaysToEnd = TRUE) +set.seed(2) +studyPopSample <- studyPop[sample.int(n = nrow(studyPop), size = 10000, replace = FALSE), ] +if (sum(studyPopSample$treatment == 1) < 1000 || sum(studyPopSample$treatment == 0) < 1000) { + studyPopSample <- studyPop[sample.int(n = nrow(studyPop), size = 25000, replace = FALSE), ] +} +if (sum(studyPopSample$treatment == 1) < 1000 || sum(studyPopSample$treatment == 0) < 1000) { + return() +} +ps <- CohortMethod::createPs(cohortMethodData = cmData, + population = studyPopSample, + stopOnError = FALSE, + control = createControl(noiseLevel = ""quiet"", + cvType = ""auto"", + cvRepetitions = 1, + startingVariance = 0.01, + seed = 1, + threads = 1)) +computePsAuc(ps) +plotPs(ps, scale = ""propensity"") +mean(ps$preferenceScore) +model <- getPsModel(ps, cmData) +head(model) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","LargeScalePopEst/extras/PlotsForCenIsbs.R",".R","7002","137","library(ggplot2) +calibrated <- read.csv(""r:/DepressionResults.csv"") +d1 <- calibrated[calibrated$analysisId == 3 & calibrated$outcomeType == ""hoi"", ] +d1$Significant <- d1$calCi95lb > 1 | d1$calCi95ub < 1 + +d2 <- read.csv(""C:/home/Research/PublicationBias/AnalysisJitter.csv"") +d2$Significant <- !(is.na(d2$P.value) | d2$P.value >= 0.05) | !(is.na(d2$CI.LB) | (d2$CI.LB <= 1 & d2$CI.UB >= 1)) +seFromCI <- (log(d2$EffectEstimate_jitter)-log(d2$CI.LB_jitter))/qnorm(0.975) +seFromP <- abs(log(d2$EffectEstimate_jitter)/qnorm(d2$P.value_jitter)) +d2$seLogRr <- seFromCI +d2$seLogRr[is.na(d2$seLogRr)] <- seFromP[is.na(d2$seLogRr)] +d2 <- d2[!is.na(d2$seLogRr), ] +d2 <- d2[d2$EffectEstimate_jitter > 0, ] +#d3 <- d2[d2$Depression == 1, ] +d3 <- d2[d2$DepressionTreatment == 1, ] + +d <- rbind(data.frame(logRr = d1$calLogRr, + seLogRr = d1$calSeLogRr, + Group = ""A\nOur large-scale study on depression treatments"", + Significant = d1$Significant, + dummy = 1), + data.frame(logRr = log(d2$EffectEstimate_jitter), + seLogRr = d2$seLogRr, + Group = ""B\nAll observational literature"", + Significant = d2$Significant, + dummy = 1), + data.frame(logRr = log(d3$EffectEstimate_jitter), + seLogRr = d3$seLogRr, + Group = ""C\nObservational literature on depression treatments"", + Significant = d3$Significant, + dummy = 1)) + +d$Group <- factor(d$Group, levels = c(""A\nOur large-scale study on depression treatments"", ""B\nAll observational literature"", ""C\nObservational literature on depression treatments"")) + +temp1 <- aggregate(dummy ~ Group, data = d, length) +temp1$nLabel <- paste0(formatC(temp1$dummy, big.mark = "",""), "" estimates"") +temp1$dummy <- NULL +temp2 <- aggregate(Significant ~ Group, data = d, mean) +temp2$meanLabel <- paste0(formatC(100 * (1-temp2$Significant), digits = 1, format = ""f""), ""% of CIs include 1"") +temp2$Significant <- NULL +dd <- merge(temp1, temp2) + +breaks <- c(0.1, 0.25, 0.5, 1, 2, 4, 6, 8, 10) +theme <- element_text(colour = ""#000000"", size = 12) +themeRA <- element_text(colour = ""#000000"", size = 12, hjust = 1) +themeLA <- element_text(colour = ""#000000"", size = 12, hjust = 0) + +createPlot <- function(group, fileName, simplified = FALSE) { + plot <- ggplot(d[d$Group == group, ], aes(x=logRr, y=seLogRr, alpha = Group), environment=environment())+ + geom_vline(xintercept=log(breaks), colour =""#AAAAAA"", lty=1, size=0.5) + + geom_point(size=0.5, color = rgb(0,0,0), shape = 16) + + geom_hline(yintercept=0) + + geom_label(x = log(0.11), y = 0.99, alpha = 1, hjust = ""left"", aes(label = nLabel), size = 5, data = dd[dd$Group == group, ]) + + scale_x_continuous(""Effect size"",limits = log(c(0.1,10)), breaks=log(breaks),labels=breaks) + + scale_y_continuous(""Standard Error"",limits = c(0,1)) + + scale_alpha_manual(values = c(0.8, 0.8, 0.8)) + + theme( + panel.grid.minor = element_blank(), + panel.background= element_blank(), + panel.grid.major= element_blank(), + axis.ticks = element_blank(), + axis.text.y = themeRA, + axis.text.x = theme, + legend.key= element_blank(), + strip.text.x = theme, + strip.text.y = theme, + strip.background = element_blank(), + legend.position = ""none"" + ) + + if (!simplified) { + plot <- plot + geom_abline(slope = 1/qnorm(0.025), colour=rgb(0.8,0,0), linetype=""dashed"", size=1,alpha=0.5) + + geom_abline(slope = 1/qnorm(0.975), colour=rgb(0.8,0,0), linetype=""dashed"", size=1,alpha=0.5) + + geom_label(x = log(0.11), y = 0.99, alpha = 1, hjust = ""left"", aes(label = nLabel), size = 5, data = dd[dd$Group == group, ]) + + geom_label(x = log(0.11), y = 0.88, alpha = 1, hjust = ""left"", aes(label = meanLabel), size = 5, data = dd[dd$Group == group, ]) + } + ggsave(plot = plot, fileName, width = 8, height = 4.5, dpi = 500) +} +createPlot(""B\nAll observational literature"", ""s:/temp/lit1.png"", TRUE) +createPlot(""B\nAll observational literature"", ""s:/temp/lit2.png"") +createPlot(""A\nOur large-scale study on depression treatments"", ""s:/temp/us.png"") +createPlot(""C\nObservational literature on depression treatments"", ""s:/temp/litDep.png"") + + + +# Evaluation and calibration plots ---------------------------------------- +workFolder <- ""R:/PopEstDepression_Ccae"" +exposureSummary <- read.csv(file.path(workFolder, ""exposureSummaryFilteredBySize.csv"")) +outcomeModelReference <- readRDS(file.path(workFolder, ""cmOutput"", ""outcomeModelReference.rds"")) +analysesSum <- read.csv(file.path(workFolder, ""analysisSummary.csv"")) +signalInjectionSum <- read.csv(file.path(workFolder, ""signalInjectionSummary.csv"")) +negativeControlIds <- unique(signalInjectionSum$outcomeId) + +row <- exposureSummary[exposureSummary$tCohortDefinitionName == ""duloxetine"" & exposureSummary$cCohortDefinitionName == ""Sertraline"", ] +treatmentId <- row$tprimeCohortDefinitionId +comparatorId <- row$cprimeCohortDefinitionId +estimates <- analysesSum[analysesSum$targetId == treatmentId & analysesSum$comparatorId == comparatorId, ] +calibrated <- read.csv(file.path(workFolder, ""calibratedEstimates.csv"")) +calibrated <- calibrated[calibrated$analysisId == 3 & calibrated$targetId == treatmentId & calibrated$comparatorId == comparatorId, ] + +injectedSignals <- signalInjectionSum[signalInjectionSum$exposureId == row$tCohortDefinitionId, ] +injectedSignals <- data.frame(outcomeId = injectedSignals$newOutcomeId, + oldOutcomeId = injectedSignals$outcomeId, + trueLogRr = log(injectedSignals$targetEffectSize)) +negativeControls <- data.frame(outcomeId = negativeControlIds, + oldOutcomeId = negativeControlIds, + trueLogRr = 0) + +source(""extras/SharedPlots.R"") + +d1 <- rbind(injectedSignals, negativeControls) +d1 <- merge(d1, estimates[estimates$analysisId == 3, ]) +d1$trueRr <- exp(d1$trueLogRr) +d1$yGroup <- ""Uncalibrated"" + +d2 <- rbind(injectedSignals, negativeControls) +d2 <- merge(d2, calibrated[calibrated$analysisId == 3, ]) +d2$logRr <- d2$calLogRr +d2$seLogRr <- d2$calSeLogRr +d2$ci95lb <- d2$calCi95lb +d2$ci95ub <- d2$calCi95ub +d2$trueRr <- exp(d2$trueLogRr) +d2$Group <- as.factor(d2$trueRr) +d2$yGroup <- ""Calibrated"" +d <- rbind(d1[, c(""logRr"", ""seLogRr"", ""ci95lb"", ""ci95ub"", ""yGroup"", ""trueRr"")], + d2[, c(""logRr"", ""seLogRr"", ""ci95lb"", ""ci95ub"", ""yGroup"", ""trueRr"")]) +d$yGroup <- factor(d$yGroup, levels = c(""Uncalibrated"", ""Calibrated"")) +plotScatter(d[d$yGroup == ""Uncalibrated"", ], yPanelGroup = FALSE) +ggsave(""s:/temp/eval.png"", width = 13.5, height = 2.5, dpi = 500) +plotScatter(d[d$yGroup == ""Calibrated"", ], yPanelGroup = FALSE) +ggsave(""s:/temp/cali.png"", width = 13.5, height = 2.5, dpi = 500) + + + + + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","LargeScalePopEst/extras/FitOnlyPsModels.R",".R","8621","159","# This code is used to fit propensity models on one computer, while another computer is fitting the outcome models for signal injection + + +constructCohortMethodDataObjectNoInjection <- function(targetId, + comparatorId, + targetConceptId, + comparatorConceptId, + workFolder) { + # Subsetting cohorts + ffbase::load.ffdf(dir = file.path(workFolder, ""allCohorts"")) + ff::open.ffdf(cohorts, readonly = TRUE) + idx <- cohorts$cohortDefinitionId == targetId | cohorts$cohortDefinitionId == comparatorId + cohorts <- ff::as.ram(cohorts[ffbase::ffwhich(idx, idx == TRUE), ]) + cohorts$treatment <- 0 + cohorts$treatment[cohorts$cohortDefinitionId == targetId] <- 1 + cohorts$cohortDefinitionId <- NULL + treatedPersons <- length(unique(cohorts$subjectId[cohorts$treatment == 1])) + comparatorPersons <- length(unique(cohorts$subjectId[cohorts$treatment == 0])) + treatedExposures <- length(cohorts$subjectId[cohorts$treatment == 1]) + comparatorExposures <- length(cohorts$subjectId[cohorts$treatment == 0]) + counts <- data.frame(description = ""Starting cohorts"", + treatedPersons = treatedPersons, + comparatorPersons = comparatorPersons, + treatedExposures = treatedExposures, + comparatorExposures = comparatorExposures) + metaData <- list(targetId = targetId, comparatorId = comparatorId, attrition = counts) + attr(cohorts, ""metaData"") <- metaData + + # Subsetting outcomes + ffbase::load.ffdf(dir = file.path(workFolder, ""allOutcomes"")) + ff::open.ffdf(outcomes, readonly = TRUE) + idx <- !is.na(ffbase::ffmatch(outcomes$rowId, ff::as.ff(cohorts$rowId))) + if (ffbase::any.ff(idx)) { + outcomes <- ff::as.ram(outcomes[ffbase::ffwhich(idx, idx == TRUE), ]) + } else { + outcomes <- as.data.frame(outcomes[1, ]) + outcomes <- outcomes[T == F, ] + } + metaData <- data.frame(outcomeIds = unique(outcomes$outcomeId)) + attr(outcomes, ""metaData"") <- metaData + + # Subsetting covariates + covariateData <- FeatureExtraction::loadCovariateData(file.path(workFolder, ""allCovariates"")) + idx <- is.na(ffbase::ffmatch(covariateData$covariates$rowId, ff::as.ff(cohorts$rowId))) + covariates <- covariateData$covariates[ffbase::ffwhich(idx, idx == FALSE), ] + + # Filtering covariates + filterConcepts <- readRDS(file.path(workFolder, ""filterConceps.rds"")) + filterConcepts <- filterConcepts[filterConcepts$exposureId %in% c(targetId, comparatorId), ] + filterConceptIds <- unique(filterConcepts$filterConceptId) + idx <- is.na(ffbase::ffmatch(covariateData$covariateRef$conceptId, ff::as.ff(filterConceptIds))) + covariateRef <- covariateData$covariateRef[ffbase::ffwhich(idx, idx == TRUE), ] + filterCovariateIds <- covariateData$covariateRef$covariateId[ffbase::ffwhich(idx, idx == FALSE), ] + idx <- is.na(ffbase::ffmatch(covariates$covariateId, filterCovariateIds)) + covariates <- covariates[ffbase::ffwhich(idx, idx == TRUE), ] + + result <- list(cohorts = cohorts, + outcomes = outcomes, + covariates = covariates, + covariateRef = covariateRef, + metaData = covariateData$metaData) + + class(result) <- ""cohortMethodData"" + return(result) +} + +generateAllCohortMethodDataObjectsNoInjection <- function(workFolder) { + writeLines(""Constructing cohortMethodData objects"") + start <- Sys.time() + exposureSummary <- read.csv(file.path(workFolder, ""exposureSummaryFilteredBySize.csv"")) + pb <- txtProgressBar(style = 3) + for (i in 1:nrow(exposureSummary)) { + targetId <- exposureSummary$tprimeCohortDefinitionId[i] + comparatorId <- exposureSummary$cprimeCohortDefinitionId[i] + targetConceptId <- exposureSummary$tCohortDefinitionId[i] + comparatorConceptId <- exposureSummary$cCohortDefinitionId[i] + folderName <- file.path(workFolder, + ""cmOutput"", + paste0(""CmData_l1_t"", targetId, ""_c"", comparatorId, ""_no_inj"")) + if (!file.exists(folderName)) { + cmData <- constructCohortMethodDataObjectNoInjection(targetId = targetId, + comparatorId = comparatorId, + targetConceptId = targetConceptId, + comparatorConceptId = comparatorConceptId, + workFolder = workFolder) + CohortMethod::saveCohortMethodData(cmData, folderName) + } + setTxtProgressBar(pb, i/nrow(exposureSummary)) + } + close(pb) + delta <- Sys.time() - start + writeLines(paste(""Generating all CohortMethodData objects took"", + signif(delta, 3), + attr(delta, ""units""))) +} + +fitAllPsModels <- function(workFolder, fitThreads = 1, cvThreads = 4) { + writeLines(""Fitting propensity models"") + exposureSummary <- read.csv(file.path(workFolder, ""exposureSummaryFilteredBySize.csv"")) + tasks <- list() + for (i in 1:nrow(exposureSummary)) { + targetId <- exposureSummary$tprimeCohortDefinitionId[i] + comparatorId <- exposureSummary$cprimeCohortDefinitionId[i] + folderName <- file.path(workFolder, + ""cmOutput"", + paste0(""CmData_l1_t"", targetId, ""_c"", comparatorId, ""_no_inj"")) + fileName <- file.path(workFolder, + ""cmOutput"", + paste0(""Ps_l1_s1_p2_t"", targetId, ""_c"", comparatorId, "".rds"")) + if (!file.exists(fileName)) { + task <- data.frame(folderName = folderName, + fileName = fileName, + cvThreads = cvThreads, + stringsAsFactors = FALSE) + tasks[[length(tasks) + 1]] <- task + } + } + + fitPropensityModel <- function(task) { + cmData <- CohortMethod::loadCohortMethodData(task$folderName) + studyPop <- CohortMethod::createStudyPopulation(cohortMethodData = cmData, + firstExposureOnly = FALSE, + washoutPeriod = 0, + removeDuplicateSubjects = FALSE, + removeSubjectsWithPriorOutcome = FALSE, + priorOutcomeLookback = 99999, + minDaysAtRisk = 1, + riskWindowStart = 0, + addExposureDaysToStart = FALSE, + riskWindowEnd = 0, + addExposureDaysToEnd = TRUE) + ps <- CohortMethod::createPs(cohortMethodData = cmData, + population = studyPop, + stopOnError = FALSE, + control = Cyclops::createControl(noiseLevel = ""quiet"", + cvType = ""auto"", + tolerance = 2e-07, + cvRepetitions = 1, + startingVariance = 0.01, + threads = task$cvThreads, + seed = 1)) + saveRDS(ps, task$fileName) + } + cluster <- OhdsiRTools::makeCluster(fitThreads) + OhdsiRTools::clusterRequire(cluster, ""Cyclops"") + OhdsiRTools::clusterRequire(cluster, ""CohortMethod"") + dummy <- OhdsiRTools::clusterApply(cluster, tasks, fitPropensityModel, stopOnError = TRUE) + OhdsiRTools::stopCluster(cluster) +} +options(fftempdir = ""S:/fftemp"") +workFolder <- ""s:/PopEstDepression_Ccae"" + +generateAllCohortMethodDataObjectsNoInjection(workFolder) + +fitAllPsModels(workFolder, fitThreads = 2, cvThreads = 10) + + + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","LargeScalePopEst/extras/MetaAnalysis.R",".R","3617","76","require(meta) + +folder <- ""s:/temp/Depression"" +calibrated <- read.csv(file.path(folder, ""DepressionResults.csv"")) +calibrated <- calibrated[calibrated$analysisId == 3, ] + +performMa <- function(i, tcos, calibrated) { + tco <- tcos[i, ] + subset <- calibrated[calibrated$targetId == tco$targetId & + calibrated$comparatorId == tco$comparatorId & + calibrated$outcomeName == tco$outcomeName, c(""logRr"", ""seLogRr"")] + subset <- subset[!is.na(subset$seLogRr), ] + if (nrow(subset) != 4) + return(NULL) + meta <- meta::metagen(subset$logRr, subset$seLogRr, sm = ""RR"") + s <- summary(meta)$random + result <- data.frame(targetId = tco$targetId, + comparatorId = tco$comparatorId, + outcomeId = tco$outcomeId, + targetName = tco$targetName, + comparatorName = tco$comparatorName, + outcomeName = tco$outcomeName, + outcomeType = tco$outcomeType, + trueRr = tco$trueRr, + rr = exp(s$TE), + ci95lb = exp(s$lower), + ci95ub = exp(s$upper), + logRr = s$TE, + seLogRr = (s$upper - s$lower)/(2*qnorm(0.975)), + i2 = meta$I2) + return(result) +} + +calibrated$outcomeId[calibrated$outcomeType == ""positive control""] <- NA +tcos <- unique(calibrated[, c(""targetId"", ""comparatorId"", ""outcomeId"", ""targetName"", ""comparatorName"", ""outcomeName"", ""outcomeType"", ""trueRr"")]) +meta <- lapply(1:nrow(tcos), performMa, tcos = tcos, calibrated = calibrated) +meta <- do.call(""rbind"", meta) + +write.csv(meta, file.path(folder, ""MetaAnalysis.csv""), row.names = FALSE) + + +calibrateMa <- function(i, tcs, meta) { + tc <- tcs[i, ] + subset <- meta[meta$targetId == tc$targetId & meta$comparatorId == tc$comparatorId, ] + + negControls <- subset[!is.na(subset$trueRr) & subset$trueRr == 1, ] + null <- EmpiricalCalibration::fitMcmcNull(logRr = negControls$logRr, + seLogRr = negControls$seLogRr) + calibratedP <- EmpiricalCalibration::calibrateP(null = null, + logRr = subset$logRr, + seLogRr = subset$seLogRr) + subset$calP <- calibratedP$p + subset$calPlb <- calibratedP$lb95ci + subset$calPub <- calibratedP$ub95ci + + controls <- subset[!is.na(subset$trueRr), ] + model <- EmpiricalCalibration::fitSystematicErrorModel(logRr = controls$logRr, + seLogRr = controls$seLogRr, + trueLogRr = log(controls$trueRr)) + calibratedCi <- EmpiricalCalibration::calibrateConfidenceInterval(logRr = subset$logRr, + seLogRr = subset$seLogRr, + model = model) + subset$calLogRr <- calibratedCi$logRr + subset$calSeLogRr <- calibratedCi$seLogRr + subset$calRr <- exp(calibratedCi$logRr) + subset$calCi95lb <- exp(calibratedCi$logLb95Rr) + subset$calCi95ub <- exp(calibratedCi$logUb95Rr) + return(subset) +} + +tcs <- unique(meta[, c(""targetId"", ""comparatorId"")]) +metaCalibrated <- lapply(1:nrow(tcs), calibrateMa, tcs = tcs, meta = meta) +metaCalibrated <- do.call(""rbind"", metaCalibrated) + +write.csv(meta, file.path(folder, ""MetaAnalysisCalibrated.csv""), row.names = FALSE) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","LargeScalePopEst/extras/TestSignalInjection.R",".R","10206","202","library(LargeScalePopEst) + +options(fftempdir = ""S:/fftemp"") +workFolder <- ""S:/PopEstDepression_Mdcd"" + +exposureSummary <- read.csv(file.path(workFolder, ""exposureSummaryFilteredBySize.csv"")) +injectionSummary <- read.csv(file.path(workFolder, ""signalInjectionSummary.csv"")) + +newRows <- data.frame() +for (i in 1:nrow(exposureSummary)) { + targetId <- exposureSummary$tprimeCohortDefinitionId[i] + comparatorId <- exposureSummary$cprimeCohortDefinitionId[i] + targetConceptId <- exposureSummary$tCohortDefinitionId[i] + comparatorConceptId <- exposureSummary$cCohortDefinitionId[i] + + folderName <- file.path(workFolder, + ""cmOutput"", + paste0(""CmData_l1_t"", targetId, ""_c"", comparatorId)) + cmData <- CohortMethod::loadCohortMethodData(folderName) + + cmData <- LargeScalePopEst:::constructCohortMethodDataObject(targetId = targetId, + comparatorId = comparatorId, + targetConceptId = targetConceptId, + comparatorConceptId = comparatorConceptId, + workFolder = workFolder) + rows <- injectionSummary[injectionSummary$exposureId == targetConceptId, ] + rows$observedFxSize <- NA + rows$observedFxSize_lb <- NA + rows$observedFxSize_ub <- NA + + for (j in 1:nrow(rows)) { + if (rows$trueEffectSize[j] != 0) { + sp1 <- CohortMethod::createStudyPopulation(cohortMethodData = cmData, + outcomeId = rows$outcomeId[j], + removeSubjectsWithPriorOutcome = TRUE, + minDaysAtRisk = 0, + riskWindowStart = 0, + riskWindowEnd = 0, + addExposureDaysToEnd = TRUE) + sp2 <- CohortMethod::createStudyPopulation(cohortMethodData = cmData, + outcomeId = rows$newOutcomeId[j], + removeSubjectsWithPriorOutcome = TRUE, + minDaysAtRisk = 0, + riskWindowStart = 0, + riskWindowEnd = 0, + addExposureDaysToEnd = TRUE) + sp2 <- sp2[sp2$treatment == 1, ] + sp1 <- sp1[sp1$treatment == 1, ] + sp1$treatment <- 0 + sp1$rowId <- sp1$rowId + max(sp2$rowId) + sp <- rbind(sp1, sp2) + om <- CohortMethod::fitOutcomeModel(sp, + cohortMethodData = cmData, + modelType = ""cox"", + stratified = FALSE, + useCovariates = FALSE) + rows$observedFxSize[j] <- exp(coef(om)) + rows$observedFxSize_lb[j] <- exp(confint(om)[1]) + rows$observedFxSize_ub[j] <- exp(confint(om)[2]) + } + } + newRows <- rbind(newRows, rows) +} + +x <- rows[, c(""targetEffectSize"", ""observedFxSize"", ""observedFxSize_lb"", ""observedFxSize_ub"")] + + +MethodEvaluation:::generateOutcomes + + +exposureOutcomePairs <- data.frame(exposureId = 739138, outcomeId = 75354) +debug(injectSignals) +injectSignals(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + workDatabaseSchema = workDatabaseSchema, + studyCohortTable = studyCohortTable, + oracleTempSchema = oracleTempSchema, + workFolder = workFolder, + exposureOutcomePairs = exposureOutcomePairs, + maxCores = maxCores) + +cmData <- LargeScalePopEst:::constructCohortMethodDataObject(targetId = 739138112, + comparatorId = 797617112, + targetConceptId = 739138, + comparatorConceptId = 797617, + workFolder = workFolder) + +cmData <- constructCustomCohortMethodDataObject(targetConceptId = 739138, workFolder = workFolder) + + + +sp1 <- CohortMethod::createStudyPopulation(cohortMethodData = cmData, + outcomeId = 75354, + removeSubjectsWithPriorOutcome = TRUE, + minDaysAtRisk = 0, + riskWindowStart = 0, + riskWindowEnd = 0, + addExposureDaysToEnd = TRUE) + +sp2 <- CohortMethod::createStudyPopulation(cohortMethodData = cmData, + outcomeId = 10328, + removeSubjectsWithPriorOutcome = TRUE, + minDaysAtRisk = 0, + riskWindowStart = 0, + riskWindowEnd = 0, + addExposureDaysToEnd = TRUE) + +sp2 <- sp2[sp2$treatment == 1, ] + +sp1 <- sp1[sp1$treatment == 1, ] +sp1$treatment <- 0 +sp1$rowId <- sp1$rowId + max(sp2$rowId) + +sp <- rbind(sp1, sp2) +om <- CohortMethod::fitOutcomeModel(sp, + cohortMethodData = cmData, + modelType = ""cox"", + stratified = FALSE, + useCovariates = FALSE) +om +s <- summary(om) +(s$outcomeCounts$treatedPersons/(s$timeAtRisk$treatedDays + s$populationCounts$treatedPersons))/(s$outcomeCounts$comparatorPersons/(s$timeAtRisk$comparatorDays + s$populationCounts$comparatorPersons)) +(s$outcomeCounts$treatedPersons/s$timeAtRisk$treatedDays)/(s$outcomeCounts$comparatorPersons/s$timeAtRisk$comparatorDays) +no <- readRDS(""S:/PopEstDepression_Mdcd/signalInjection/newOutcomes_e739138_o75354_rr2.rds"") +no[!(no$subjectId %in% sp2$subjectId[sp2$outcomeCount != 0]), ] + + +constructCustomCohortMethodDataObject <- function(targetConceptId, workFolder) { + exposureSummary <- read.csv(file.path(workFolder, ""exposureSummaryFilteredBySize.csv"")) + targetIds <- exposureSummary$tprimeCohortDefinitionId[exposureSummary$tCohortDefinitionId == targetConceptId] + # Subsetting cohorts + ffbase::load.ffdf(dir = file.path(workFolder, ""allCohorts"")) + ff::open.ffdf(cohorts, readonly = TRUE) + idx <- ffbase::""%in%""(cohorts$cohortDefinitionId, targetIds) + cohorts <- ff::as.ram(cohorts[ffbase::ffwhich(idx, idx == TRUE), ]) + cohorts$treatment <- 1 + cohorts$cohortDefinitionId <- NULL + cohorts <- cohorts[order(cohorts$rowId), ] + cohorts <- cohorts[!duplicated(cohorts$rowId), ] + treatedPersons <- length(unique(cohorts$subjectId[cohorts$treatment == 1])) + comparatorPersons <- length(unique(cohorts$subjectId[cohorts$treatment == 0])) + treatedExposures <- length(cohorts$subjectId[cohorts$treatment == 1]) + comparatorExposures <- length(cohorts$subjectId[cohorts$treatment == 0]) + counts <- data.frame(description = ""Starting cohorts"", + treatedPersons = treatedPersons, + comparatorPersons = comparatorPersons, + treatedExposures = treatedExposures, + comparatorExposures = comparatorExposures) + metaData <- list(targetId = targetConceptId, comparatorId = 0, attrition = counts) + attr(cohorts, ""metaData"") <- metaData + + # Subsetting outcomes + ffbase::load.ffdf(dir = file.path(workFolder, ""allOutcomes"")) + ff::open.ffdf(outcomes, readonly = TRUE) + idx <- !is.na(ffbase::ffmatch(outcomes$rowId, ff::as.ff(cohorts$rowId))) + if (ffbase::any.ff(idx)) { + outcomes <- ff::as.ram(outcomes[ffbase::ffwhich(idx, idx == TRUE), ]) + } else { + outcomes <- as.data.frame(outcomes[1, ]) + outcomes <- outcomes[T == F, ] + } + x <- outcomes[outcomes$outcomeId == 75354 & outcomes$daysToEvent < 0, ] + length(unique(x$rowId)) + sum(!(cohorts$rowId %in% unique(x$rowId))) + # Add injected outcomes + ffbase::load.ffdf(dir = file.path(workFolder, ""injectedOutcomes"")) + ff::open.ffdf(injectedOutcomes, readonly = TRUE) + injectionSummary <- read.csv(file.path(workFolder, ""signalInjectionSummary.csv"")) + injectionSummary <- injectionSummary[injectionSummary$exposureId == targetConceptId, ] + idx1 <- ffbase::""%in%""(injectedOutcomes$subjectId, cohorts$subjectId) + idx2 <- ffbase::""%in%""(injectedOutcomes$cohortDefinitionId, injectionSummary$newOutcomeId) + idx <- idx1 & idx2 + if (ffbase::any.ff(idx)) { + injectedOutcomes <- ff::as.ram(injectedOutcomes[idx, ]) + colnames(injectedOutcomes)[colnames(injectedOutcomes) == ""cohortStartDate""] <- ""eventDate"" + colnames(injectedOutcomes)[colnames(injectedOutcomes) == ""cohortDefinitionId""] <- ""outcomeId"" + injectedOutcomes <- merge(cohorts[, + c(""rowId"", ""subjectId"", ""cohortStartDate"")], + injectedOutcomes[, + c(""subjectId"", ""outcomeId"", ""eventDate"")]) + injectedOutcomes$daysToEvent <- injectedOutcomes$eventDate - injectedOutcomes$cohortStartDate + # any(injectedOutcomes$daysToEvent < 0) min(outcomes$daysToEvent[outcomes$outcomeId == 73008]) + outcomes <- rbind(outcomes, injectedOutcomes[, c(""rowId"", ""outcomeId"", ""daysToEvent"")]) + } + metaData <- data.frame(outcomeIds = unique(outcomes$outcomeId)) + attr(outcomes, ""metaData"") <- metaData + + # Subsetting covariates + covariateData <- FeatureExtraction::loadCovariateData(file.path(workFolder, ""allCovariates"")) + idx <- is.na(ffbase::ffmatch(covariateData$covariates$rowId, ff::as.ff(cohorts$rowId))) + covariates <- covariateData$covariates[ffbase::ffwhich(idx, idx == FALSE), ] + + + result <- list(cohorts = cohorts, + outcomes = outcomes, + covariates = covariates, + metaData = covariateData$metaData) + + class(result) <- ""cohortMethodData"" + return(result) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","LargeScalePopEst/extras/SharedPlots.R",".R","15603","297","require(ggplot2) + +plotScatter <- function(d, size = 1, yPanelGroup = FALSE, labelY = 0.8) { + d <- d[!is.na(d$logRr), ] + d <- d[!is.na(d$ci95lb), ] + d <- d[!is.na(d$ci95ub), ] + if (nrow(d) == 0) { + return(NULL) + } + d$Group <- as.factor(d$trueRr) + d$Significant <- d$ci95lb > d$trueRr | d$ci95ub < d$trueRr + + + if (yPanelGroup) { + temp1 <- aggregate(Significant ~ Group + yGroup, data = d, length) + temp2 <- aggregate(Significant ~ Group + yGroup, data = d, mean) + } else { + temp1 <- aggregate(Significant ~ Group, data = d, length) + temp2 <- aggregate(Significant ~ Group, data = d, mean) + } + temp1$nLabel <- paste0(formatC(temp1$Significant, big.mark = "",""), "" estimates"") + temp1$Significant <- NULL + + temp2$meanLabel <- paste0(formatC(100 * (1 - temp2$Significant), digits = 1, format = ""f""), + ""% of CIs include "", + temp2$Group) + temp2$Significant <- NULL + dd <- merge(temp1, temp2) + dd$tes <- as.numeric(as.character(dd$Group)) + + #breaks <- c(0.25, 0.5, 1, 2, 4, 6, 8, 10) + breaks <- c(0.1, 0.25, 0.5, 1, 2, 4, 6, 8, 10) + theme <- element_text(colour = ""#000000"", size = 12) + themeRA <- element_text(colour = ""#000000"", size = 12, hjust = 1) + themeLA <- element_text(colour = ""#000000"", size = 12, hjust = 0) + + d$Group <- paste(""True hazard ratio ="", d$Group) + dd$Group <- paste(""True hazard ratio ="", dd$Group) + alpha <- 1 - min(0.95*(nrow(d)/nrow(dd)/50000)^0.1, 0.95) + plot <- ggplot(d, aes(x = logRr, y= seLogRr), environment = environment()) + + geom_vline(xintercept = log(breaks), colour = ""#AAAAAA"", lty = 1, size = 0.5) + + geom_abline(aes(intercept = (-log(tes))/qnorm(0.025), slope = 1/qnorm(0.025)), colour = rgb(0.8, 0, 0), linetype = ""dashed"", size = 1, alpha = 0.5, data = dd) + + geom_abline(aes(intercept = (-log(tes))/qnorm(0.975), slope = 1/qnorm(0.975)), colour = rgb(0.8, 0, 0), linetype = ""dashed"", size = 1, alpha = 0.5, data = dd) + + geom_point(size = size, color = rgb(0, 0, 0, alpha = 0.05), alpha = alpha, shape = 16) + + geom_hline(yintercept = 0) + + #geom_label(x = log(0.3), y = 0.95, alpha = 1, hjust = ""left"", aes(label = nLabel), size = 5, data = dd) + + geom_label(x = log(0.15), y = 0.90, alpha = 1, hjust = ""left"", aes(label = nLabel), size = 5, data = dd) + + #geom_label(x = log(0.3), y = 0.8, alpha = 1, hjust = ""left"", aes(label = meanLabel), size = 5, data = dd) + + geom_label(x = log(0.15), y = labelY, alpha = 1, hjust = ""left"", aes(label = meanLabel), size = 5, data = dd) + + #scale_x_continuous(""Hazard ratio"", limits = log(c(0.25, 10)), breaks = log(breaks), labels = breaks) + + scale_x_continuous(""Hazard ratio"", limits = log(c(0.1, 10)), breaks = log(breaks), labels = breaks) + + scale_y_continuous(""Standard Error"", limits = c(0, 1)) + + theme(panel.grid.minor = element_blank(), + panel.background = element_blank(), + panel.grid.major = element_blank(), + axis.ticks = element_blank(), + axis.text.y = themeRA, + axis.text.x = theme, + axis.title = theme, + legend.key = element_blank(), + strip.text.x = theme, + strip.text.y = theme, + strip.background = element_blank(), + legend.position = ""none"") + + if (yPanelGroup) { + plot <- plot + facet_grid(yGroup ~ Group) + } else { + plot <- plot + facet_grid(. ~ Group) + } + return(plot) +} + + + +plotCiCalibration <- function(d) { + + # data <- d[d$targetId == 750982076 & d$comparatorId ==721724076, ] + # data <- d[d$comparatorName == ""Psychotherapy"", ] + data <- d + data$trueLogRr <- log(data$trueRr) + data$strata = as.factor(data$trueLogRr) + if (any(is.infinite(data$seLogRr))) { + warning(""Estimate(s) with infinite standard error detected. Removing before fitting error model"") + data <- data[!is.infinite(data$seLogRr), ] + } + if (any(is.infinite(data$logRr))) { + warning(""Estimate(s) with infinite logRr detected. Removing before fitting error model"") + data <- data[!is.infinite(data$logRr), ] + } + if (any(is.na(data$seLogRr))) { + warning(""Estimate(s) with NA standard error detected. Removing before fitting error model"") + data <- data[!is.na(data$seLogRr), ] + } + if (any(is.na(data$logRr))) { + warning(""Estimate(s) with NA logRr detected. Removing before fitting error model"") + data <- data[!is.na(data$logRr), ] + } + #data <- data[sample.int(nrow(data), 1000),] + + + computeLooCoverage <- function(i, data, result) { + computeCoverage <- function(j, subResult, dataLeftOut, model) { + subset <- dataLeftOut[dataLeftOut$strata == subResult$strata[j],] + if (nrow(subset) == 0) + return(0) + ci <- EmpiricalCalibration::calibrateConfidenceInterval(logRr = subset$logRr, + seLogRr = subset$seLogRr, + ciWidth = subResult$ciWidth[j], + model = model) + return(sum(ci$logLb95Rr <= subset$trueLogRr & ci$logUb95Rr >= subset$trueLogRr)) + } + computeTheoreticalCoverage <- function(j, subResult, dataLeftOut) { + subset <- dataLeftOut[dataLeftOut$strata == subResult$strata[j],] + ciWidth <- subResult$ciWidth[j] + return(sum((subset$trueLogRr >= subset$logRr + qnorm((1-ciWidth)/2)*subset$seLogRr) & (subset$trueLogRr <= subset$logRr - qnorm((1-ciWidth)/2)*subset$seLogRr))) + } + tcdbIndex <- data$targetId == result$targetId[i] & data$comparatorId == result$comparatorId[i] & data$db == result$db[i] + dataLeaveOneOut <- data[tcdbIndex & data$group != result$leaveOutGroup[i], ] + dataLeftOut <- data[tcdbIndex & data$group == result$leaveOutGroup[i], ] + if (nrow(dataLeaveOneOut) == 0 || nrow(dataLeftOut) == 0) + return(data.frame()) + + model <- EmpiricalCalibration::fitSystematicErrorModel(logRr = dataLeaveOneOut$logRr, + seLogRr = dataLeaveOneOut$seLogRr, + trueLogRr = dataLeaveOneOut$trueLogRr, + estimateCovarianceMatrix = FALSE) + + strata <- unique(data$strata) + ciWidth <- seq(0.01, 0.99, by = 0.01) + + subResult <- expand.grid(strata, ciWidth) + names(subResult) <- c(""strata"", ""ciWidth"") + subResult$coverage <- sapply(1:nrow(subResult), computeCoverage, subResult = subResult, dataLeftOut = dataLeftOut, model = model) + subResult$theoreticalCoverage <- sapply(1:nrow(subResult), computeTheoreticalCoverage, subResult = subResult, dataLeftOut = dataLeftOut) + #subResult$leaveOutGroup <- rep(leaveOutGroup, nrow(subResult)) + return(subResult) + } + writeLines(""Fitting error models within leave-one-out cross-validation"") + tcdbs <- unique(data[, c(""targetId"", ""comparatorId"", ""db"")]) + + # tcdbs <- tcdbs[sample.int(nrow(tcdbs), 10),] + # temp <- data + # data <- merge(data, tcdbs) + #data <- temp + leaveOutGroups <- unique(data$group) + result <- data.frame(targetId = rep(tcdbs$targetId, length(leaveOutGroups)), + comparatorId = rep(tcdbs$comparatorId, length(leaveOutGroups)), + db = rep(tcdbs$db, length(leaveOutGroups)), + leaveOutGroup = rep(leaveOutGroups, each = nrow(tcdbs))) + + #rm(calibrated) + #rm(d) + cluster <- OhdsiRTools::makeCluster(15) + coverages <- OhdsiRTools::clusterApply(cluster, 1:nrow(result), computeLooCoverage, data = data, result = result) + OhdsiRTools::stopCluster(cluster) + #coverages <- lapply(unique(leaveOutGrouping), computeLooCoverage, data = data) + coverage <- do.call(""rbind"", coverages) + data$count <- 1 + counts <- aggregate(count ~ strata, data = data, sum) + naCounts <- aggregate(coverage ~ strata + ciWidth, data = coverage, function(x) sum(is.na(x)), na.action = na.pass) + colnames(naCounts)[colnames(naCounts) == ""coverage""] <- ""naCount"" + coverageCali <- aggregate(coverage ~ strata + ciWidth, data = coverage, sum) + coverageCali <- merge(coverageCali, counts, by = ""strata"") + coverageCali <- merge(coverageCali, naCounts, by = c(""strata"", ""ciWidth"")) + coverageCali$coverage <- coverageCali$coverage / (coverageCali$count - coverageCali$naCount) + coverageCali$label <- ""Calibrated"" + coverageTheoretical <- aggregate(theoreticalCoverage ~ strata + ciWidth, data = coverage, sum, na.action = na.pass) + coverageTheoretical <- merge(coverageTheoretical, counts, by = ""strata"") + coverageTheoretical$coverage <- coverageTheoretical$theoreticalCoverage / coverageCali$count + coverageTheoretical$label <- ""Uncalibrated"" + vizData <- rbind(coverageCali[, c(""strata"", ""label"", ""ciWidth"", ""coverage"")], + coverageTheoretical[, c(""strata"", ""label"", ""ciWidth"", ""coverage"")]) + + names(vizData)[names(vizData) == ""label""] <- ""CI calculation"" + vizData$trueRr <- as.factor(exp(as.numeric(as.character(vizData$strata)))) + breaks <- c(0, 0.25, 0.5, 0.75, 1) + theme <- ggplot2::element_text(colour = ""#000000"", size = 10) + themeRA <- ggplot2::element_text(colour = ""#000000"", size = 10, hjust = 1) + #saveRDS(vizData, file.path(paperFolder, ""vizData.rds"")) + plot <- with(vizData, { + ggplot2::ggplot(vizData, + ggplot2::aes(x = ciWidth, + y = coverage, + colour = `CI calculation`, + linetype = `CI calculation`), + environment = environment()) + + ggplot2::geom_vline(xintercept = breaks, + colour = ""#AAAAAA"", + lty = 1, + size = 0.3) + + ggplot2::geom_vline(xintercept = 0.95, colour = ""#888888"", linetype = ""dashed"", size = 1) + + ggplot2::geom_hline(yintercept = breaks, colour = ""#AAAAAA"", lty = 1, size = 0.3) + + ggplot2::geom_abline(colour = ""#AAAAAA"", lty = 1, size = 0.3) + + ggplot2::geom_line(size = 1) + + ggplot2::scale_colour_manual(values = c(rgb(0, 0, 0), rgb(0, 0, 0), rgb(0.5, 0.5, 0.5))) + + ggplot2::scale_linetype_manual(values = c(""solid"", ""twodash"")) + + ggplot2::scale_x_continuous(""Width of CI"", limits = c(0, 1), breaks = c(breaks, 0.95), labels = c(""0"", "".25"", "".50"", "".75"", """", "".95"")) + + ggplot2::scale_y_continuous(""Coverage"", limits = c(0, 1), breaks = breaks, labels = c(""0"", "".25"", "".50"", "".75"", ""1"")) + + ggplot2::facet_grid(. ~ trueRr) + + ggplot2::theme(panel.grid.minor = ggplot2::element_blank(), + panel.background = ggplot2::element_rect(fill = ""#FAFAFA"", colour = NA), + panel.grid.major = ggplot2::element_blank(), + axis.ticks = ggplot2::element_blank(), + axis.text.y = themeRA, + axis.text.x = theme, + strip.text.x = theme, + strip.background = ggplot2::element_blank(), + legend.position = ""top"") + }) + + return(plot) +} + +plotPs <- function(data, + unfilteredData = NULL, + scale = ""preference"", + type = ""density"", + binWidth = 0.05, + treatmentLabel = ""Treated"", + comparatorLabel = ""Comparator"", + legenPosition = ""top"", + fileName = NULL) { + if (!(""treatment"" %in% colnames(data))) + stop(""Missing column treatment in data"") + if (!(""propensityScore"" %in% colnames(data))) + stop(""Missing column propensityScore in data"") + if (!is.null(unfilteredData)) { + if (!(""treatment"" %in% colnames(unfilteredData))) + stop(""Missing column treatment in unfilteredData"") + if (!(""propensityScore"" %in% colnames(unfilteredData))) + stop(""Missing column propensityScore in unfilteredData"") + } + if (type != ""density"" && type != ""histogram"") + stop(paste(""Unknown type '"", type, ""', please choose either 'density' or 'histogram'""), + sep = """") + if (scale != ""propensity"" && scale != ""preference"") + stop(paste(""Unknown scale '"", scale, ""', please choose either 'propensity' or 'preference'""), + sep = """") + + if (scale == ""preference"") { + data <- computePreferenceScore(data, unfilteredData) + data$SCORE <- data$preferenceScore + label <- ""Preference score"" + } else { + data$SCORE <- data$propensityScore + label <- ""Propensity score"" + } + data$GROUP <- treatmentLabel + data$GROUP[data$treatment == 0] <- comparatorLabel + data$GROUP <- factor(data$GROUP, levels = c(treatmentLabel, comparatorLabel)) + if (type == ""density"") { + plot <- ggplot2::ggplot(data, + ggplot2::aes(x = SCORE, color = GROUP, group = GROUP, fill = GROUP)) + + ggplot2::geom_density() + + ggplot2::scale_fill_manual(values = c(rgb(0.8, 0, 0, alpha = 0.5), + rgb(0, 0, 0.8, alpha = 0.5))) + + ggplot2::scale_color_manual(values = c(rgb(0.8, 0, 0, alpha = 0.5), + rgb(0, 0, 0.8, alpha = 0.5))) + + ggplot2::scale_x_continuous(label, limits = c(0, 1)) + + ggplot2::scale_y_continuous(""Density"") + + ggplot2::theme(legend.title = ggplot2::element_blank(), + legend.position = legenPosition) + if (!is.null(attr(data, ""strata""))) { + strata <- data.frame(propensityScore = attr(data, ""strata"")) + if (scale == ""preference"") { + if (is.null(unfilteredData)) { + strata <- computePreferenceScore(strata, data) + } else { + strata <- computePreferenceScore(strata, unfilteredData) + } + strata$SCORE <- strata$preferenceScore + } else { + strata$SCORE <- strata$propensityScore + } + plot <- plot + + ggplot2::geom_vline(xintercept = strata$SCORE, color = rgb(0, 0, 0, alpha = 0.5)) + } + } else { + plot <- ggplot2::ggplot(data, + ggplot2::aes(x = SCORE, color = GROUP, group = GROUP, fill = GROUP)) + + ggplot2::geom_histogram(binwidth = binWidth, position = ""identity"") + + ggplot2::scale_fill_manual(values = c(rgb(0.8, 0, 0, alpha = 0.5), + rgb(0, 0, 0.8, alpha = 0.5))) + + ggplot2::scale_color_manual(values = c(rgb(0.8, 0, 0, alpha = 0.5), + rgb(0, 0, 0.8, alpha = 0.5))) + + ggplot2::scale_x_continuous(label, limits = c(0, 1)) + + ggplot2::scale_y_continuous(""Number of subjects"") + + ggplot2::theme(legend.title = ggplot2::element_blank(), + legend.position = legenPosition) + } + + if (!is.null(fileName)) + ggplot2::ggsave(fileName, plot, width = 3.5, height = 2.5, dpi = 400) + return(plot) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","LargeScalePopEst/extras/FixShinyData.R",".R","1067","29","# Swap ggplot figures with underlying data to make more robust against changes in ggplot2: + +dataFolder <- ""C:/Users/mschuemi/git/ShinyDeploy/SystematicEvidence/data"" + + +# Fix details evaluation and calibration plots ---------------------------------- +# source(""extras/SharedPlots.R"") +files <- list.files(dataFolder, ""details"") +file <- files[1] +for (file in files) { + # targetName <- gsub(""_.*"", """", gsub(""details_"", """", file)) + # comparatorName <- gsub(""_.*"", """", gsub(""details_[^_]*_"", """", file)) + # db <- gsub("".rds$"", """", gsub(""details_[^_]*_[^_]*_"", """", file)) + details <- readRDS(file.path(dataFolder, file)) + + controls <- details$evaluationPlot$data + controls <- controls[, c(""trueRr"", ""logRr"", ""ci95lb"", ""ci95ub"", ""seLogRr"")] + details$controlEstimates <- controls + + controls <- details$calibrationPlot$data + controls <- controls[, c(""trueRr"", ""logRr"", ""ci95lb"", ""ci95ub"", ""seLogRr"")] + details$controlCalibratedEstimates <- controls + + details$evaluationPlot <- NULL + details$calibrationPlot <- NULL + + saveRDS(details, file.path(dataFolder, file)) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","UkaTkaSafetyEffectiveness/inst/shiny/EvidenceExplorer/global.R",".R","9020","116","source(""DataPulls.R"") +source(""PlotsAndTables.R"") + +shinySettings <- list(dataFolder = ""S:/StudyResults/UkaTkaSafetyFull/shinyDataAll"", blind = FALSE) +# shinySettings <- list(dataFolder = ""S:/StudyResults/UkaTkaSafetyFull_old_pos_control_synth/shinyDataAll"", blind = FALSE) +dataFolder <- shinySettings$dataFolder +blind <- shinySettings$blind +connection <- NULL +positiveControlOutcome <- NULL + +splittableTables <- c(""covariate_balance"", ""preference_score_dist"", ""kaplan_meier_dist"") + +files <- list.files(dataFolder, pattern = "".rds"") + +# Remove data already in global environment: +tableNames <- gsub(""(_t[0-9]+_c[0-9]+)|(_)[^_]*\\.rds"", """", files) +camelCaseNames <- SqlRender::snakeCaseToCamelCase(tableNames) +camelCaseNames <- unique(camelCaseNames) +camelCaseNames <- camelCaseNames[!(camelCaseNames %in% SqlRender::snakeCaseToCamelCase(splittableTables))] +rm(list = camelCaseNames) + +relabel <- function(var, oldLabel, newLabel) { + levels(var)[levels(var) == oldLabel] <- newLabel + return(var) +} + +# Load data from data folder: +loadFile <- function(file) { + # file = files[3] + tableName <- gsub(""(_t[0-9]+_c[0-9]+)*\\.rds"", """", file) + # tableName <- gsub(""(_t[0-9]+_c[0-9]+)|(_)[^_]*\\.rds"", """", file) + camelCaseName <- SqlRender::snakeCaseToCamelCase(tableName) + if (!(tableName %in% splittableTables)) { + newData <- readRDS(file.path(dataFolder, file)) + colnames(newData) <- SqlRender::snakeCaseToCamelCase(colnames(newData)) + if (exists(camelCaseName, envir = .GlobalEnv)) { + existingData <- get(camelCaseName, envir = .GlobalEnv) + newData <- rbind(existingData, newData) + } + if (!is.null(newData$databaseId)) { + newData$databaseId <- relabel(newData$databaseId, ""thin"", ""THIN"") + newData$databaseId <- relabel(newData$databaseId, ""pmtx"", ""PharMetrics"") + } + assign(camelCaseName, newData, envir = .GlobalEnv) + } + invisible(NULL) +} +lapply(files, loadFile) + +tcos <- unique(cohortMethodResult[, c(""targetId"", ""comparatorId"", ""outcomeId"")]) +tcos <- tcos[tcos$outcomeId %in% outcomeOfInterest$outcomeId, ] + +dbInfoHtml <- readChar(""DataSources.html"", file.info(""DataSources.html"")$size) +outcomesInfoHtml <- readChar(""Outcomes.html"", file.info(""Outcomes.html"")$size) +targetCohortsInfoHtml <- readChar(""TargetCohorts.html"", file.info(""TargetCohorts.html"")$size) +comparatorCohortsInfoHtml <- readChar(""ComparatorCohorts.html"", file.info(""ComparatorCohorts.html"")$size) +analysesInfoHtml <- readChar(""Analyses.html"", file.info(""Analyses.html"")$size) + + + +# exposures rename +exposureOfInterest$exposureName <- relabel(exposureOfInterest$exposureName, ""[OD4] Patients with unicompartmental knee replacement without limitation on hip-spine-foot pathology"", ""Unicompartmental knee replacement without hip-spine-foot pathology restriction"") +exposureOfInterest$exposureName <- relabel(exposureOfInterest$exposureName, ""[OD4] Patients with unicompartmental knee replacement"", ""Unicompartmental knee replacement"") +exposureOfInterest$exposureName <- relabel(exposureOfInterest$exposureName, ""[OD4] Patients with total knee replacement without limitation on hip-spine-foot pathology"", ""Total knee replacement without hip-spine-foot pathology restriction"") +exposureOfInterest$exposureName <- relabel(exposureOfInterest$exposureName, ""[OD4] Patients with total knee replacement"", ""Total knee replacement"") +exposureOfInterest$order <- match(exposureOfInterest$exposureName, c(""Unicompartmental knee replacement"", + ""Total knee replacement"", + ""Unicompartmental knee replacement without hip-spine-foot pathology restriction"", + ""Total knee replacement without hip-spine-foot pathology restriction"")) +exposureOfInterest <- exposureOfInterest[order(exposureOfInterest$order), ] + +# outcomes rename +outcomeOfInterest$outcomeName <- relabel(outcomeOfInterest$outcomeName, ""[OD4] Post operative infection events"", ""Post-operative infection"") +outcomeOfInterest$outcomeName <- relabel(outcomeOfInterest$outcomeName, ""[OD4] Venous thromboembolism events"", ""Venous thromboembolism"") +outcomeOfInterest$outcomeName <- relabel(outcomeOfInterest$outcomeName, ""[OD4] Mortality"", ""Mortality"") +outcomeOfInterest$outcomeName <- relabel(outcomeOfInterest$outcomeName, ""[OD4] Readmission after knee arthroplasty"", ""Readmission"") +outcomeOfInterest$outcomeName <- relabel(outcomeOfInterest$outcomeName, ""[OD4] Persons with knee arthroplasty revision"", ""Revision"") +outcomeOfInterest$outcomeName <- relabel(outcomeOfInterest$outcomeName, ""[OD4] Opioid use after arthroplasty"", ""Opioid use"") +outcomeOfInterest$order <- match(outcomeOfInterest$outcomeName, c(""Venous thromboembolism"", + ""Post-operative infection"", + ""Readmission"", + ""Mortality"", + ""Opioid use"", + ""Revision"")) +outcomeOfInterest <- outcomeOfInterest[order(outcomeOfInterest$order), ] + +# analyses rename +cohortMethodAnalysis$description <- relabel(cohortMethodAnalysis$description, ""1. PS matching variable ratio No trim TAR 60d"", ""10:1 variable ratio matching, 60 day time-at-risk"") +cohortMethodAnalysis$description <- relabel(cohortMethodAnalysis$description, ""2. PS matching variable ratio No trim TAR 1yr"", ""10:1 variable ratio matching, 1 year time-at-risk"") +cohortMethodAnalysis$description <- relabel(cohortMethodAnalysis$description, ""3. PS matching variable ratio No trim TAR 5yr"", ""10:1 variable ratio matching, 5 year time-at-risk"") +cohortMethodAnalysis$description <- relabel(cohortMethodAnalysis$description, ""4. PS matching variable ratio Trim 5% TAR 60d"", ""10:1 variable ratio matching 5% trim, 60 day time-at-risk"") +cohortMethodAnalysis$description <- relabel(cohortMethodAnalysis$description, ""5. PS matching 1-1 ratio No trim TAR 60d"", ""1:1 ratio matching, 60 day time-at-risk"") +cohortMethodAnalysis$description <- relabel(cohortMethodAnalysis$description, ""6. PS matching variable ratio Trim 5% TAR 5yr"", ""10:1 variable ratio matching 5% trim, 5 year time-at-risk"") +cohortMethodAnalysis$description <- relabel(cohortMethodAnalysis$description, ""7. PS matching 1-1 ratio No trim TAR 5yr"", ""1:1 ratio matching, 5 year time-at-risk"") +cohortMethodAnalysis$description <- relabel(cohortMethodAnalysis$description, ""8. PS matching variable ratio No trim TAR 91d-1yr"", ""10:1 variable ratio matching, 91 days to 1 year time-at-risk"") +cohortMethodAnalysis$description <- relabel(cohortMethodAnalysis$description, ""9. PS matching variable ratio No trim TAR 91d-5yr"", ""10:1 variable ratio matching, 91 days to 5 years time-at-risk"") +cohortMethodAnalysis$description <- relabel(cohortMethodAnalysis$description, ""10. PS matching variable ratio Trim 5% TAR 91d-1yr"", ""10:1 variable ratio matching 5% trim, 91 days to 1 year time-at-risk"") +cohortMethodAnalysis$description <- relabel(cohortMethodAnalysis$description, ""11. PS matching 1-1 ratio No trim TAR 91d-1yr"" , ""1:1 ratio matching, 91 days to 1 year time-at-risk"") + +dropRows <- (cohortMethodResult$databaseId %in% c(""CCAE"", ""MDCR"", ""PharMetrics"") & cohortMethodResult$outcomeId == 8210) | # drop mortality from CCAE, MDCR, PharMetrics + (cohortMethodResult$databaseId %in% c(""THIN"", ""PharMetrics"") & cohortMethodResult$outcomeId == 8211) | # drop readmission from THIN and PharMetrics + (cohortMethodResult$outcomeId %in% c(8208, 8209, 8210, 8211) & cohortMethodResult$analysisId %in% c(6:11)) | + (cohortMethodResult$outcomeId == 8212 & cohortMethodResult$analysisId %in% c(1, 4, 5, 8:11)) | # drop complications analyses (5yr trim, 5yr 1:1, 91d-1yr TARs, 91d-5yr TARs) + (cohortMethodResult$outcomeId == 8233 & cohortMethodResult$analysisId %in% c(1:7)) # drop opioids analyses (60d TAR, 1yr TAR, 5yr TAR) +cohortMethodResult <- cohortMethodResult[!dropRows, ] + +badCalibration <- (cohortMethodResult$databaseId %in% c(""THIN"") & cohortMethodResult$outcomeId %in% c(8208, 8209, 8210, 8211) & cohortMethodResult$analysisId %in% c(1,4,5)) # THIN 60d complications for removing calibrated results +cohortMethodResult[badCalibration, c(""calibratedP"", ""calibratedRr"", ""calibratedCi95Lb"", ""calibratedCi95Ub"", ""calibratedLogRr"",""calibratedSeLogRr"")] <- NA + +primary <- (cohortMethodResult$targetId == 8257 & cohortMethodResult$outcomeId %in% c(8208, 8209, 8210, 8211) & cohortMethodResult$analysisId == 1) | + (cohortMethodResult$targetId == 8257 & cohortMethodResult$outcomeId %in% c(8212) & cohortMethodResult$analysisId == 3) | + (cohortMethodResult$targetId == 8257 & cohortMethodResult$outcomeId %in% c(8233) & cohortMethodResult$analysisId == 8) + +cohortMethodResult$analysisType[primary] <- ""Primary"" +cohortMethodResult$analysisType[!primary] <- ""Sensitivity"" +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","UkaTkaSafetyEffectiveness/inst/shiny/EvidenceExplorer/server.R",".R","24117","605","library(shiny) +library(DT) + +mainColumns <- c(""analysisType"", + ""description"", + ""databaseId"", + ""rr"", + ""ci95Lb"", + ""ci95Ub"", + ""p"", + ""calibratedRr"", + ""calibratedCi95Lb"", + ""calibratedCi95Ub"", + ""calibratedP"") + +mainColumnNames <- c(""Analysis"", + ""Specification"", + ""Data source"", + ""HR"", + ""LB"", + ""UB"", + ""P"", + ""Cal.HR"", + ""Cal.LB"", + ""Cal.UB"", + ""Cal.P"") + +shinyServer(function(input, output, session) { + + + observe({ + targetId <- exposureOfInterest$exposureId[exposureOfInterest$exposureName == input$target] + comparatorId <- exposureOfInterest$exposureId[exposureOfInterest$exposureName == input$comparator] + tcoSubset <- tcos[tcos$targetId == targetId & tcos$comparatorId == comparatorId, ] + outcomes <- outcomeOfInterest$outcomeName[outcomeOfInterest$outcomeId %in% tcoSubset$outcomeId] + updateSelectInput(session = session, + inputId = ""outcome"", + choices = outcomes) + }) + + resultSubset <- reactive({ + targetId <- exposureOfInterest$exposureId[exposureOfInterest$exposureName == input$target] + comparatorId <- exposureOfInterest$exposureId[exposureOfInterest$exposureName == input$comparator] + outcomeId <- outcomeOfInterest$outcomeId[outcomeOfInterest$outcomeName == input$outcome] + analysisIds <- cohortMethodAnalysis$analysisId[cohortMethodAnalysis$description %in% input$analysis] + databaseIds <- input$database + if (length(analysisIds) == 0) { + analysisIds <- -1 + } + if (length(databaseIds) == 0) { + databaseIds <- ""none"" + } + results <- getMainResults(connection = connection, + targetIds = targetId, + comparatorIds = comparatorId, + outcomeIds = outcomeId, + databaseIds = databaseIds, + analysisIds = analysisIds) + if (blind) { + results$rr <- rep(NA, nrow(results)) + results$ci95Ub <- rep(NA, nrow(results)) + results$ci95Lb <- rep(NA, nrow(results)) + results$logRr <- rep(NA, nrow(results)) + results$seLogRr <- rep(NA, nrow(results)) + results$p <- rep(NA, nrow(results)) + results$calibratedRr <- rep(NA, nrow(results)) + results$calibratedCi95Ub <- rep(NA, nrow(results)) + results$calibratedCi95Lb <- rep(NA, nrow(results)) + results$calibratedLogRr <- rep(NA, nrow(results)) + results$calibratedSeLogRr <- rep(NA, nrow(results)) + results$calibratedP <- rep(NA, nrow(results)) + } + return(results) + }) + + selectedRow <- reactive({ + idx <- input$mainTable_rows_selected + if (is.null(idx)) { + return(NULL) + } else { + subset <- resultSubset() + if (nrow(subset) == 0) { + return(NULL) + } + row <- subset[idx, ] + return(row) + } + }) + + output$rowIsSelected <- reactive({ + return(!is.null(selectedRow())) + }) + outputOptions(output, ""rowIsSelected"", suspendWhenHidden = FALSE) + + balance <- reactive({ + row <- selectedRow() + if (is.null(row)) { + return(NULL) + } else { + targetId <- exposureOfInterest$exposureId[exposureOfInterest$exposureName == input$target] + comparatorId <- exposureOfInterest$exposureId[exposureOfInterest$exposureName == input$comparator] + outcomeId <- outcomeOfInterest$outcomeId[outcomeOfInterest$outcomeName == input$outcome] + balance <- getCovariateBalance(connection = connection, + targetId = targetId, + comparatorId = comparatorId, + databaseId = row$databaseId, + analysisId = row$analysisId, + outcomeId = outcomeId) + return(balance) + } + }) + + output$mainTable <- renderDataTable({ + table <- resultSubset() + if (is.null(table) || nrow(table) == 0) { + return(NULL) + } + table <- merge(table, cohortMethodAnalysis) + table <- table[, mainColumns] + table$rr <- prettyHr(table$rr) + table$ci95Lb <- prettyHr(table$ci95Lb) + table$ci95Ub <- prettyHr(table$ci95Ub) + table$p <- prettyHr(table$p) + table$calibratedRr <- prettyHr(table$calibratedRr) + table$calibratedCi95Lb <- prettyHr(table$calibratedCi95Lb) + table$calibratedCi95Ub <- prettyHr(table$calibratedCi95Ub) + table$calibratedP <- prettyHr(table$calibratedP) + colnames(table) <- mainColumnNames + options = list(pageLength = 15, + searching = FALSE, + lengthChange = TRUE, + ordering = TRUE, + paging = TRUE) + selection = list(mode = ""single"", target = ""row"") + table <- datatable(table, + options = options, + selection = selection, + rownames = FALSE, + escape = FALSE, + class = ""stripe nowrap compact"") + return(table) + }) + + output$powerTableCaption <- renderUI({ + row <- selectedRow() + if (!is.null(row)) { + text <- ""Table 1a. Number of subjects, follow-up time (in years), number of outcome + events, and event incidence rate (IR) per 1,000 patient years (PY) in the target (%s) and + comparator (%s) group after propensity score adjustment, as well as the minimum detectable relative risk (MDRR). + Note that the IR does not account for any stratification."" + return(HTML(sprintf(text, input$target, input$comparator))) + } else { + return(NULL) + } + }) + + output$powerTable <- renderTable({ + row <- selectedRow() + if (is.null(row)) { + return(NULL) + } else { + table <- preparePowerTable(row, cohortMethodAnalysis) + table$description <- NULL + colnames(table) <- c(""Target subjects"", + ""Comparator subjects"", + ""Target years"", + ""Comparator years"", + ""Target events"", + ""Comparator events"", + ""Target IR (per 1,000 PY)"", + ""Comparator IR (per 1,000 PY)"", + ""MDRR"") + return(table) + } + }) + + output$timeAtRiskTableCaption <- renderUI({ + row <- selectedRow() + if (!is.null(row)) { + text <- ""Table 1b. Time (days) at risk distribution expressed as + minimum (min), 25th percentile (P25), median, 75th percentile (P75), and maximum (max) in the target + (%s) and comparator (%s) cohort after propensity score adjustment."" + return(HTML(sprintf(text, input$target, input$comparator))) + } else { + return(NULL) + } + }) + + output$timeAtRiskTable <- renderTable({ + row <- selectedRow() + if (is.null(row)) { + return(NULL) + } else { + targetId <- exposureOfInterest$exposureId[exposureOfInterest$exposureName == input$target] + comparatorId <- exposureOfInterest$exposureId[exposureOfInterest$exposureName == input$comparator] + outcomeId <- outcomeOfInterest$outcomeId[outcomeOfInterest$outcomeName == input$outcome] + followUpDist <- getCmFollowUpDist(connection = connection, + targetId = targetId, + comparatorId = comparatorId, + outcomeId = outcomeId, + databaseId = row$databaseId, + analysisId = row$analysisId) + table <- prepareFollowUpDistTable(followUpDist) + return(table) + } + }) + + attritionPlot <- reactive({ + row <- selectedRow() + if (is.null(row)) { + return(NULL) + } else { + targetId <- exposureOfInterest$exposureId[exposureOfInterest$exposureName == input$target] + comparatorId <- exposureOfInterest$exposureId[exposureOfInterest$exposureName == input$comparator] + outcomeId <- outcomeOfInterest$outcomeId[outcomeOfInterest$outcomeName == input$outcome] + attrition <- getAttrition(connection = connection, + targetId = targetId, + comparatorId = comparatorId, + outcomeId = outcomeId, + databaseId = row$databaseId, + analysisId = row$analysisId) + plot <- drawAttritionDiagram(attrition) + return(plot) + } + }) + + output$attritionPlot <- renderPlot({ + return(attritionPlot()) + }) + + output$downloadAttritionPlot <- downloadHandler(filename = ""Attrition.png"", contentType = ""image/png"", content = function(file) { + device <- function(..., width, height) grDevices::png(..., width = width, height = height, res = 300, units = ""in"") + ggplot2::ggsave(file, plot = attritionPlot(), width = 6, height = 7, dpi = 400, device = device) + }) + + output$attritionPlotCaption <- renderUI({ + row <- selectedRow() + if (is.null(row)) { + return(NULL) + } else { + text <- ""Figure 1. Attrition diagram, showing the Number of subjectsin the target (%s) and + comparator (%s) group after various stages in the analysis."" + return(HTML(sprintf(text, input$target, input$comparator))) + } + }) + + output$table1Caption <- renderUI({ + row <- selectedRow() + if (is.null(row)) { + return(NULL) + } else { + text <- ""Table 2. Select characteristics before and after propensity score adjustment, showing the (weighted) + percentage of subjects with the characteristics in the target (%s) and comparator (%s) group, as + well as the standardized difference of the means."" + return(HTML(sprintf(text, input$target, input$comparator))) + } + }) + + output$table1Table <- renderDataTable({ + row <- selectedRow() + if (is.null(row)) { + return(NULL) + } else { + bal <- balance() + if (nrow(bal) == 0) { + return(NULL) + } + table1 <- prepareTable1(balance = bal, + beforeLabel = paste(""Before PS adjustment""), + afterLabel = paste(""After PS adjustment"")) + + container <- htmltools::withTags(table( + class = 'display', + thead( + tr( + th(rowspan = 3, ""Characteristic""), + th(colspan = 3, class = ""dt-center"", paste(""Before PS adjustment"")), + th(colspan = 3, class = ""dt-center"", paste(""After PS adjustment"")) + ), + tr( + lapply(table1[1, 2:ncol(table1)], th) + ), + tr( + lapply(table1[2, 2:ncol(table1)], th) + ) + ) + )) + options <- list(columnDefs = list(list(className = 'dt-right', targets = 1:6)), + searching = FALSE, + ordering = FALSE, + paging = FALSE, + bInfo = FALSE) + table1 <- datatable(table1[3:nrow(table1), ], + options = options, + rownames = FALSE, + escape = FALSE, + container = container, + class = ""stripe nowrap compact"") + return(table1) + } + }) + + psDistPlot <- reactive({ + row <- selectedRow() + if (is.null(row)) { + return(NULL) + } else { + targetId <- exposureOfInterest$exposureId[exposureOfInterest$exposureName == input$target] + comparatorId <- exposureOfInterest$exposureId[exposureOfInterest$exposureName == input$comparator] + outcomeId <- outcomeOfInterest$outcomeId[outcomeOfInterest$outcomeName == input$outcome] + ps <- getPs(connection = connection, + targetId = targetId, + comparatorId = comparatorId, + databaseId = row$databaseId) + plot <- plotPs(ps, input$target, input$comparator) + return(plot) + } + }) + + output$psDistPlot <- renderPlot({ + return(psDistPlot()) + }) + + output$downloadPsDistPlot <- downloadHandler(filename = ""Ps.png"", contentType = ""image/png"", content = function(file) { + device <- function(..., width, height) grDevices::png(..., width = width, height = height, res = 300, units = ""in"") + ggplot2::ggsave(file, plot = psDistPlot(), width = 5, height = 3.5, dpi = 400, device = device) + }) + + balancePlot <- reactive({ + bal <- balance() + if (is.null(bal) || nrow(bal) == 0) { + return(NULL) + } else { + row <- selectedRow() + writeLines(""Plotting covariate balance"") + plot <- plotCovariateBalanceScatterPlot(balance = bal, + beforeLabel = ""Before propensity score adjustment"", + afterLabel = ""After propensity score adjustment"") + return(plot) + } + }) + + output$balancePlot <- renderPlot({ + return(balancePlot()) + }) + + output$downloadBalancePlot <- downloadHandler(filename = ""Balance.png"", contentType = ""image/png"", content = function(file) { + device <- function(..., width, height) grDevices::png(..., width = width, height = height, res = 300, units = ""in"") + ggplot2::ggsave(file, plot = balancePlot(), width = 4, height = 4, dpi = 400, device = device) + }) + + output$balancePlotCaption <- renderUI({ + bal <- balance() + if (is.null(bal) || nrow(bal) == 0) { + return(NULL) + } else { + row <- selectedRow() + text <- ""Figure 3. Covariate balance before and after propensity score adjustment. Each dot represents + the standardizes difference of means for a single covariate before and after propensity score adjustment on the propensity + score. Move the mouse arrow over a dot for more details."" + return(HTML(sprintf(text))) + } + }) + + output$hoverInfoBalanceScatter <- renderUI({ + bal <- balance() + if (is.null(bal) || nrow(bal) == 0) { + return(NULL) + } else { + row <- selectedRow() + hover <- input$plotHoverBalanceScatter + point <- nearPoints(bal, hover, threshold = 5, maxpoints = 1, addDist = TRUE) + if (nrow(point) == 0) { + return(NULL) + } + left_pct <- (hover$x - hover$domain$left) / (hover$domain$right - hover$domain$left) + top_pct <- (hover$domain$top - hover$y) / (hover$domain$top - hover$domain$bottom) + left_px <- hover$range$left + left_pct * (hover$range$right - hover$range$left) + top_px <- hover$range$top + top_pct * (hover$range$bottom - hover$range$top) + style <- paste0(""position:absolute; z-index:100; background-color: rgba(245, 245, 245, 0.85); "", + ""left:"", + left_px - 251, + ""px; top:"", + top_px - 150, + ""px; width:500px;"") + beforeMatchingStdDiff <- formatC(point$beforeMatchingStdDiff, digits = 2, format = ""f"") + afterMatchingStdDiff <- formatC(point$afterMatchingStdDiff, digits = 2, format = ""f"") + div( + style = ""position: relative; width: 0; height: 0"", + wellPanel( + style = style, + p(HTML(paste0("" Covariate: "", point$covariateName, ""
"", + "" Std. diff before "",tolower(row$psStrategy),"": "", beforeMatchingStdDiff, ""
"", + "" Std. diff after "",tolower(row$psStrategy),"": "", afterMatchingStdDiff))) + ) + ) + } + }) + + systematicErrorPlot <- reactive({ + row <- selectedRow() + if (is.null(row)) { + return(NULL) + } else { + targetId <- exposureOfInterest$exposureId[exposureOfInterest$exposureName == input$target] + comparatorId <- exposureOfInterest$exposureId[exposureOfInterest$exposureName == input$comparator] + controlResults <- getControlResults(connection = connection, + targetId = targetId, + comparatorId = comparatorId, + analysisId = row$analysisId, + databaseId = row$databaseId) + + plot <- plotScatter(controlResults) + return(plot) + } + }) + + output$systematicErrorPlot <- renderPlot({ + return(systematicErrorPlot()) + }) + + output$downloadSystematicErrorPlot <- downloadHandler(filename = ""SystematicError.png"", contentType = ""image/png"", content = function(file) { + device <- function(..., width, height) grDevices::png(..., width = width, height = height, res = 300, units = ""in"") + ggplot2::ggsave(file, plot = systematicErrorPlot(), width = 12, height = 5.5, dpi = 400, device = device) + }) + + kaplanMeierPlot <- reactive({ + row <- selectedRow() + if (blind || is.null(row)) { + return(NULL) + } else { + targetId <- exposureOfInterest$exposureId[exposureOfInterest$exposureName == input$target] + comparatorId <- exposureOfInterest$exposureId[exposureOfInterest$exposureName == input$comparator] + outcomeId <- outcomeOfInterest$outcomeId[outcomeOfInterest$outcomeName == input$outcome] + km <- getKaplanMeier(connection = connection, + targetId = targetId, + comparatorId = comparatorId, + outcomeId = outcomeId, + databaseId = row$databaseId, + analysisId = row$analysisId) + plot <- plotKaplanMeier(kaplanMeier = km, + targetName = input$target, + comparatorName = input$comparator) + return(plot) + } + }) + + output$kaplanMeierPlot <- renderPlot({ + return(kaplanMeierPlot()) + }, res = 100) + + output$downloadKaplanMeierPlot <- downloadHandler(filename = ""KaplanMeier.png"", contentType = ""image/png"", content = function(file) { + device <- function(..., width, height) grDevices::png(..., width = width, height = height, res = 300, units = ""in"") + ggplot2::ggsave(file, plot = kaplanMeierPlot(), width = 7, height = 5, dpi = 400, device = device) + }) + + output$kaplanMeierPlotPlotCaption <- renderUI({ + row <- selectedRow() + if (is.null(row)) { + return(NULL) + } else { + text <- ""Figure 5. Kaplan Meier plot, showing survival as a function of time. This plot + is adjusted using the propensity score: The target curve (%s) shows the actual observed survival. The + comparator curve (%s) applies reweighting to approximate the counterfactual of what the target survival + would look like had the target cohort been exposed to the comparator instead. The shaded area denotes + the 95 percent confidence interval."" + return(HTML(sprintf(text, input$target, input$comparator))) + } + }) + + interactionEffects <- reactive({ + row <- selectedRow() + if (is.null(row)) { + return(NULL) + } else { + targetId <- exposureOfInterest$exposureId[exposureOfInterest$exposureName == input$target] + comparatorId <- exposureOfInterest$exposureId[exposureOfInterest$exposureName == input$comparator] + outcomeId <- outcomeOfInterest$outcomeId[outcomeOfInterest$outcomeName == input$outcome] + subgroupResults <- getSubgroupResults(connection = connection, + targetIds = targetId, + comparatorIds = comparatorId, + outcomeIds = outcomeId, + databaseIds = row$databaseId, + analysisIds = row$analysisId) + if (nrow(subgroupResults) == 0) { + return(NULL) + } else { + if (blind) { + subgroupResults$rrr <- rep(NA, nrow(subgroupResults)) + subgroupResults$ci95Lb <- rep(NA, nrow(subgroupResults)) + subgroupResults$ci95Ub <- rep(NA, nrow(subgroupResults)) + subgroupResults$logRrr <- rep(NA, nrow(subgroupResults)) + subgroupResults$seLogRrr <- rep(NA, nrow(subgroupResults)) + subgroupResults$p <- rep(NA, nrow(subgroupResults)) + subgroupResults$calibratedP <- rep(NA, nrow(subgroupResults)) + } + return(subgroupResults) + } + } + }) + + output$subgroupTableCaption <- renderUI({ + row <- selectedRow() + if (is.null(row)) { + return(NULL) + } else { + text <- ""Table 4. Subgroup interactions. For each subgroup, the number of subject within the subroup + in the target (%s) and comparator (%s) cohorts are provided, as well as the hazard ratio ratio (HRR) + with 95 percent confidence interval and p-value (uncalibrated and calibrated) for interaction of the main effect with + the subgroup."" + return(HTML(sprintf(text, input$target, input$comparator))) + } + }) + + output$subgroupTable <- renderDataTable({ + row <- selectedRow() + if (is.null(row)) { + return(NULL) + } else { + subgroupResults <- interactionEffects() + if (is.null(subgroupResults)) { + return(NULL) + } + subgroupTable <- prepareSubgroupTable(subgroupResults, output = ""html"") + colnames(subgroupTable) <- c(""Subgroup"", + ""Target subjects"", + ""Comparator subjects"", + ""HRR"", + ""P"", + ""Cal.P"") + options <- list(searching = FALSE, + ordering = FALSE, + paging = FALSE, + bInfo = FALSE) + subgroupTable <- datatable(subgroupTable, + options = options, + rownames = FALSE, + escape = FALSE, + class = ""stripe nowrap compact"") + return(subgroupTable) + } + }) + + observeEvent(input$dbInfo, { + showModal(modalDialog( + title = ""Data source"", + easyClose = TRUE, + footer = NULL, + size = ""l"", + HTML(dbInfoHtml) + )) + }) + + observeEvent(input$targetCohortsInfo, { + showModal(modalDialog( + title = ""Target cohort"", + easyClose = TRUE, + footer = NULL, + size = ""l"", + HTML(targetCohortsInfoHtml) + )) + }) + + observeEvent(input$comparatorCohortsInfo, { + showModal(modalDialog( + title = ""Comparator cohort"", + easyClose = TRUE, + footer = NULL, + size = ""l"", + HTML(comparatorCohortsInfoHtml) + )) + }) + + observeEvent(input$outcomesInfo, { + showModal(modalDialog( + title = ""Outcome"", + easyClose = TRUE, + footer = NULL, + size = ""l"", + HTML(outcomesInfoHtml) + )) + }) + + observeEvent(input$analysesInfo, { + showModal(modalDialog( + title = ""Analysis specification"", + easyClose = TRUE, + footer = NULL, + size = ""l"", + HTML(analysesInfoHtml) + )) + }) + + observeEvent(input$analysisTypeInfo, { + showModal(modalDialog( + title = ""Analyses type"", + easyClose = TRUE, + footer = NULL, + size = ""l"", + HTML(analysisTypeInfoHtml) + )) + }) + +}) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","UkaTkaSafetyEffectiveness/inst/shiny/EvidenceExplorer/PlotsAndTables.R",".R","48980","965","createTitle <- function(tcoDbs) { + tcoDbs$targetName <- exposures$exposureName[match(tcoDbs$targetId, exposures$exposureId)] + tcoDbs$comparatorName <- exposures$exposureName[match(tcoDbs$comparatorId, exposures$exposureId)] + tcoDbs$outcomeName <- outcomes$outcomeName[match(tcoDbs$outcomeId, outcomes$outcomeId)] + tcoDbs$indicationId <- exposures$indicationId[match(tcoDbs$targetId, exposures$exposureId)] + + titles <- paste(tcoDbs$outcomeName, + ""risk in new-users of"", + uncapitalize(tcoDbs$targetName), + ""versus"", + uncapitalize(tcoDbs$comparatorName), + ""for"", + uncapitalize(tcoDbs$indicationId), + ""in the"", + tcoDbs$databaseId, + ""database"") + return(titles) +} + +createAuthors <- function() { + authors <- paste0( + ""Martijn J. Schuemie"", "", "", + ""Patrick B. Ryan"", "", "", + ""Seng Chan You"", "", "", + ""Nicole Pratt"", "", "", + ""David Madigan"", "", "", + ""George Hripcsak"", "" and "", + ""Marc A. Suchard"" + ) +} + + + + +createAbstract <- function(tcoDb) { + + targetName <- uncapitalize(exposures$exposureName[match(tcoDb$targetId, exposures$exposureId)]) + comparatorName <- uncapitalize(exposures$exposureName[match(tcoDb$comparatorId, exposures$exposureId)]) + outcomeName <- uncapitalize(outcomes$outcomeName[match(tcoDb$outcomeId, outcomes$outcomeId)]) + indicationId <- uncapitalize(exposures$indicationId[match(tcoDb$targetId, exposures$exposureId)]) + + results <- getMainResults(connection, + targetIds = tcoDb$targetId, + comparatorIds = tcoDb$comparatorId, + outcomeIds = tcoDb$outcomeId, + databaseIds = tcoDb$databaseId) + + studyPeriod <- getStudyPeriod(connection = connection, + targetId = tcoDb$targetId, + comparatorId = tcoDb$comparatorId, + databaseId = tcoDb$databaseId) + + writeAbstract(outcomeName, targetName, comparatorName, tcoDb$databaseId, studyPeriod, results) +} + +writeAbstract <- function(outcomeName, + targetName, + comparatorName, + databaseId, + studyPeriod, + mainResults) { + + minYear <- substr(studyPeriod$minDate, 1, 4) + maxYear <- substr(studyPeriod$maxDate, 1, 4) + + abstract <- paste0( + ""We conduct a large-scale study on the incidence of "", outcomeName, "" among new users of "", targetName, "" and "", comparatorName, "" from "", minYear, "" to "", maxYear, "" in the "", databaseId, "" database. "", + ""Outcomes of interest are estimates of the hazard ratio (HR) for incident events between comparable new users under on-treatment and intent-to-treat risk window assumptions. "", + ""Secondary analyses entertain possible clinically relevant subgroup interaction with the HR. "", + ""We identify "", mainResults[1, ""targetSubjects""], "" "", targetName, "" and "", mainResults[1, ""comparatorSubjects""], "" "", comparatorName, "" patients for the on-treatment design, totaling "", round(mainResults[1, ""targetDays""] / 365.24), "" and "", round(mainResults[1, ""comparatorDays""] / 365.24), "" patient-years of observation, and "", mainResults[1, ""targetOutcomes""], "" and "", mainResults[1, ""comparatorOutcomes""], "" events respectively. "", + ""We control for measured confounding using propensity score trimming and stratification or matching based on an expansive propensity score model that includes all measured patient features before treatment initiation. "", + ""We account for unmeasured confounding using negative and positive controls to estimate and adjust for residual systematic bias in the study design and data source, providing calibrated confidence intervals and p-values. "", + ""In terms of "", outcomeName, "", "", targetName, "" has a "", judgeHazardRatio(mainResults[1, ""calibratedCi95Lb""], mainResults[1, ""calibratedCi95Ub""]), + "" risk as compared to "", comparatorName, "" [HR: "", prettyHr(mainResults[1, ""calibratedRr""]), "", 95% confidence interval (CI) "", + prettyHr(mainResults[1, ""calibratedCi95Lb""]), "" - "", prettyHr(mainResults[1, ""calibratedCi95Ub""]), ""]."" + ) + + abstract +} + +prepareFollowUpDistTable <- function(followUpDist) { + targetRow <- data.frame(Cohort = ""Target"", + Min = followUpDist$targetMinDays, + P10 = followUpDist$targetP10Days, + P25 = followUpDist$targetP25Days, + Median = followUpDist$targetMedianDays, + P75 = followUpDist$targetP75Days, + P90 = followUpDist$targetP90Days, + Max = followUpDist$targetMaxDays) + comparatorRow <- data.frame(Cohort = ""Comparator"", + Min = followUpDist$comparatorMinDays, + P10 = followUpDist$comparatorP10Days, + P25 = followUpDist$comparatorP25Days, + Median = followUpDist$comparatorMedianDays, + P75 = followUpDist$comparatorP75Days, + P90 = followUpDist$comparatorP90Days, + Max = followUpDist$comparatorMaxDays) + table <- rbind(targetRow, comparatorRow) + table$Min <- formatC(table$Min, big.mark = "","", format = ""d"") + table$P10 <- formatC(table$P10, big.mark = "","", format = ""d"") + table$P25 <- formatC(table$P25, big.mark = "","", format = ""d"") + table$Median <- formatC(table$Median, big.mark = "","", format = ""d"") + table$P75 <- formatC(table$P75, big.mark = "","", format = ""d"") + table$P90 <- formatC(table$P90, big.mark = "","", format = ""d"") + table$Max <- formatC(table$Max, big.mark = "","", format = ""d"") + return(table) +} + +prepareMainResultsTable <- function(mainResults, analyses) { + table <- mainResults + table$hr <- sprintf(""%.2f (%.2f - %.2f)"", mainResults$rr, mainResults$ci95Lb, mainResults$ci95Ub) + table$p <- sprintf(""%.2f"", table$p) + table$calHr <- sprintf(""%.2f (%.2f - %.2f)"", + mainResults$calibratedRr, + mainResults$calibratedCi95Lb, + mainResults$calibratedCi95Ub) + table$calibratedP <- sprintf(""%.2f"", table$calibratedP) + table <- merge(table, analyses) + table <- table[, c(""description"", ""hr"", ""p"", ""calHr"", ""calibratedP"")] + colnames(table) <- c(""Analysis"", ""HR (95% CI)"", ""P"", ""Cal. HR (95% CI)"", ""Cal. p"") + return(table) +} + +preparePowerTable <- function(mainResults, analyses) { + table <- merge(mainResults, analyses) + alpha <- 0.05 + power <- 0.8 + z1MinAlpha <- qnorm(1 - alpha/2) + zBeta <- -qnorm(1 - power) + pA <- table$targetSubjects/(table$targetSubjects + table$comparatorSubjects) + pB <- 1 - pA + totalEvents <- abs(table$targetOutcomes) + (table$comparatorOutcomes) + table$mdrr <- exp(sqrt((zBeta + z1MinAlpha)^2/(totalEvents * pA * pB))) + table$targetYears <- table$targetDays/365.25 + table$comparatorYears <- table$comparatorDays/365.25 + table$targetIr <- 1000 * table$targetOutcomes/table$targetYears + table$comparatorIr <- 1000 * table$comparatorOutcomes/table$comparatorYears + table <- table[, c(""description"", + ""targetSubjects"", + ""comparatorSubjects"", + ""targetYears"", + ""comparatorYears"", + ""targetOutcomes"", + ""comparatorOutcomes"", + ""targetIr"", + ""comparatorIr"", + ""mdrr"")] + table$targetSubjects <- formatC(table$targetSubjects, big.mark = "","", format = ""d"") + table$comparatorSubjects <- formatC(table$comparatorSubjects, big.mark = "","", format = ""d"") + table$targetYears <- formatC(table$targetYears, big.mark = "","", format = ""d"") + table$comparatorYears <- formatC(table$comparatorYears, big.mark = "","", format = ""d"") + table$targetOutcomes <- formatC(table$targetOutcomes, big.mark = "","", format = ""d"") + table$comparatorOutcomes <- formatC(table$comparatorOutcomes, big.mark = "","", format = ""d"") + table$targetIr <- sprintf(""%.2f"", table$targetIr) + table$comparatorIr <- sprintf(""%.2f"", table$comparatorIr) + table$mdrr <- sprintf(""%.2f"", table$mdrr) + table$targetSubjects <- gsub(""^-"", ""<"", table$targetSubjects) + table$comparatorSubjects <- gsub(""^-"", ""<"", table$comparatorSubjects) + table$targetOutcomes <- gsub(""^-"", ""<"", table$targetOutcomes) + table$comparatorOutcomes <- gsub(""^-"", ""<"", table$comparatorOutcomes) + table$targetIr <- gsub(""^-"", ""<"", table$targetIr) + table$comparatorIr <- gsub(""^-"", ""<"", table$comparatorIr) + idx <- (table$targetOutcomes < 0 | table$comparatorOutcomes < 0) + table$mdrr[idx] <- paste0("">"", table$mdrr[idx]) + return(table) +} + + +prepareSubgroupTable <- function(subgroupResults, output = ""latex"") { + rnd <- function(x) { + ifelse(x > 10, sprintf(""%.1f"", x), sprintf(""%.2f"", x)) + } + + subgroupResults$hrr <- paste0(rnd(subgroupResults$rrr), + "" ("", + rnd(subgroupResults$ci95Lb), + "" - "", + rnd(subgroupResults$ci95Ub), + "")"") + + subgroupResults$hrr[is.na(subgroupResults$rrr)] <- """" + subgroupResults$p <- sprintf(""%.2f"", subgroupResults$p) + subgroupResults$p[subgroupResults$p == ""NA""] <- """" + subgroupResults$calibratedP <- sprintf(""%.2f"", subgroupResults$calibratedP) + subgroupResults$calibratedP[subgroupResults$calibratedP == ""NA""] <- """" + + if (any(grepl(""on-treatment"", subgroupResults$analysisDescription)) && + any(grepl(""intent-to-treat"", subgroupResults$analysisDescription))) { + idx <- grepl(""on-treatment"", subgroupResults$analysisDescription) + onTreatment <- subgroupResults[idx, c(""interactionCovariateName"", + ""targetSubjects"", + ""comparatorSubjects"", + ""hrr"", + ""p"", + ""calibratedP"")] + itt <- subgroupResults[!idx, c(""interactionCovariateName"", ""hrr"", ""p"", ""calibratedP"")] + colnames(onTreatment)[4:6] <- paste(""onTreatment"", colnames(onTreatment)[4:6], sep = ""_"") + colnames(itt)[2:4] <- paste(""itt"", colnames(itt)[2:4], sep = ""_"") + table <- merge(onTreatment, itt) + } else { + table <- subgroupResults[, c(""interactionCovariateName"", + ""targetSubjects"", + ""comparatorSubjects"", + ""hrr"", + ""p"", + ""calibratedP"")] + } + table$interactionCovariateName <- gsub(""Subgroup: "", """", table$interactionCovariateName) + if (output == ""latex"") { + table$interactionCovariateName <- gsub("">="", ""$\\\\ge$ "", table$interactionCovariateName) + } + table$targetSubjects <- formatC(table$targetSubjects, big.mark = "","", format = ""d"") + table$targetSubjects <- gsub(""^-"", ""<"", table$targetSubjects) + table$comparatorSubjects <- formatC(table$comparatorSubjects, big.mark = "","", format = ""d"") + table$comparatorSubjects <- gsub(""^-"", ""<"", table$comparatorSubjects) + table$comparatorSubjects <- gsub(""^<"", ""$<$"", table$comparatorSubjects) + return(table) +} + +prepareTable1 <- function(balance, + beforeLabel = ""Before stratification"", + afterLabel = ""After stratification"", + targetLabel = ""Target"", + comparatorLabel = ""Comparator"", + percentDigits = 1, + stdDiffDigits = 2, + output = ""latex"", + pathToCsv = ""Table1Specs.csv"") { + if (output == ""latex"") { + space <- "" "" + } else { + space <- "" "" + } + specifications <- read.csv(pathToCsv, stringsAsFactors = FALSE) + + fixCase <- function(label) { + idx <- (toupper(label) == label) + if (any(idx)) { + label[idx] <- paste0(substr(label[idx], 1, 1), + tolower(substr(label[idx], 2, nchar(label[idx])))) + } + return(label) + } + + formatPercent <- function(x) { + result <- format(round(100 * x, percentDigits), digits = percentDigits + 1, justify = ""right"") + result <- gsub(""^-"", ""<"", result) + result <- gsub(""NA"", """", result) + result <- gsub("" "", space, result) + return(result) + } + + formatStdDiff <- function(x) { + result <- format(round(x, stdDiffDigits), digits = stdDiffDigits + 1, justify = ""right"") + result <- gsub(""NA"", """", result) + result <- gsub("" "", space, result) + return(result) + } + + resultsTable <- data.frame() + for (i in 1:nrow(specifications)) { + if (specifications$analysisId[i] == """") { + resultsTable <- rbind(resultsTable, + data.frame(Characteristic = specifications$label[i], value = """")) + } else { + idx <- balance$analysisId == specifications$analysisId[i] + if (any(idx)) { + if (specifications$covariateIds[i] != """") { + covariateIds <- as.numeric(strsplit(specifications$covariateIds[i], "";"")[[1]]) + idx <- balance$covariateId %in% covariateIds + } else { + covariateIds <- NULL + } + if (any(idx)) { + balanceSubset <- balance[idx, ] + if (is.null(covariateIds)) { + balanceSubset <- balanceSubset[order(balanceSubset$covariateId), ] + } else { + balanceSubset <- merge(balanceSubset, data.frame(covariateId = covariateIds, + rn = 1:length(covariateIds))) + balanceSubset <- balanceSubset[order(balanceSubset$rn, balanceSubset$covariateId), ] + } + balanceSubset$covariateName <- fixCase(gsub(""^.*: "", """", balanceSubset$covariateName)) + if (specifications$covariateIds[i] == """" || length(covariateIds) > 1) { + resultsTable <- rbind(resultsTable, data.frame(Characteristic = specifications$label[i], + beforeMatchingMeanTreated = NA, + beforeMatchingMeanComparator = NA, + beforeMatchingStdDiff = NA, + afterMatchingMeanTreated = NA, + afterMatchingMeanComparator = NA, + afterMatchingStdDiff = NA, + stringsAsFactors = FALSE)) + resultsTable <- rbind(resultsTable, data.frame(Characteristic = paste0(space, + space, + space, + space, + balanceSubset$covariateName), + beforeMatchingMeanTreated = balanceSubset$beforeMatchingMeanTreated, + beforeMatchingMeanComparator = balanceSubset$beforeMatchingMeanComparator, + beforeMatchingStdDiff = balanceSubset$beforeMatchingStdDiff, + afterMatchingMeanTreated = balanceSubset$afterMatchingMeanTreated, + afterMatchingMeanComparator = balanceSubset$afterMatchingMeanComparator, + afterMatchingStdDiff = balanceSubset$afterMatchingStdDiff, + stringsAsFactors = FALSE)) + } else { + resultsTable <- rbind(resultsTable, data.frame(Characteristic = specifications$label[i], + beforeMatchingMeanTreated = balanceSubset$beforeMatchingMeanTreated, + beforeMatchingMeanComparator = balanceSubset$beforeMatchingMeanComparator, + beforeMatchingStdDiff = balanceSubset$beforeMatchingStdDiff, + afterMatchingMeanTreated = balanceSubset$afterMatchingMeanTreated, + afterMatchingMeanComparator = balanceSubset$afterMatchingMeanComparator, + afterMatchingStdDiff = balanceSubset$afterMatchingStdDiff, + stringsAsFactors = FALSE)) + } + } + } + } + } + resultsTable$beforeMatchingMeanTreated <- formatPercent(resultsTable$beforeMatchingMeanTreated) + resultsTable$beforeMatchingMeanComparator <- formatPercent(resultsTable$beforeMatchingMeanComparator) + resultsTable$beforeMatchingStdDiff <- formatStdDiff(resultsTable$beforeMatchingStdDiff) + resultsTable$afterMatchingMeanTreated <- formatPercent(resultsTable$afterMatchingMeanTreated) + resultsTable$afterMatchingMeanComparator <- formatPercent(resultsTable$afterMatchingMeanComparator) + resultsTable$afterMatchingStdDiff <- formatStdDiff(resultsTable$afterMatchingStdDiff) + + headerRow <- as.data.frame(t(rep("""", ncol(resultsTable)))) + colnames(headerRow) <- colnames(resultsTable) + headerRow$beforeMatchingMeanTreated <- targetLabel + headerRow$beforeMatchingMeanComparator <- comparatorLabel + headerRow$afterMatchingMeanTreated <- targetLabel + headerRow$afterMatchingMeanComparator <- comparatorLabel + + subHeaderRow <- as.data.frame(t(rep("""", ncol(resultsTable)))) + colnames(subHeaderRow) <- colnames(resultsTable) + subHeaderRow$Characteristic <- ""Characteristic"" + subHeaderRow$beforeMatchingMeanTreated <- ""%"" + subHeaderRow$beforeMatchingMeanComparator <- ""%"" + subHeaderRow$beforeMatchingStdDiff <- ""Std. diff"" + subHeaderRow$afterMatchingMeanTreated <- ""%"" + subHeaderRow$afterMatchingMeanComparator <- ""%"" + subHeaderRow$afterMatchingStdDiff <- ""Std. diff"" + + resultsTable <- rbind(headerRow, subHeaderRow, resultsTable) + + colnames(resultsTable) <- rep("""", ncol(resultsTable)) + colnames(resultsTable)[2] <- beforeLabel + colnames(resultsTable)[5] <- afterLabel + return(resultsTable) +} + +plotPs <- function(ps, targetName, comparatorName) { + ps <- rbind(data.frame(x = ps$preferenceScore, y = ps$targetDensity, group = targetName), + data.frame(x = ps$preferenceScore, y = ps$comparatorDensity, group = comparatorName)) + ps$group <- factor(ps$group, levels = c(as.character(targetName), as.character(comparatorName))) + theme <- ggplot2::element_text(colour = ""#000000"", size = 12, margin = ggplot2::margin(0, 0.5, 0, 0.1, ""cm"")) + plot <- ggplot2::ggplot(ps, + ggplot2::aes(x = x, y = y, color = group, group = group, fill = group)) + + ggplot2::geom_density(stat = ""identity"") + + ggplot2::scale_fill_manual(values = c(rgb(0.8, 0, 0, alpha = 0.5), + rgb(0, 0, 0.8, alpha = 0.5))) + + ggplot2::scale_color_manual(values = c(rgb(0.8, 0, 0, alpha = 0.5), + rgb(0, 0, 0.8, alpha = 0.5))) + + ggplot2::scale_x_continuous(""Preference score"", limits = c(0, 1)) + + ggplot2::scale_y_continuous(""Density"") + + ggplot2::theme(legend.title = ggplot2::element_blank(), + panel.grid.major = ggplot2::element_blank(), + panel.grid.minor = ggplot2::element_blank(), + legend.position = ""top"", + legend.text = theme, + axis.text = theme, + axis.title = theme) + return(plot) +} + +plotAllPs <- function(ps) { + ps <- rbind(data.frame(targetName = ps$targetName, + comparatorName = ps$comparatorName, + x = ps$preferenceScore, + y = ps$targetDensity, + group = ""Target""), + data.frame(targetName = ps$targetName, + comparatorName = ps$comparatorName, + x = ps$preferenceScore, + y = ps$comparatorDensity, + group = ""Comparator"")) + ps$group <- factor(ps$group, levels = c(""Target"", ""Comparator"")) + plot <- ggplot2::ggplot(ps, ggplot2::aes(x = x, y = y, color = group, group = group, fill = group)) + + ggplot2::geom_density(stat = ""identity"") + + ggplot2::scale_fill_manual(values = c(rgb(0.8, 0, 0, alpha = 0.5), rgb(0, 0, 0.8, alpha = 0.5))) + + ggplot2::scale_color_manual(values = c(rgb(0.8, 0, 0, alpha = 0.5), rgb(0, 0, 0.8, alpha = 0.5))) + + ggplot2::scale_x_continuous(""Preference score"", limits = c(0, 1)) + + ggplot2::scale_y_continuous(""Density"") + + ggplot2::facet_grid(targetName ~ comparatorName) + + ggplot2::theme(legend.title = ggplot2::element_blank(), + axis.title.x = ggplot2::element_blank(), + axis.text.x = ggplot2::element_blank(), + axis.ticks.x = ggplot2::element_blank(), + axis.title.y = ggplot2::element_blank(), + axis.text.y = ggplot2::element_blank(), + axis.ticks.y = ggplot2::element_blank(), + panel.grid.major = ggplot2::element_blank(), + panel.grid.minor = ggplot2::element_blank(), + strip.text.x = ggplot2::element_text(size = 12, angle = 90, vjust = 0), + strip.text.y = ggplot2::element_text(size = 12, angle = 0, hjust = 0), + panel.spacing = ggplot2::unit(0.1, ""lines""), + legend.position = ""none"") + return(plot) +} + + +plotCovariateBalanceScatterPlot <- function(balance, beforeLabel = ""Before stratification"", afterLabel = ""After stratification"") { + limits <- c(min(c(balance$absBeforeMatchingStdDiff, balance$absAfterMatchingStdDiff), + na.rm = TRUE), + max(c(balance$absBeforeMatchingStdDiff, balance$absAfterMatchingStdDiff), + na.rm = TRUE)) + theme <- ggplot2::element_text(colour = ""#000000"", size = 12) + plot <- ggplot2::ggplot(balance, ggplot2::aes(x = absBeforeMatchingStdDiff, y = absAfterMatchingStdDiff)) + + ggplot2::geom_point(color = rgb(0, 0, 0.8, alpha = 0.3), shape = 16, size = 2) + + ggplot2::geom_abline(slope = 1, intercept = 0, linetype = ""dashed"") + + ggplot2::geom_hline(yintercept = 0) + + ggplot2::geom_vline(xintercept = 0) + + ggplot2::scale_x_continuous(beforeLabel, limits = limits) + + ggplot2::scale_y_continuous(afterLabel, limits = limits) + + ggplot2::theme(text = theme) + + return(plot) +} + +plotKaplanMeier <- function(kaplanMeier, targetName, comparatorName) { + data <- rbind(data.frame(time = kaplanMeier$time, + s = kaplanMeier$targetSurvival, + lower = kaplanMeier$targetSurvivalLb, + upper = kaplanMeier$targetSurvivalUb, + strata = paste0("" "", targetName, "" "")), + data.frame(time = kaplanMeier$time, + s = kaplanMeier$comparatorSurvival, + lower = kaplanMeier$comparatorSurvivalLb, + upper = kaplanMeier$comparatorSurvivalUb, + strata = paste0("" "", comparatorName))) + + xlims <- c(-max(data$time)/40, max(data$time)) + ylims <- c(min(data$lower), 1) + xLabel <- ""Time in days"" + yLabel <- ""Survival probability"" + xBreaks <- kaplanMeier$time[!is.na(kaplanMeier$targetAtRisk)] + plot <- ggplot2::ggplot(data, ggplot2::aes(x = time, + y = s, + color = strata, + fill = strata, + ymin = lower, + ymax = upper)) + + ggplot2::geom_ribbon(color = rgb(0, 0, 0, alpha = 0)) + + ggplot2::geom_step(size = 1) + + ggplot2::scale_color_manual(values = c(rgb(0.8, 0, 0, alpha = 0.8), + rgb(0, 0, 0.8, alpha = 0.8))) + + ggplot2::scale_fill_manual(values = c(rgb(0.8, 0, 0, alpha = 0.3), + rgb(0, 0, 0.8, alpha = 0.3))) + + ggplot2::scale_x_continuous(xLabel, limits = xlims, breaks = xBreaks) + + ggplot2::scale_y_continuous(yLabel, limits = ylims) + + ggplot2::theme(legend.title = ggplot2::element_blank(), + legend.position = ""top"", + legend.key.size = ggplot2::unit(1, ""lines""), + plot.title = ggplot2::element_text(hjust = 0.5)) + + ggplot2::theme(axis.title.y = ggplot2::element_text(vjust = -10)) + + targetAtRisk <- kaplanMeier$targetAtRisk[!is.na(kaplanMeier$targetAtRisk)] + comparatorAtRisk <- kaplanMeier$comparatorAtRisk[!is.na(kaplanMeier$comparatorAtRisk)] + labels <- data.frame(x = c(0, xBreaks, xBreaks), + y = as.factor(c(""Number at risk"", + rep(targetName, length(xBreaks)), + rep(comparatorName, length(xBreaks)))), + label = c("""", + formatC(targetAtRisk, big.mark = "","", mode = ""integer""), + formatC(comparatorAtRisk, big.mark = "","", mode = ""integer""))) + labels$y <- factor(labels$y, levels = c(comparatorName, targetName, ""Number at risk"")) + dataTable <- ggplot2::ggplot(labels, ggplot2::aes(x = x, y = y, label = label)) + ggplot2::geom_text(size = 3.5, vjust = 0.5) + ggplot2::scale_x_continuous(xLabel, + limits = xlims, + breaks = xBreaks) + ggplot2::theme(panel.grid.major = ggplot2::element_blank(), + panel.grid.minor = ggplot2::element_blank(), + legend.position = ""none"", + panel.border = ggplot2::element_blank(), + panel.background = ggplot2::element_blank(), + axis.text.x = ggplot2::element_text(color = ""white""), + axis.title.x = ggplot2::element_text(color = ""white""), + axis.title.y = ggplot2::element_blank(), + axis.ticks = ggplot2::element_line(color = ""white"")) + plots <- list(plot, dataTable) + grobs <- widths <- list() + for (i in 1:length(plots)) { + grobs[[i]] <- ggplot2::ggplotGrob(plots[[i]]) + widths[[i]] <- grobs[[i]]$widths[2:5] + } + maxwidth <- do.call(grid::unit.pmax, widths) + for (i in 1:length(grobs)) { + grobs[[i]]$widths[2:5] <- as.list(maxwidth) + } + plot <- gridExtra::grid.arrange(grobs[[1]], grobs[[2]], heights = c(400, 100)) + return(plot) +} + +judgeCoverage <- function(values) { + ifelse(any(values < 0.9), ""poor"", ""acceptable"") +} + +getCoverage <- function(controlResults) { + d <- rbind(data.frame(yGroup = ""Uncalibrated"", + logRr = controlResults$logRr, + seLogRr = controlResults$seLogRr, + ci95Lb = controlResults$ci95Lb, + ci95Ub = controlResults$ci95Ub, + trueRr = controlResults$effectSize), + data.frame(yGroup = ""Calibrated"", + logRr = controlResults$calibratedLogRr, + seLogRr = controlResults$calibratedSeLogRr, + ci95Lb = controlResults$calibratedCi95Lb, + ci95Ub = controlResults$calibratedCi95Ub, + trueRr = controlResults$effectSize)) + d <- d[!is.na(d$logRr), ] + d <- d[!is.na(d$ci95Lb), ] + d <- d[!is.na(d$ci95Ub), ] + if (nrow(d) == 0) { + return(NULL) + } + + d$Group <- as.factor(d$trueRr) + d$Significant <- d$ci95Lb > d$trueRr | d$ci95Ub < d$trueRr + + temp2 <- aggregate(Significant ~ Group + yGroup, data = d, mean) + temp2$coverage <- (1 - temp2$Significant) + + data.frame(true = temp2$Group, group = temp2$yGroup, coverage = temp2$coverage) +} + +plotScatter <- function(controlResults) { + size <- 2 + labelY <- 0.7 + d <- rbind(data.frame(yGroup = ""Uncalibrated"", + logRr = controlResults$logRr, + seLogRr = controlResults$seLogRr, + ci95Lb = controlResults$ci95Lb, + ci95Ub = controlResults$ci95Ub, + trueRr = controlResults$effectSize), + data.frame(yGroup = ""Calibrated"", + logRr = controlResults$calibratedLogRr, + seLogRr = controlResults$calibratedSeLogRr, + ci95Lb = controlResults$calibratedCi95Lb, + ci95Ub = controlResults$calibratedCi95Ub, + trueRr = controlResults$effectSize)) + d <- d[!is.na(d$logRr), ] + d <- d[!is.na(d$ci95Lb), ] + d <- d[!is.na(d$ci95Ub), ] + if (nrow(d) == 0) { + return(NULL) + } + d$Group <- as.factor(d$trueRr) + d$Significant <- d$ci95Lb > d$trueRr | d$ci95Ub < d$trueRr + temp1 <- aggregate(Significant ~ Group + yGroup, data = d, length) + temp2 <- aggregate(Significant ~ Group + yGroup, data = d, mean) + temp1$nLabel <- paste0(formatC(temp1$Significant, big.mark = "",""), "" estimates"") + temp1$Significant <- NULL + + temp2$meanLabel <- paste0(formatC(100 * (1 - temp2$Significant), digits = 1, format = ""f""), + ""% of CIs include "", + temp2$Group) + temp2$Significant <- NULL + dd <- merge(temp1, temp2) + dd$tes <- as.numeric(as.character(dd$Group)) + + breaks <- c(0.1, 0.25, 0.5, 1, 2, 4, 6, 8, 10) + theme <- ggplot2::element_text(colour = ""#000000"", size = 12) + themeRA <- ggplot2::element_text(colour = ""#000000"", size = 12, hjust = 1) + themeLA <- ggplot2::element_text(colour = ""#000000"", size = 12, hjust = 0) + + d$Group <- paste(""True hazard ratio ="", d$Group) + dd$Group <- paste(""True hazard ratio ="", dd$Group) + alpha <- 1 - min(0.95 * (nrow(d)/nrow(dd)/50000)^0.1, 0.95) + plot <- ggplot2::ggplot(d, ggplot2::aes(x = logRr, y = seLogRr), environment = environment()) + + ggplot2::geom_vline(xintercept = log(breaks), colour = ""#AAAAAA"", lty = 1, size = 0.5) + + ggplot2::geom_abline(ggplot2::aes(intercept = (-log(tes))/qnorm(0.025), slope = 1/qnorm(0.025)), + colour = rgb(0.8, 0, 0), + linetype = ""dashed"", + size = 1, + alpha = 0.5, + data = dd) + + ggplot2::geom_abline(ggplot2::aes(intercept = (-log(tes))/qnorm(0.975), slope = 1/qnorm(0.975)), + colour = rgb(0.8, 0, 0), + linetype = ""dashed"", + size = 1, + alpha = 0.5, + data = dd) + + ggplot2::geom_point(size = size, + color = rgb(0, 0, 0, alpha = 0.05), + alpha = alpha, + shape = 16) + + ggplot2::geom_hline(yintercept = 0) + + ggplot2::geom_label(x = log(0.15), + y = 0.9, + alpha = 1, + hjust = ""left"", + ggplot2::aes(label = nLabel), + size = 5, + data = dd) + + ggplot2::geom_label(x = log(0.15), + y = labelY, + alpha = 1, + hjust = ""left"", + ggplot2::aes(label = meanLabel), + size = 5, + data = dd) + + ggplot2::scale_x_continuous(""Hazard ratio"", + limits = log(c(0.1, 10)), + breaks = log(breaks), + labels = breaks) + + ggplot2::scale_y_continuous(""Standard Error"", limits = c(0, 1)) + + ggplot2::facet_grid(yGroup ~ Group) + + ggplot2::theme(panel.grid.minor = ggplot2::element_blank(), + panel.background = ggplot2::element_blank(), + panel.grid.major = ggplot2::element_blank(), + axis.ticks = ggplot2::element_blank(), + axis.text.y = themeRA, + axis.text.x = theme, + axis.title = theme, + legend.key = ggplot2::element_blank(), + strip.text.x = theme, + strip.text.y = theme, + strip.background = ggplot2::element_blank(), + legend.position = ""none"") + + return(plot) +} + +plotLargeScatter <- function(d, xLabel) { + d$Significant <- d$ci95Lb > 1 | d$ci95Ub < 1 + + oneRow <- data.frame(nLabel = paste0(formatC(nrow(d), big.mark = "",""), "" estimates""), + meanLabel = paste0(formatC(100 * + mean(!d$Significant, na.rm = TRUE), digits = 1, format = ""f""), ""% of CIs includes 1"")) + + breaks <- c(0.1, 0.25, 0.5, 1, 2, 4, 6, 8, 10) + theme <- ggplot2::element_text(colour = ""#000000"", size = 12) + themeRA <- ggplot2::element_text(colour = ""#000000"", size = 12, hjust = 1) + themeLA <- ggplot2::element_text(colour = ""#000000"", size = 12, hjust = 0) + + alpha <- 1 - min(0.95 * (nrow(d)/50000)^0.1, 0.95) + plot <- ggplot2::ggplot(d, ggplot2::aes(x = logRr, y = seLogRr)) + + ggplot2::geom_vline(xintercept = log(breaks), colour = ""#AAAAAA"", lty = 1, size = 0.5) + + ggplot2::geom_abline(ggplot2::aes(intercept = 0, slope = 1/qnorm(0.025)), + colour = rgb(0.8, 0, 0), + linetype = ""dashed"", + size = 1, + alpha = 0.5) + + ggplot2::geom_abline(ggplot2::aes(intercept = 0, slope = 1/qnorm(0.975)), + colour = rgb(0.8, 0, 0), + linetype = ""dashed"", + size = 1, + alpha = 0.5) + + ggplot2::geom_point(size = 2, color = rgb(0, 0, 0, alpha = 0.05), alpha = alpha, shape = 16) + + ggplot2::geom_hline(yintercept = 0) + + ggplot2::geom_label(x = log(0.11), + y = 1, + alpha = 1, + hjust = ""left"", + ggplot2::aes(label = nLabel), + size = 5, + data = oneRow) + + ggplot2::geom_label(x = log(0.11), + y = 0.935, + alpha = 1, + hjust = ""left"", + ggplot2::aes(label = meanLabel), + size = 5, + data = oneRow) + + ggplot2::scale_x_continuous(xLabel, limits = log(c(0.1, + 10)), breaks = log(breaks), labels = breaks) + + ggplot2::scale_y_continuous(""Standard Error"", limits = c(0, 1)) + + ggplot2::theme(panel.grid.minor = ggplot2::element_blank(), + panel.background = ggplot2::element_blank(), + panel.grid.major = ggplot2::element_blank(), + axis.ticks = ggplot2::element_blank(), + axis.text.y = themeRA, + axis.text.x = theme, + axis.title = theme, + legend.key = ggplot2::element_blank(), + strip.text.x = theme, + strip.background = ggplot2::element_blank(), + legend.position = ""none"") + return(plot) +} + + + +drawAttritionDiagram <- function(attrition, + targetLabel = ""Target"", + comparatorLabel = ""Comparator"") { + addStep <- function(data, attrition, row) { + label <- paste(strwrap(as.character(attrition$description[row]), width = 30), collapse = ""\n"") + data$leftBoxText[length(data$leftBoxText) + 1] <- label + data$rightBoxText[length(data$rightBoxText) + 1] <- paste(targetLabel, + "": n = "", + data$currentTarget - attrition$targetPersons[row], + ""\n"", + comparatorLabel, + "": n = "", + data$currentComparator - attrition$comparatorPersons[row], + sep = """") + data$currentTarget <- attrition$targetPersons[row] + data$currentComparator <- attrition$comparatorPersons[row] + return(data) + } + data <- list(leftBoxText = c(paste(""Exposed:\n"", + targetLabel, + "": n = "", + attrition$targetPersons[1], + ""\n"", + comparatorLabel, + "": n = "", + attrition$comparatorPersons[1], + sep = """")), rightBoxText = c(""""), currentTarget = attrition$targetPersons[1], currentComparator = attrition$comparatorPersons[1]) + for (i in 2:nrow(attrition)) { + data <- addStep(data, attrition, i) + } + + + data$leftBoxText[length(data$leftBoxText) + 1] <- paste(""Study population:\n"", + targetLabel, + "": n = "", + data$currentTarget, + ""\n"", + comparatorLabel, + "": n = "", + data$currentComparator, + sep = """") + leftBoxText <- data$leftBoxText + rightBoxText <- data$rightBoxText + nSteps <- length(leftBoxText) + + boxHeight <- (1/nSteps) - 0.03 + boxWidth <- 0.45 + shadowOffset <- 0.01 + arrowLength <- 0.01 + x <- function(x) { + return(0.25 + ((x - 1)/2)) + } + y <- function(y) { + return(1 - (y - 0.5) * (1/nSteps)) + } + + downArrow <- function(p, x1, y1, x2, y2) { + p <- p + ggplot2::geom_segment(ggplot2::aes_string(x = x1, y = y1, xend = x2, yend = y2)) + p <- p + ggplot2::geom_segment(ggplot2::aes_string(x = x2, + y = y2, + xend = x2 + arrowLength, + yend = y2 + arrowLength)) + p <- p + ggplot2::geom_segment(ggplot2::aes_string(x = x2, + y = y2, + xend = x2 - arrowLength, + yend = y2 + arrowLength)) + return(p) + } + rightArrow <- function(p, x1, y1, x2, y2) { + p <- p + ggplot2::geom_segment(ggplot2::aes_string(x = x1, y = y1, xend = x2, yend = y2)) + p <- p + ggplot2::geom_segment(ggplot2::aes_string(x = x2, + y = y2, + xend = x2 - arrowLength, + yend = y2 + arrowLength)) + p <- p + ggplot2::geom_segment(ggplot2::aes_string(x = x2, + y = y2, + xend = x2 - arrowLength, + yend = y2 - arrowLength)) + return(p) + } + box <- function(p, x, y) { + p <- p + ggplot2::geom_rect(ggplot2::aes_string(xmin = x - (boxWidth/2) + shadowOffset, + ymin = y - (boxHeight/2) - shadowOffset, + xmax = x + (boxWidth/2) + shadowOffset, + ymax = y + (boxHeight/2) - shadowOffset), fill = rgb(0, + 0, + 0, + alpha = 0.2)) + p <- p + ggplot2::geom_rect(ggplot2::aes_string(xmin = x - (boxWidth/2), + ymin = y - (boxHeight/2), + xmax = x + (boxWidth/2), + ymax = y + (boxHeight/2)), fill = rgb(0.94, + 0.94, + 0.94), color = ""black"") + return(p) + } + label <- function(p, x, y, text, hjust = 0) { + p <- p + ggplot2::geom_text(ggplot2::aes_string(x = x, y = y, label = paste(""\"""", text, ""\"""", + sep = """")), + hjust = hjust, + size = 3.7) + return(p) + } + + p <- ggplot2::ggplot() + for (i in 2:nSteps - 1) { + p <- downArrow(p, x(1), y(i) - (boxHeight/2), x(1), y(i + 1) + (boxHeight/2)) + p <- label(p, x(1) + 0.02, y(i + 0.5), ""Y"") + } + for (i in 2:(nSteps - 1)) { + p <- rightArrow(p, x(1) + boxWidth/2, y(i), x(2) - boxWidth/2, y(i)) + p <- label(p, x(1.5), y(i) - 0.02, ""N"", 0.5) + } + for (i in 1:nSteps) { + p <- box(p, x(1), y(i)) + } + for (i in 2:(nSteps - 1)) { + p <- box(p, x(2), y(i)) + } + for (i in 1:nSteps) { + p <- label(p, x(1) - boxWidth/2 + 0.02, y(i), text = leftBoxText[i]) + } + for (i in 2:(nSteps - 1)) { + p <- label(p, x(2) - boxWidth/2 + 0.02, y(i), text = rightBoxText[i]) + } + p <- p + ggplot2::theme(legend.position = ""none"", + plot.background = ggplot2::element_blank(), + panel.grid.major = ggplot2::element_blank(), + panel.grid.minor = ggplot2::element_blank(), + panel.border = ggplot2::element_blank(), + panel.background = ggplot2::element_blank(), + axis.text = ggplot2::element_blank(), + axis.title = ggplot2::element_blank(), + axis.ticks = ggplot2::element_blank()) + + return(p) +} + +judgeHazardRatio <- function(hrLower, hrUpper) { + nonZeroHazardRatio(hrLower, hrUpper, c(""lower"", ""higher"", ""similar"")) +} + +nonZeroHazardRatio <- function(hrLower, hrUpper, terms) { + if (hrUpper < 1) { + return(terms[1]) + } else if (hrLower > 1) { + return(terms[2]) + } else { + return(terms[3]) + } +} + +judgeEffectiveness <- function(hrLower, hrUpper) { + nonZeroHazardRatio(hrLower, hrUpper, c(""less"", ""more"", ""as"")) +} + +prettyHr <- function(x) { + result <- sprintf(""%.2f"", x) + result[is.na(x) | x > 100] <- ""NA"" + return(result) +} + +goodPropensityScore <- function(value) { + return(value > 1) +} + +goodSystematicBias <- function(value) { + return(value > 1) +} + +judgePropensityScore <- function(ps, bias) { + paste0("" "", + ifelse(goodPropensityScore(ps), ""substantial"", ""inadequate""), + "" control of measured confounding by propensity score adjustment, and "", + ifelse(goodSystematicBias(bias), ""minimal"", ""non-negligible""), + "" residual systematic bias through negative and positive control experiments"", + ifelse(goodPropensityScore(ps) && goodSystematicBias(bias), + "", lending credibility to our effect estimates"", + """")) +} + +uncapitalize <- function(x) { + if (is.character(x)) { + substr(x, 1, 1) <- tolower(substr(x, 1, 1)) + } + x +} + +capitalize <- function(x) { + substr(x, 1, 1) <- toupper(substr(x, 1, 1)) + x +} + +createDocument <- function(targetId, + comparatorId, + outcomeId, + databaseId, + indicationId, + outputFile, + template = ""template.Rnw"", + workingDirectory = ""temp"", + emptyWorkingDirectory = TRUE) { + + if (missing(outputFile)) { + stop(""Must provide an output file name"") + } + + currentDirectory <- getwd() + on.exit(setwd(currentDirectory)) + + input <- file(template, ""r"") + + name <- paste0(""paper_"", targetId, ""_"", comparatorId, ""_"", outcomeId, ""_"", databaseId) + + if (!dir.exists(workingDirectory)) { + dir.create(workingDirectory) + } + + workingDirectory <- file.path(workingDirectory, name) + + if (!dir.exists(workingDirectory)) { + dir.create(workingDirectory) + } + + if (is.null(setwd(workingDirectory))) { + stop(paste0(""Unable to change directory into: "", workingDirectory)) + } + + system(paste0(""cp "", file.path(currentDirectory, ""pnas-new.cls""), "" ."")) + system(paste0(""cp "", file.path(currentDirectory, ""widetext.sty""), "" ."")) + system(paste0(""cp "", file.path(currentDirectory, ""pnasresearcharticle.sty""), "" ."")) + system(paste0(""cp "", file.path(currentDirectory, ""Sweave.sty""), "" ."")) + + texName <- paste0(name, "".Rnw"") + output <- file(texName, ""w"") + + while (TRUE) { + line <- readLines(input, n = 1) + if (length(line) == 0) { + break + } + line <- sub(""DATABASE_ID_TAG"", paste0(""\"""", databaseId, ""\""""), line) + line <- sub(""TARGET_ID_TAG"", targetId, line) + line <- sub(""COMPARATOR_ID_TAG"", comparatorId, line) + line <- sub(""OUTCOME_ID_TAG"", outcomeId, line) + line <- sub(""INDICATION_ID_TAG"", indicationId, line) + line <- sub(""CURRENT_DIRECTORY"", currentDirectory, line) + writeLines(line, output) + } + close(input) + close(output) + + Sweave(texName) + system(paste0(""pdflatex "", name)) + system(paste0(""pdflatex "", name)) + + # Save result + workingName <- file.path(workingDirectory, name) + workingName <- paste0(workingName, "".pdf"") + + setwd(currentDirectory) + + system(paste0(""cp "", workingName, "" "", outputFile)) + + if (emptyWorkingDirectory) { + # deleteName = file.path(workingDirectory, ""*"") + # system(paste0(""rm "", deleteName)) + unlink(workingDirectory, recursive = TRUE) + } + + invisible(outputFile) +} + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","UkaTkaSafetyEffectiveness/inst/shiny/EvidenceExplorer/ui.R",".R","12676","104","library(shiny) +library(DT) + +shinyUI( + fluidPage(style = ""width:1500px;"", + titlePanel(paste(""Prospective validation of a randomised trial of unicompartmental and total knee replacement: real-world evidence from the OHDSI network"", if(blind) ""***Blinded***"" else """")), + tags$head(tags$style(type = ""text/css"", "" + #loadmessage { + position: fixed; + top: 0px; + left: 0px; + width: 100%; + padding: 5px 0px 5px 0px; + text-align: center; + font-weight: bold; + font-size: 100%; + color: #000000; + background-color: #ADD8E6; + z-index: 105; + } + "")), + conditionalPanel(condition = ""$('html').hasClass('shiny-busy')"", + tags$div(""Procesing..."",id = ""loadmessage"")), + + tabsetPanel(id = ""mainTabsetPanel"", + tabPanel(""About"", + HTML(""
""), + div(p(""These research results are from a retrospective, real-world observational study to evaluate the risk of post-operative complications, opioid use, and revision with unicompartmental versus total knee replacement. The results have been reported in advance of results from an ongoing clinical trial comparing the same procedures for the risk of the same outcomes. This web-based application provides an interactive platform to explore all analysis results generated as part of this study. A full manuscript has been submitted for peer review publication.""), style=""border: 1px solid black; padding: 5px;""), + HTML(""
""), + HTML(""

Below is the abstract of the manuscript that summarizes the findings:

""), + HTML(""

Backgroud: In this network cohort study we aimed to predict the results of an ongoing surgical randomised controlled trial of unicompartmental and total knee replacement, the Total or Partial Knee Arthroplasty Trial (TOPKAT).

""), + HTML(""

Methods: Five US and UK healthcare databases part of the Observational Health Data Sciences and Informatics (OHDSI) network were analysed. As with the target trial, post-operative complications (venous thromboembolism, infection, readmission, and mortality) were considered over 60 days following surgery and implant survival (revision procedures) over five years following surgery. Clinical effectiveness was assessed using opioid use, as a proxy measure for persistent pain, from 91 to 365 days after surgery. Propensity score matched Cox proportional hazards models were fitted for each outcome. Hazard Ratios (HRs) were calibrated using negative and positive control outcomes to minimise residual confounding.

""), + HTML(""

Findings: In total, 32,376 and 250,295 individuals who received unicompartmental and total knee replacement respectively were matched based on propensity scores and included in the analysis. Unicompartmental knee replacement was consistently associated with a reduced risk of venous thromboembolism (calibrated HRs: 0.47 (0.31 - 0.73) to 0.76 (0.60 to 0.99)) and opioid use (calibrated HRs: 0.72 (0.63 to 0.84) to 0.86 (0.77 to 0.96)), but an increased risk of revision (calibrated HRs: 1.48 (1.25 to 1.83) to 1.76 (1.42 to 2.32)). Unicompartmental knee replacement was also associated with either a protective or no effect on risk of infection and readmission, and there was little evidence of a difference in risk of mortality in the one database for which calibrated HRs could be estimated.

""), + HTML(""

Interpretation: Based on our results, we predict TOPKAT will find a significantly increased risk of revision but improved patient reported outcomes for unicompartmental knee replacement. While the trial is not powered to assess complications, we find unicompartmental knee replacement to be a safer procedure with, in particular, a reduced risk of venous thromboembolism. These findings, along with those from the trial when they emerge, will improve the understanding of the relative merits of unicompartmental and total knee replacement.

""), + HTML(""
""), + HTML(""

Below are links for study-related artifacts that have been made available as part of this study:

""), + HTML("""") + ), + tabPanel(""Explore results"", + fluidRow( + column(4, + selectInput(""target"", div(""Target cohort:"", actionLink(""targetCohortsInfo"", """", icon(""info-circle""))), unique(exposureOfInterest$exposureName), selected = unique(exposureOfInterest$exposureName)[1], width = '100%'), + selectInput(""comparator"", div(""Comparator cohort:"", actionLink(""comparatorCohortsInfo"", """", icon(""info-circle""))), unique(exposureOfInterest$exposureName), selected = unique(exposureOfInterest$exposureName)[2], width = '100%'), + selectInput(""outcome"", div(""Outcome:"", actionLink(""outcomesInfo"", """", icon(""info-circle""))), unique(outcomeOfInterest$outcomeName), width = '100%'), + checkboxGroupInput(""database"", div(""Data source:"", actionLink(""dbInfo"", """", icon(""info-circle""))), database$databaseId, selected = database$databaseId[1], width = '100%'), + checkboxGroupInput(""analysis"", div(""Analysis specification:"", actionLink(""analysesInfo"", """", icon(""info-circle""))), cohortMethodAnalysis$description, selected = cohortMethodAnalysis$description, width = '100%') + ), + + column(8, + dataTableOutput(""mainTable""), + conditionalPanel(""output.rowIsSelected == true"", + tabsetPanel(id = ""detailsTabsetPanel"", + tabPanel(""Power"", + uiOutput(""powerTableCaption""), + tableOutput(""powerTable""), + uiOutput(""timeAtRiskTableCaption""), + tableOutput(""timeAtRiskTable"") + ), + tabPanel(""Attrition"", + plotOutput(""attritionPlot"", width = 600, height = 600), + uiOutput(""attritionPlotCaption""), + downloadButton(""downloadAttritionPlot"", label = ""Download diagram"") + ), + tabPanel(""Population characteristics"", + uiOutput(""table1Caption""), + dataTableOutput(""table1Table"")), + tabPanel(""Propensity scores"", + plotOutput(""psDistPlot""), + div(strong(""Figure 2.""),""Preference score distribution. The preference score is a transformation of the propensity score + that adjusts for differences in the sizes of the two treatment groups. A higher overlap indicates subjects in the + two groups were more similar in terms of their predicted probability of receiving one treatment over the other.""), + downloadButton(""downloadPsDistPlot"", label = ""Download plot"")), + tabPanel(""Covariate balance"", + uiOutput(""hoverInfoBalanceScatter""), + plotOutput(""balancePlot"", + hover = hoverOpts(""plotHoverBalanceScatter"", delay = 100, delayType = ""debounce"")), + uiOutput(""balancePlotCaption""), + downloadButton(""downloadBalancePlot"", label = ""Download plot"")), + tabPanel(""Systematic error"", + plotOutput(""systematicErrorPlot""), + div(strong(""Figure 4.""),""Systematic error. Effect size estimates for the negative controls (true hazard ratio = 1) + and positive controls (true hazard ratio > 1), before and after calibration. Estimates below the diagonal dashed + lines are statistically significant (alpha = 0.05) different from the true effect size. A well-calibrated + estimator should have the true effect size within the 95 percent confidence interval 95 percent of times.""), + downloadButton(""downloadSystematicErrorPlot"", label = ""Download plot"")), + tabPanel(""Kaplan-Meier"", + plotOutput(""kaplanMeierPlot"", height = 550), + uiOutput(""kaplanMeierPlotPlotCaption""), + downloadButton(""downloadKaplanMeierPlot"", label = ""Download plot"")) #, + # tabPanel(""Subgroups"", + # uiOutput(""subgroupTableCaption""), + # dataTableOutput(""subgroupTable"")) + ) + ) + ) + ) + ) + ) + ) +) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","UkaTkaSafetyEffectiveness/inst/shiny/EvidenceExplorer/DataPulls.R",".R","16239","367","getExposureName <- function(connection, exposureId) { + sql <- ""SELECT exposure_name FROM single_exposure_of_interest WHERE exposure_id = @exposure_id + UNION ALL SELECT exposure_name FROM combi_exposure_of_interest WHERE exposure_id = @exposure_id"" + sql <- SqlRender::renderSql(sql, exposure_id = exposureId)$sql + sql <- SqlRender::translateSql(sql, targetDialect = connection@dbms)$sql + exposureName <- querySql(connection, sql) + return(exposureName[1, 1]) +} + +getExposureDescription <- function(connection, exposureId) { + sql <- ""SELECT description FROM single_exposure_of_interest WHERE exposure_id = @exposure_id + UNION ALL SELECT exposure_name FROM combi_exposure_of_interest WHERE exposure_id = @exposure_id"" + sql <- SqlRender::renderSql(sql, exposure_id = exposureId)$sql + sql <- SqlRender::translateSql(sql, targetDialect = connection@dbms)$sql + exposureDescription <- querySql(connection, sql) + return(exposureDescription[1, 1]) +} + +getOutcomeName <- function(connection, outcomeId) { + sql <- ""SELECT outcome_name FROM outcome_of_interest WHERE outcome_id = @outcome_id"" + sql <- SqlRender::renderSql(sql, outcome_id = outcomeId)$sql + sql <- SqlRender::translateSql(sql, targetDialect = connection@dbms)$sql + outcomeName <- querySql(connection, sql) + return(outcomeName[1, 1]) +} + +getIndications <- function(connection) { + sql <- ""SELECT indication_id, indication_name FROM indication"" + sql <- SqlRender::translateSql(sql, targetDialect = connection@dbms)$sql + indications <- querySql(connection, sql) + colnames(indications) <- SqlRender::snakeCaseToCamelCase(colnames(indications)) + return(indications) +} + +getSubgroups <- function(connection) { + sql <- ""SELECT DISTINCT interaction_covariate_id AS subgroup_id, covariate_name AS subgroup_name + FROM ( + SELECT DISTINCT interaction_covariate_id + FROM cm_interaction_result + ) ids + INNER JOIN covariate + ON interaction_covariate_id = covariate_id"" + sql <- SqlRender::translateSql(sql, targetDialect = connection@dbms)$sql + subgroups <- querySql(connection, sql) + colnames(subgroups) <- SqlRender::snakeCaseToCamelCase(colnames(subgroups)) + subgroups$subgroupName <- gsub(""Subgroup: "", """", subgroups$subgroupName) + return(subgroups) +} + + +getExposures <- function(connection) { + sql <- ""SELECT * FROM ( + SELECT exposure_id, exposure_name, indication_id FROM single_exposure_of_interest + UNION ALL SELECT exposure_id, exposure_name, indication_id FROM combi_exposure_of_interest + ) exposure + INNER JOIN exposure_group + ON exposure.exposure_id = exposure_group.exposure_id;"" + sql <- SqlRender::translateSql(sql, targetDialect = connection@dbms)$sql + exposures <- querySql(connection, sql) + colnames(exposures) <- SqlRender::snakeCaseToCamelCase(colnames(exposures)) + return(exposures) +} + +getOutcomes <- function(connection) { + sql <- ""SELECT outcome_id, outcome_name, indication_id FROM outcome_of_interest"" + sql <- SqlRender::translateSql(sql, targetDialect = connection@dbms)$sql + outcomes <- querySql(connection, sql) + colnames(outcomes) <- SqlRender::snakeCaseToCamelCase(colnames(outcomes)) + return(outcomes) +} + +getAnalyses <- function(connection) { + sql <- ""SELECT analysis_id, description FROM cohort_method_analysis"" + sql <- SqlRender::translateSql(sql, targetDialect = connection@dbms)$sql + analyses <- querySql(connection, sql) + colnames(analyses) <- SqlRender::snakeCaseToCamelCase(colnames(analyses)) + return(analyses) +} + +getDatabases <- function(connection) { + sql <- ""SELECT * FROM database"" + sql <- SqlRender::translateSql(sql, targetDialect = connection@dbms)$sql + databases <- querySql(connection, sql) + colnames(databases) <- SqlRender::snakeCaseToCamelCase(colnames(databases)) + return(databases) +} + +getDatabaseDetails <- function(connection, databaseId) { + sql <- ""SELECT * FROM database WHERE database_id = '@database_id'"" + sql <- SqlRender::renderSql(sql, database_id = databaseId)$sql + sql <- SqlRender::translateSql(sql, targetDialect = connection@dbms)$sql + databaseDetails <- querySql(connection, sql) + colnames(databaseDetails) <- SqlRender::snakeCaseToCamelCase(colnames(databaseDetails)) + databaseDetails$description <- sub(""\\n"", "" "", databaseDetails$description) + databaseDetails$description <- sub(""JDMC"", ""JMDC"", databaseDetails$description) # TODO Fix in schema + return(databaseDetails) +} + +getIndicationForExposure <- function(connection, + exposureIds = c()) { + sql <- ""SELECT exposure_id, indication_id FROM single_exposure_of_interest WHERE"" + sql <- paste(sql, paste0(""exposure_id IN ("", paste(exposureIds, collapse = "", ""), "")"")) + + sql <- SqlRender::translateSql(sql, targetDialect = connection@dbms)$sql + indications <- querySql(connection, sql) + colnames(indications) <- SqlRender::snakeCaseToCamelCase(colnames(indications)) + return(indications) +} + +getTcoDbs <- function(connection, + targetIds = c(), + comparatorIds = c(), + outcomeIds = c(), + databaseIds = c(), + operator = ""AND"") { + sql <- ""SELECT target_id, comparator_id, outcome_id, database_id FROM cohort_method_result WHERE analysis_id = 1"" + parts <- c() + if (length(targetIds) != 0) { + parts <- c(parts, paste0(""target_id IN ("", paste(targetIds, collapse = "", ""), "")"")) + } + if (length(comparatorIds) != 0) { + parts <- c(parts, paste0(""comparator_id IN ("", paste(comparatorIds, collapse = "", ""), "")"")) + } + if (length(outcomeIds) != 0) { + parts <- c(parts, paste0(""outcome_id IN ("", paste(outcomeIds, collapse = "", ""), "")"")) + } + if (length(databaseIds) != 0) { + parts <- c(parts, paste0(""database_id IN ('"", paste(databaseIds, collapse = ""', '""), ""')"")) + } + if (length(parts) != 0) { + if (operator == ""AND"") { + sql <- paste(sql, ""AND"", paste(parts, collapse = "" AND "")) + } else { + sql <- paste(sql, ""AND"", paste(parts, collapse = "" OR "")) + } + } + sql <- SqlRender::translateSql(sql, targetDialect = connection@dbms)$sql + tcoDbs <- querySql(connection, sql) + colnames(tcoDbs) <- SqlRender::snakeCaseToCamelCase(colnames(tcoDbs)) + return(tcoDbs) +} + +getTcoDbsStrict <- function(connection, exposureIds = c(), outcomeIds = c(), databaseIds = c()) { + sql <- ""SELECT target_id, comparator_id, outcome_id, database_id FROM cohort_method_result WHERE analysis_id = 1"" + parts <- c() + if (length(exposureIds) != 0) { + for (exposureId in exposureIds) { + parts <- c(parts, + paste0(""(target_id = "", exposureId, "" OR comparator_id = "", exposureId, "")"")) + } + } + if (length(outcomeIds) != 0) { + parts <- c(parts, paste0(""outcome_id IN ("", paste(outcomeIds, collapse = "", ""), "")"")) + } + if (length(databaseIds) != 0) { + parts <- c(parts, paste0(""database_id IN ('"", paste(databaseIds, collapse = ""', '""), ""')"")) + } + if (length(parts) != 0) { + sql <- paste(sql, ""AND"", paste(parts, collapse = "" AND "")) + } + sql <- SqlRender::translateSql(sql, targetDialect = connection@dbms)$sql + tcoDbs <- querySql(connection, sql) + colnames(tcoDbs) <- SqlRender::snakeCaseToCamelCase(colnames(tcoDbs)) + return(tcoDbs) +} + +getMainResults <- function(connection, + targetIds = c(), + comparatorIds = c(), + outcomeIds = c(), + databaseIds = c(), + analysisIds = c()) { + idx <- rep(TRUE, nrow(cohortMethodResult)) + if (length(targetIds) != 0) { + idx <- idx & cohortMethodResult$targetId %in% targetIds + } + if (length(comparatorIds) != 0) { + idx <- idx & cohortMethodResult$comparatorId %in% comparatorIds + } + if (length(outcomeIds) != 0) { + idx <- idx & cohortMethodResult$outcomeId %in% outcomeIds + } + if (length(databaseIds) != 0) { + idx <- idx & cohortMethodResult$databaseId %in% databaseIds + } + if (length(analysisIds) != 0) { + idx <- idx & cohortMethodResult$analysisId %in% analysisIds + } + result <- cohortMethodResult[idx, ] + result <- result[order(result$analysisId), ] + return(result) +} + +getSubgroupResults <- function(connection, + targetIds = c(), + comparatorIds = c(), + outcomeIds = c(), + databaseIds = c(), + analysisIds = c(), + subgroupIds = c(), + estimatesOnly = FALSE) { + idx <- rep(TRUE, nrow(cmInteractionResult)) + if (length(targetIds) != 0) { + idx <- idx & cmInteractionResult$targetId %in% targetIds + } + if (length(comparatorIds) != 0) { + idx <- idx & cmInteractionResult$comparatorId %in% comparatorIds + } + if (length(outcomeIds) != 0) { + idx <- idx & cmInteractionResult$outcomeId %in% outcomeIds + } + if (length(databaseIds) != 0) { + idx <- idx & cmInteractionResult$databaseId %in% databaseIds + } + if (length(analysisIds) != 0) { + idx <- idx & cmInteractionResult$analysisId %in% analysisIds + } + if (length(subgroupIds) != 0) { + idx <- idx & cmInteractionResult$interactionCovariateId %in% subgroupIds + } + result <- cmInteractionResult[idx, ] + result <- merge(result, data.frame(interactionCovariateId = covariate$covariateId, + databaseId = covariate$databaseId, + covariateName = covariate$covariateName)) + result <- result[, c(""covariateName"", + ""targetSubjects"", + ""comparatorSubjects"", + ""rrr"", + ""ci95Lb"", + ""ci95Ub"", + ""p"", + ""calibratedP"")] + colnames(result) <- c(""interactionCovariateName"", + ""targetSubjects"", + ""comparatorSubjects"", + ""rrr"", + ""ci95Lb"", + ""ci95Ub"", + ""p"", + ""calibratedP"") + return(result) +} + +getControlResults <- function(connection, targetId, comparatorId, analysisId, databaseId) { + results <- cohortMethodResult[cohortMethodResult$targetId == targetId & + cohortMethodResult$comparatorId == comparatorId & + cohortMethodResult$analysisId == analysisId & + cohortMethodResult$databaseId == databaseId, ] + results$effectSize <- NA + idx <- results$outcomeId %in% negativeControlOutcome$outcomeId + results$effectSize[idx] <- 1 + if (!is.null(positiveControlOutcome)) { + idx <- results$outcomeId %in% positiveControlOutcome$outcomeId + results$effectSize[idx] <- positiveControlOutcome$effectSize[match(results$outcomeId[idx], + positiveControlOutcome$outcomeId)] + } + results <- results[!is.na(results$effectSize), ] + return(results) +} + +getCmFollowUpDist <- function(connection, + targetId, + comparatorId, + outcomeId, + databaseId, + analysisId) { + followUpDist <- cmFollowUpDist[cmFollowUpDist$targetId == targetId & + cmFollowUpDist$comparatorId == comparatorId & + cmFollowUpDist$outcomeId == outcomeId & + cmFollowUpDist$analysisId == analysisId & + cmFollowUpDist$databaseId == databaseId, ] + return(followUpDist) +} + +getCovariateBalance <- function(connection, + targetId, + comparatorId, + databaseId, + analysisId, + outcomeId = NULL) { + # file <- sprintf(""covariate_balance_t%s_c%s_%s.rds"", targetId, comparatorId, databaseId) + file <- sprintf(""covariate_balance_t%s_c%s.rds"", targetId, comparatorId) + balance <- readRDS(file.path(dataFolder, file)) + colnames(balance) <- SqlRender::snakeCaseToCamelCase(colnames(balance)) + levels(balance$databaseId)[levels(balance$databaseId) == ""thin""] <- ""THIN"" + levels(balance$databaseId)[levels(balance$databaseId) == ""pmtx""] <- ""PharMetrics"" + balance <- balance[balance$analysisId == analysisId & balance$outcomeId == outcomeId & balance$databaseId == databaseId, ] + balance <- merge(balance, covariate[covariate$databaseId == databaseId, c(""covariateId"", ""covariateAnalysisId"", ""covariateName"")]) + balance <- balance[ c(""covariateId"", + ""covariateName"", + ""covariateAnalysisId"", + ""targetMeanBefore"", + ""comparatorMeanBefore"", + ""stdDiffBefore"", + ""targetMeanAfter"", + ""comparatorMeanAfter"", + ""stdDiffAfter"")] + colnames(balance) <- c(""covariateId"", + ""covariateName"", + ""analysisId"", + ""beforeMatchingMeanTreated"", + ""beforeMatchingMeanComparator"", + ""beforeMatchingStdDiff"", + ""afterMatchingMeanTreated"", + ""afterMatchingMeanComparator"", + ""afterMatchingStdDiff"") + balance$absBeforeMatchingStdDiff <- abs(balance$beforeMatchingStdDiff) + balance$absAfterMatchingStdDiff <- abs(balance$afterMatchingStdDiff) + return(balance) +} + +getPs <- function(connection, targetIds, comparatorIds, databaseId) { + file <- sprintf(""preference_score_dist_t%s_c%s.rds"", targetIds, comparatorIds) + ps <- readRDS(file.path(dataFolder, file)) + colnames(ps) <- SqlRender::snakeCaseToCamelCase(colnames(ps)) + levels(ps$databaseId)[levels(ps$databaseId) == ""thin""] <- ""THIN"" + levels(ps$databaseId)[levels(ps$databaseId) == ""pmtx""] <- ""PharMetrics"" + ps <- ps[ps$databaseId == databaseId, ] + return(ps) +} + +getKaplanMeier <- function(connection, targetId, comparatorId, outcomeId, databaseId, analysisId) { + file <- sprintf(""kaplan_meier_dist_t%s_c%s.rds"", targetId, comparatorId) + km <- readRDS(file.path(dataFolder, file)) + colnames(km) <- SqlRender::snakeCaseToCamelCase(colnames(km)) + levels(km$databaseId)[levels(km$databaseId) == ""thin""] <- ""THIN"" + levels(km$databaseId)[levels(km$databaseId) == ""pmtx""] <- ""PharMetrics"" + km <- km[km$outcomeId == outcomeId & + km$analysisId == analysisId & + km$databaseId == databaseId, ] + return(km) +} + +getAttrition <- function(connection, targetId, comparatorId, outcomeId, analysisId, databaseId) { + result <- attrition[attrition$targetId == targetId & + attrition$comparatorId == comparatorId & + attrition$outcomeId == outcomeId & + attrition$analysisId == analysisId & + attrition$databaseId == databaseId, ] + targetAttrition <- result[result$exposureId == targetId, ] + comparatorAttrition <- result[result$exposureId == comparatorId, ] + colnames(targetAttrition)[colnames(targetAttrition) == ""subjects""] <- ""targetPersons"" + targetAttrition$exposureId <- NULL + colnames(comparatorAttrition)[colnames(comparatorAttrition) == ""subjects""] <- ""comparatorPersons"" + comparatorAttrition$exposureId <- NULL + result <- merge(targetAttrition, comparatorAttrition) + result <- result[order(result$sequenceNumber), ] + return(result) +} + +getStudyPeriod <- function(connection, targetId, comparatorId, databaseId) { + sql <- ""SELECT min_date, + max_date + FROM comparison_summary + WHERE target_id = @target_id + AND comparator_id = @comparator_id + AND database_id = '@database_id'"" + sql <- SqlRender::renderSql(sql, + target_id = targetId, + comparator_id = comparatorId, + database_id = databaseId)$sql + sql <- SqlRender::translateSql(sql, targetDialect = connection@dbms)$sql + studyPeriod <- querySql(connection, sql) + colnames(studyPeriod) <- SqlRender::snakeCaseToCamelCase(colnames(studyPeriod)) + return(studyPeriod) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","UkaTkaSafetyEffectiveness/R/Export.R",".R","51236","1054","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of UkaTkaSafetyFull +# +# 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. + +#' Export all results to tables +#' +#' @description +#' Outputs all results to a folder called 'export', and zips them. +#' +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/). Do not use a folder on a network drive since this greatly impacts +#' performance. +#' @param databaseId A short string for identifying the database (e.g. 'Synpuf'). +#' @param databaseName The full name of the database. +#' @param databaseDescription A short description (several sentences) of the database. +#' @param minCellCount The minimum cell count for fields contains person counts or fractions. +#' @param maxCores How many parallel cores should be used? If more cores are made +#' available this can speed up the analyses. +#' +#' @export +exportResults <- function(outputFolder, + databaseId, + databaseName, + databaseDescription, + minCellCount = 5, + maxCores, + timeAtRiskLabel) { + exportFolder <- file.path(outputFolder, paste0(""export"", timeAtRiskLabel)) + if (!file.exists(exportFolder)) { + dir.create(exportFolder, recursive = TRUE) + } + + exportAnalyses(outputFolder = outputFolder, + exportFolder = exportFolder, + timeAtRiskLabel = timeAtRiskLabel) + + exportExposures(outputFolder = outputFolder, + exportFolder = exportFolder) + + exportOutcomes(outputFolder = outputFolder, + exportFolder = exportFolder, + timeAtRiskLabel = timeAtRiskLabel) + + exportMetadata(outputFolder = outputFolder, + exportFolder = exportFolder, + databaseId = databaseId, + databaseName = databaseName, + databaseDescription = databaseDescription, + minCellCount = minCellCount, + timeAtRiskLabel = timeAtRiskLabel) + + exportMainResults(outputFolder = outputFolder, + exportFolder = exportFolder, + databaseId = databaseId, + minCellCount = minCellCount, + maxCores = maxCores, + timeAtRiskLabel = timeAtRiskLabel) + + exportDiagnostics(outputFolder = outputFolder, + exportFolder = exportFolder, + databaseId = databaseId, + minCellCount = minCellCount, + maxCores = maxCores, + timeAtRiskLabel = timeAtRiskLabel) +} + +exportAnalyses <- function(outputFolder, + exportFolder, + timeAtRiskLabel) { + ParallelLogger::logInfo(""Exporting analyses"") + ParallelLogger::logInfo(""- cohort_method_analysis table"") + + tempFileName <- tempfile() + + cmAnalysisListFile <- system.file(""settings"", + ""cmAnalysisList.json"", + package = ""UkaTkaSafetyFull"") + cmAnalysisList <- CohortMethod::loadCmAnalysisList(cmAnalysisListFile) + cmAnalysisToRow <- function(cmAnalysis) { + ParallelLogger::saveSettingsToJson(cmAnalysis, tempFileName) + row <- data.frame(analysisId = cmAnalysis$analysisId, + description = cmAnalysis$description, + definition = readChar(tempFileName, file.info(tempFileName)$size)) + return(row) + } + cohortMethodAnalysis <- lapply(cmAnalysisList, cmAnalysisToRow) + cohortMethodAnalysis <- do.call(""rbind"", cohortMethodAnalysis) + cohortMethodAnalysis <- unique(cohortMethodAnalysis) + unlink(tempFileName) + colnames(cohortMethodAnalysis) <- SqlRender::camelCaseToSnakeCase(colnames(cohortMethodAnalysis)) + fileName <- file.path(exportFolder, ""cohort_method_analysis.csv"") + write.csv(cohortMethodAnalysis, fileName, row.names = FALSE) + + + ParallelLogger::logInfo(""- covariate_analysis table"") + reference <- readRDS(file.path(outputFolder, paste0(""cmOutput"", timeAtRiskLabel), ""outcomeModelReference.rds"")) + getCovariateAnalyses <- function(cmDataFolder) { + cmData <- CohortMethod::loadCohortMethodData(file.path(outputFolder, paste0(""cmOutput"", timeAtRiskLabel), cmDataFolder), readOnly = TRUE) + covariateAnalysis <- ff::as.ram(cmData$analysisRef) + covariateAnalysis <- covariateAnalysis[, c(""analysisId"", ""analysisName"")] + return(covariateAnalysis) + } + covariateAnalysis <- lapply(unique(reference$cohortMethodDataFolder), getCovariateAnalyses) + covariateAnalysis <- do.call(""rbind"", covariateAnalysis) + covariateAnalysis <- unique(covariateAnalysis) + colnames(covariateAnalysis) <- c(""covariate_analysis_id"", ""covariate_analysis_name"") + fileName <- file.path(exportFolder, ""covariate_analysis.csv"") + write.csv(covariateAnalysis, fileName, row.names = FALSE) +} + +exportExposures <- function(outputFolder, exportFolder) { + ParallelLogger::logInfo(""Exporting exposures"") + ParallelLogger::logInfo(""- exposure_of_interest table"") + pathToCsv <- system.file(""settings"", ""TcosOfInterest.csv"", package = ""UkaTkaSafetyFull"") + tcosOfInterest <- read.csv(pathToCsv, stringsAsFactors = FALSE) + pathToCsv <- system.file(""settings"", ""CohortsToCreate.csv"", package = ""UkaTkaSafetyFull"") + cohortsToCreate <- read.csv(pathToCsv) + createExposureRow <- function(exposureId) { + atlasName <- as.character(cohortsToCreate$atlasName[cohortsToCreate$cohortId == exposureId]) + name <- as.character(cohortsToCreate$name[cohortsToCreate$cohortId == exposureId]) + cohortFileName <- system.file(""cohorts"", paste0(name, "".json""), package = ""UkaTkaSafetyFull"") + definition <- readChar(cohortFileName, file.info(cohortFileName)$size) + return(data.frame(exposureId = exposureId, + exposureName = atlasName, + definition = definition)) + } + exposuresOfInterest <- unique(c(tcosOfInterest$targetId, tcosOfInterest$comparatorId)) + exposureOfInterest <- lapply(exposuresOfInterest, createExposureRow) + exposureOfInterest <- do.call(""rbind"", exposureOfInterest) + colnames(exposureOfInterest) <- SqlRender::camelCaseToSnakeCase(colnames(exposureOfInterest)) + fileName <- file.path(exportFolder, ""exposure_of_interest.csv"") + write.csv(exposureOfInterest, fileName, row.names = FALSE) +} + +exportOutcomes <- function(outputFolder, + exportFolder, + timeAtRiskLabel) { + ParallelLogger::logInfo(""Exporting outcomes"") + ParallelLogger::logInfo(""- outcome_of_interest table"") + pathToCsv <- system.file(""settings"", ""CohortsToCreate.csv"", package = ""UkaTkaSafetyFull"") + cohortsToCreate <- read.csv(pathToCsv) + createOutcomeRow <- function(outcomeId) { + atlasName <- as.character(cohortsToCreate$atlasName[cohortsToCreate$cohortId == outcomeId]) + name <- as.character(cohortsToCreate$name[cohortsToCreate$cohortId == outcomeId]) + cohortFileName <- system.file(""cohorts"", paste0(name, "".json""), package = ""UkaTkaSafetyFull"") + definition <- readChar(cohortFileName, file.info(cohortFileName)$size) + return(data.frame(outcomeId = outcomeId, + outcomeName = atlasName, + definition = definition)) + } + outcomesOfInterest <- getOutcomesOfInterest() + outcomeOfInterest <- lapply(outcomesOfInterest, createOutcomeRow) + outcomeOfInterest <- do.call(""rbind"", outcomeOfInterest) + colnames(outcomeOfInterest) <- SqlRender::camelCaseToSnakeCase(colnames(outcomeOfInterest)) + fileName <- file.path(exportFolder, ""outcome_of_interest.csv"") + write.csv(outcomeOfInterest, fileName, row.names = FALSE) + + + ParallelLogger::logInfo(""- negative_control_outcome table"") + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""UkaTkaSafetyFull"") + negativeControls <- read.csv(pathToCsv) + negativeControls <- negativeControls[tolower(negativeControls$type) == ""outcome"", ] + negativeControls <- negativeControls[, c(""outcomeId"", ""outcomeName"")] + colnames(negativeControls) <- SqlRender::camelCaseToSnakeCase(colnames(negativeControls)) + fileName <- file.path(exportFolder, ""negative_control_outcome.csv"") + write.csv(negativeControls, fileName, row.names = FALSE) + + + synthesisSummaryFile <- file.path(outputFolder, paste0(""SynthesisSummary"", timeAtRiskLabel, "".csv"")) + if (file.exists(synthesisSummaryFile)) { + positiveControls <- read.csv(synthesisSummaryFile, stringsAsFactors = FALSE) + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""UkaTkaSafetyFull"") + negativeControls <- read.csv(pathToCsv) + positiveControls <- merge(positiveControls, + negativeControls[, c(""outcomeId"", ""outcomeName"")]) + positiveControls$outcomeName <- paste0(positiveControls$outcomeName, + "", RR = "", + positiveControls$targetEffectSize) + positiveControls <- positiveControls[, c(""newOutcomeId"", + ""outcomeName"", + ""exposureId"", + ""outcomeId"", + ""targetEffectSize"")] + colnames(positiveControls) <- c(""outcomeId"", + ""outcomeName"", + ""exposureId"", + ""negativeControlId"", + ""effectSize"") + colnames(positiveControls) <- SqlRender::camelCaseToSnakeCase(colnames(positiveControls)) + fileName <- file.path(exportFolder, ""positive_control_outcome.csv"") + write.csv(positiveControls, fileName, row.names = FALSE) + } +} + +exportMetadata <- function(outputFolder, + exportFolder, + databaseId, + databaseName, + databaseDescription, + minCellCount, + timeAtRiskLabel) { + ParallelLogger::logInfo(""Exporting metadata"") + + getInfo <- function(row) { + cmData <- CohortMethod::loadCohortMethodData(file.path(outputFolder, paste0(""cmOutput"", timeAtRiskLabel), row$cohortMethodDataFolder), skipCovariates = TRUE) + info <- data.frame(targetId = row$targetId, + comparatorId = row$comparatorId, + targetMinDate = min(cmData$cohorts$cohortStartDate[cmData$cohorts$treatment == 1]), + targetMaxDate = max(cmData$cohorts$cohortStartDate[cmData$cohorts$treatment == 1]), + comparatorMinDate = min(cmData$cohorts$cohortStartDate[cmData$cohorts$treatment == 0]), + comparatorMaxDate = max(cmData$cohorts$cohortStartDate[cmData$cohorts$treatment == 0])) + info$comparisonMinDate <- min(info$targetMinDate, info$comparatorMinDate) + info$comparisonMaxDate <- min(info$targetMaxDate, info$comparatorMaxDate) + return(info) + } + reference <- readRDS(file.path(outputFolder, paste0(""cmOutput"", timeAtRiskLabel), ""outcomeModelReference.rds"")) + reference <- unique(reference[, c(""targetId"", ""comparatorId"", ""cohortMethodDataFolder"")]) + reference <- split(reference, reference$cohortMethodDataFolder, drop = TRUE) + info <- lapply(reference, getInfo) + info <- do.call(""rbind"", info) + + + ParallelLogger::logInfo(""- database table"") + database <- data.frame(database_id = databaseId, + database_name = databaseName, + description = databaseDescription, + is_meta_analysis = 0) + fileName <- file.path(exportFolder, ""database.csv"") + write.csv(database, fileName, row.names = FALSE) + + + ParallelLogger::logInfo(""- exposure_summary table"") + minDates <- rbind(data.frame(exposureId = info$targetId, + minDate = info$targetMinDate), + data.frame(exposureId = info$comparatorId, + minDate = info$comparatorMinDate)) + minDates <- aggregate(minDate ~ exposureId, minDates, min) + maxDates <- rbind(data.frame(exposureId = info$targetId, + maxDate = info$targetMaxDate), + data.frame(exposureId = info$comparatorId, + maxDate = info$comparatorMaxDate)) + maxDates <- aggregate(maxDate ~ exposureId, maxDates, max) + exposureSummary <- merge(minDates, maxDates) + exposureSummary$databaseId <- databaseId + colnames(exposureSummary) <- SqlRender::camelCaseToSnakeCase(colnames(exposureSummary)) + fileName <- file.path(exportFolder, ""exposure_summary.csv"") + write.csv(exposureSummary, fileName, row.names = FALSE) + + ParallelLogger::logInfo(""- comparison_summary table"") + minDates <- aggregate(comparisonMinDate ~ targetId + comparatorId, info, min) + maxDates <- aggregate(comparisonMaxDate ~ targetId + comparatorId, info, max) + comparisonSummary <- merge(minDates, maxDates) + comparisonSummary$databaseId <- databaseId + colnames(comparisonSummary)[colnames(comparisonSummary) == ""comparisonMinDate""] <- ""minDate"" + colnames(comparisonSummary)[colnames(comparisonSummary) == ""comparisonMaxDate""] <- ""maxDate"" + colnames(comparisonSummary) <- SqlRender::camelCaseToSnakeCase(colnames(comparisonSummary)) + fileName <- file.path(exportFolder, ""comparison_summary.csv"") + write.csv(comparisonSummary, fileName, row.names = FALSE) + + + ParallelLogger::logInfo(""- attrition table"") + fileName <- file.path(exportFolder, ""attrition.csv"") + if (file.exists(fileName)) { + unlink(fileName) + } + outcomesOfInterest <- getOutcomesOfInterest() + reference <- readRDS(file.path(outputFolder, paste0(""cmOutput"", timeAtRiskLabel), ""outcomeModelReference.rds"")) + reference <- reference[reference$outcomeId %in% outcomesOfInterest, ] + first <- !file.exists(fileName) + pb <- txtProgressBar(style = 3) + for (i in 1:nrow(reference)) { + outcomeModel <- readRDS(file.path(outputFolder, + paste0(""cmOutput"", timeAtRiskLabel), + reference$outcomeModelFile[i])) + attrition <- outcomeModel$attrition[, c(""description"", ""targetPersons"", ""comparatorPersons"")] + attrition$sequenceNumber <- 1:nrow(attrition) + attrition1 <- attrition[, c(""sequenceNumber"", ""description"", ""targetPersons"")] + colnames(attrition1)[3] <- ""subjects"" + attrition1$exposureId <- reference$targetId[i] + attrition2 <- attrition[, c(""sequenceNumber"", ""description"", ""comparatorPersons"")] + colnames(attrition2)[3] <- ""subjects"" + attrition2$exposureId <- reference$comparatorId[i] + attrition <- rbind(attrition1, attrition2) + attrition$targetId <- reference$targetId[i] + attrition$comparatorId <- reference$comparatorId[i] + attrition$analysisId <- reference$analysisId[i] + attrition$outcomeId <- reference$outcomeId[i] + attrition$databaseId <- databaseId + attrition <- attrition[, c(""databaseId"", + ""exposureId"", + ""targetId"", + ""comparatorId"", + ""outcomeId"", + ""analysisId"", + ""sequenceNumber"", + ""description"", + ""subjects"")] + attrition <- enforceMinCellValue(attrition, ""subjects"", minCellCount, silent = TRUE) + + colnames(attrition) <- SqlRender::camelCaseToSnakeCase(colnames(attrition)) + write.table(x = attrition, + file = fileName, + row.names = FALSE, + col.names = first, + sep = "","", + dec = ""."", + qmethod = ""double"", + append = !first) + first <- FALSE + if (i%%100 == 10) { + setTxtProgressBar(pb, i/nrow(reference)) + } + } + setTxtProgressBar(pb, 1) + close(pb) + + + ParallelLogger::logInfo(""- covariate table"") + reference <- readRDS(file.path(outputFolder, paste0(""cmOutput"", timeAtRiskLabel), ""outcomeModelReference.rds"")) + getCovariates <- function(cmDataFolder) { + cmData <- CohortMethod::loadCohortMethodData(file.path(outputFolder, paste0(""cmOutput"", timeAtRiskLabel), cmDataFolder), readOnly = TRUE) + covariateRef <- ff::as.ram(cmData$covariateRef) + covariateRef <- covariateRef[, c(""covariateId"", ""covariateName"", ""analysisId"")] + colnames(covariateRef) <- c(""covariateId"", ""covariateName"", ""covariateAnalysisId"") + return(covariateRef) + } + covariates <- lapply(unique(reference$cohortMethodDataFolder), getCovariates) + covariates <- do.call(""rbind"", covariates) + covariates <- unique(covariates) + covariates$databaseId <- databaseId + colnames(covariates) <- SqlRender::camelCaseToSnakeCase(colnames(covariates)) + fileName <- file.path(exportFolder, ""covariate.csv"") + write.csv(covariates, fileName, row.names = FALSE) + rm(covariates) # Free up memory + + + ParallelLogger::logInfo(""- cm_follow_up_dist table"") + getResult <- function(i) { + if (reference$strataFile[i] == """") { + strataPop <- readRDS(file.path(outputFolder, + paste0(""cmOutput"", timeAtRiskLabel), + reference$studyPopFile[i])) + } else { + strataPop <- readRDS(file.path(outputFolder, + paste0(""cmOutput"", timeAtRiskLabel), + reference$strataFile[i])) + } + + targetDist <- quantile(strataPop$survivalTime[strataPop$treatment == 1], + c(0, 0.1, 0.25, 0.5, 0.85, 0.9, 1)) + comparatorDist <- quantile(strataPop$survivalTime[strataPop$treatment == 0], + c(0, 0.1, 0.25, 0.5, 0.85, 0.9, 1)) + row <- data.frame(target_id = reference$targetId[i], + comparator_id = reference$comparatorId[i], + outcome_id = reference$outcomeId[i], + analysis_id = reference$analysisId[i], + target_min_days = targetDist[1], + target_p10_days = targetDist[2], + target_p25_days = targetDist[3], + target_median_days = targetDist[4], + target_p75_days = targetDist[5], + target_p90_days = targetDist[6], + target_max_days = targetDist[7], + comparator_min_days = comparatorDist[1], + comparator_p10_days = comparatorDist[2], + comparator_p25_days = comparatorDist[3], + comparator_median_days = comparatorDist[4], + comparator_p75_days = comparatorDist[5], + comparator_p90_days = comparatorDist[6], + comparator_max_days = comparatorDist[7]) + return(row) + } + outcomesOfInterest <- getOutcomesOfInterest() + reference <- readRDS(file.path(outputFolder, paste0(""cmOutput"", timeAtRiskLabel), ""outcomeModelReference.rds"")) + reference <- reference[reference$outcomeId %in% outcomesOfInterest, ] + results <- plyr::llply(1:nrow(reference), getResult, .progress = ""text"") + results <- do.call(""rbind"", results) + results$database_id <- databaseId + fileName <- file.path(exportFolder, ""cm_follow_up_dist.csv"") + write.csv(results, fileName, row.names = FALSE) + rm(results) # Free up memory +} + +enforceMinCellValue <- function(data, fieldName, minValues, silent = FALSE) { + toCensor <- !is.na(data[, fieldName]) & data[, fieldName] < minValues & data[, fieldName] != 0 + if (!silent) { + percent <- round(100 * sum(toCensor)/nrow(data), 1) + ParallelLogger::logInfo("" censoring "", + sum(toCensor), + "" values ("", + percent, + ""%) from "", + fieldName, + "" because value below minimum"") + } + if (length(minValues) == 1) { + data[toCensor, fieldName] <- -minValues + } else { + data[toCensor, fieldName] <- -minValues[toCensor] + } + return(data) +} + + +exportMainResults <- function(outputFolder, + exportFolder, + databaseId, + minCellCount, + maxCores, + timeAtRiskLabel) { + ParallelLogger::logInfo(""Exporting main results"") + + + ParallelLogger::logInfo(""- cohort_method_result table"") + analysesSum <- read.csv(file.path(outputFolder, paste0(""analysisSummary"", timeAtRiskLabel, "".csv""))) + allControls <- getAllControls(outputFolder, timeAtRiskLabel) + ParallelLogger::logInfo("" Performing empirical calibration on main effects"") + cluster <- ParallelLogger::makeCluster(min(4, maxCores)) + subsets <- split(analysesSum, + paste(analysesSum$targetId, analysesSum$comparatorId, analysesSum$analysisId), drop = TRUE) + rm(analysesSum) # Free up memory + results <- ParallelLogger::clusterApply(cluster, + subsets, + calibrate, + allControls = allControls) + ParallelLogger::stopCluster(cluster) + rm(subsets) # Free up memory + results <- do.call(""rbind"", results) + results$databaseId <- databaseId + results <- enforceMinCellValue(results, ""targetSubjects"", minCellCount) + results <- enforceMinCellValue(results, ""comparatorSubjects"", minCellCount) + results <- enforceMinCellValue(results, ""targetOutcomes"", minCellCount) + results <- enforceMinCellValue(results, ""comparatorOutcomes"", minCellCount) + colnames(results) <- SqlRender::camelCaseToSnakeCase(colnames(results)) + fileName <- file.path(exportFolder, ""cohort_method_result.csv"") + write.csv(results, fileName, row.names = FALSE) + rm(results) # Free up memory + + ParallelLogger::logInfo(""- cm_interaction_result table"") + reference <- readRDS(file.path(outputFolder, paste0(""cmOutput"", timeAtRiskLabel), ""outcomeModelReference.rds"")) + loadInteractionsFromOutcomeModel <- function(i) { + outcomeModel <- readRDS(file.path(outputFolder, + paste0(""cmOutput"", timeAtRiskLabel), + reference$outcomeModelFile[i])) + if (!is.null(outcomeModel$subgroupCounts)) { + rows <- data.frame(targetId = reference$targetId[i], + comparatorId = reference$comparatorId[i], + outcomeId = reference$outcomeId[i], + analysisId = reference$analysisId[i], + interactionCovariateId = outcomeModel$subgroupCounts$subgroupCovariateId, + rrr = NA, + ci95Lb = NA, + ci95Ub = NA, + p = NA, + i2 = NA, + logRrr = NA, + seLogRrr = NA, + targetSubjects = outcomeModel$subgroupCounts$targetPersons, + comparatorSubjects = outcomeModel$subgroupCounts$comparatorPersons, + targetDays = outcomeModel$subgroupCounts$targetDays, + comparatorDays = outcomeModel$subgroupCounts$comparatorDays, + targetOutcomes = outcomeModel$subgroupCounts$targetOutcomes, + comparatorOutcomes = outcomeModel$subgroupCounts$comparatorOutcomes) + if (!is.null(outcomeModel$outcomeModelInteractionEstimates)) { + idx <- match(outcomeModel$outcomeModelInteractionEstimates$covariateId, + rows$interactionCovariateId) + rows$rrr[idx] <- exp(outcomeModel$outcomeModelInteractionEstimates$logRr) + rows$ci95Lb[idx] <- exp(outcomeModel$outcomeModelInteractionEstimates$logLb95) + rows$ci95Ub[idx] <- exp(outcomeModel$outcomeModelInteractionEstimates$logUb95) + rows$logRrr[idx] <- outcomeModel$outcomeModelInteractionEstimates$logRr + rows$seLogRrr[idx] <- outcomeModel$outcomeModelInteractionEstimates$seLogRr + z <- rows$logRrr[idx]/rows$seLogRrr[idx] + rows$p[idx] <- 2 * pmin(pnorm(z), 1 - pnorm(z)) + } + return(rows) + } else { + return(NULL) + } + + } + interactions <- plyr::llply(1:nrow(reference), + loadInteractionsFromOutcomeModel, + .progress = ""text"") + interactions <- do.call(""rbind"", interactions) + if (!is.null(interactions)) { + ParallelLogger::logInfo("" Performing empirical calibration on interaction effects"") + allControls <- getAllControls(outputFolder, timeAtRiskLabel) + negativeControls <- allControls[allControls$targetEffectSize == 1, ] + cluster <- ParallelLogger::makeCluster(min(4, maxCores)) + subsets <- split(interactions, + paste(interactions$targetId, interactions$comparatorId, interactions$analysisId)) + interactions <- ParallelLogger::clusterApply(cluster, + subsets, + calibrateInteractions, + negativeControls = negativeControls) + ParallelLogger::stopCluster(cluster) + rm(subsets) # Free up memory + interactions <- do.call(""rbind"", interactions) + interactions$databaseId <- databaseId + + interactions <- enforceMinCellValue(interactions, ""targetSubjects"", minCellCount) + interactions <- enforceMinCellValue(interactions, ""comparatorSubjects"", minCellCount) + interactions <- enforceMinCellValue(interactions, ""targetOutcomes"", minCellCount) + interactions <- enforceMinCellValue(interactions, ""comparatorOutcomes"", minCellCount) + colnames(interactions) <- SqlRender::camelCaseToSnakeCase(colnames(interactions)) + fileName <- file.path(exportFolder, ""cm_interaction_result.csv"") + write.csv(interactions, fileName, row.names = FALSE) + rm(interactions) # Free up memory + } +} + +calibrate <- function(subset, allControls) { + ncs <- subset[subset$outcomeId %in% allControls$outcomeId[allControls$targetEffectSize == 1], ] + ncs <- ncs[!is.na(ncs$seLogRr), ] + if (nrow(ncs) > 5) { + null <- EmpiricalCalibration::fitMcmcNull(ncs$logRr, ncs$seLogRr) + calibratedP <- EmpiricalCalibration::calibrateP(null = null, + logRr = subset$logRr, + seLogRr = subset$seLogRr) + subset$calibratedP <- calibratedP$p + } else { + subset$calibratedP <- rep(NA, nrow(subset)) + } + pcs <- subset[subset$outcomeId %in% allControls$outcomeId[allControls$targetEffectSize != 1], ] + pcs <- pcs[!is.na(pcs$seLogRr), ] + if (nrow(pcs) > 5) { + controls <- merge(subset, allControls[, c(""targetId"", ""comparatorId"", ""outcomeId"", ""targetEffectSize"")]) + model <- EmpiricalCalibration::fitSystematicErrorModel(logRr = controls$logRr, + seLogRr = controls$seLogRr, + trueLogRr = log(controls$targetEffectSize), + estimateCovarianceMatrix = FALSE) + calibratedCi <- EmpiricalCalibration::calibrateConfidenceInterval(logRr = subset$logRr, + seLogRr = subset$seLogRr, + model = model) + subset$calibratedRr <- exp(calibratedCi$logRr) + subset$calibratedCi95Lb <- exp(calibratedCi$logLb95Rr) + subset$calibratedCi95Ub <- exp(calibratedCi$logUb95Rr) + subset$calibratedLogRr <- calibratedCi$logRr + subset$calibratedSeLogRr <- calibratedCi$seLogRr + } else { + subset$calibratedRr <- rep(NA, nrow(subset)) + subset$calibratedCi95Lb <- rep(NA, nrow(subset)) + subset$calibratedCi95Ub <- rep(NA, nrow(subset)) + subset$calibratedLogRr <- rep(NA, nrow(subset)) + subset$calibratedSeLogRr <- rep(NA, nrow(subset)) + } + subset$i2 <- rep(NA, nrow(subset)) + subset <- subset[, c(""targetId"", + ""comparatorId"", + ""outcomeId"", + ""analysisId"", + ""rr"", + ""ci95lb"", + ""ci95ub"", + ""p"", + ""i2"", + ""logRr"", + ""seLogRr"", + ""target"", + ""comparator"", + ""targetDays"", + ""comparatorDays"", + ""eventsTarget"", + ""eventsComparator"", + ""calibratedP"", + ""calibratedRr"", + ""calibratedCi95Lb"", + ""calibratedCi95Ub"", + ""calibratedLogRr"", + ""calibratedSeLogRr"")] + colnames(subset) <- c(""targetId"", + ""comparatorId"", + ""outcomeId"", + ""analysisId"", + ""rr"", + ""ci95Lb"", + ""ci95Ub"", + ""p"", + ""i2"", + ""logRr"", + ""seLogRr"", + ""targetSubjects"", + ""comparatorSubjects"", + ""targetDays"", + ""comparatorDays"", + ""targetOutcomes"", + ""comparatorOutcomes"", + ""calibratedP"", + ""calibratedRr"", + ""calibratedCi95Lb"", + ""calibratedCi95Ub"", + ""calibratedLogRr"", + ""calibratedSeLogRr"") + return(subset) +} + +calibrateInteractions <- function(subset, negativeControls) { + ncs <- subset[subset$outcomeId %in% negativeControls$outcomeId, ] + ncs <- ncs[!is.na(ncs$seLogRr), ] + if (nrow(ncs) > 5) { + null <- EmpiricalCalibration::fitMcmcNull(ncs$logRr, ncs$seLogRr) + calibratedP <- EmpiricalCalibration::calibrateP(null = null, + logRr = subset$logRr, + seLogRr = subset$seLogRr) + subset$calibratedP <- calibratedP$p + } else { + subset$calibratedP <- rep(NA, nrow(subset)) + } + return(subset) +} + + +exportDiagnostics <- function(outputFolder, + exportFolder, + databaseId, + minCellCount, + maxCores, + timeAtRiskLabel) { + ParallelLogger::logInfo(""Exporting diagnostics"") + + ParallelLogger::logInfo(""- covariate_balance table"") + fileName <- file.path(exportFolder, ""covariate_balance.csv"") + if (!file.exists(fileName)) { + if (file.exists(fileName)) { + unlink(fileName) + } + first <- TRUE + balanceFolder <- file.path(outputFolder, ""balance"") + files <- list.files(balanceFolder, pattern = ""bal_.*.rds"", full.names = TRUE) + pb <- txtProgressBar(style = 3) + + for (i in 1:length(files)) { + ids <- gsub(""^.*bal_t"", """", files[i]) + targetId <- as.numeric(gsub(""_c.*"", """", ids)) + ids <- gsub(""^.*_c"", """", ids) + comparatorId <- as.numeric(gsub(""_[aso].*$"", """", ids)) + if (grepl(""_s"", ids)) { + subgroupId <- as.numeric(gsub(""^.*_s"", """", gsub(""_a[0-9]*.rds"", """", ids))) + } else { + subgroupId <- NA + } + if (grepl(""_o"", ids)) { + outcomeId <- as.numeric(gsub(""^.*_o"", """", gsub(""_a[0-9]*.rds"", """", ids))) + } else { + outcomeId <- NA + } + ids <- gsub(""^.*_a"", """", ids) + analysisId <- as.numeric(gsub("".rds"", """", ids)) + balance <- readRDS(files[i]) + inferredTargetBeforeSize <- mean(balance$beforeMatchingSumTarget/balance$beforeMatchingMeanTarget, + na.rm = TRUE) + inferredComparatorBeforeSize <- mean(balance$beforeMatchingSumComparator/balance$beforeMatchingMeanComparator, + na.rm = TRUE) + inferredTargetAfterSize <- mean(balance$afterMatchingSumTarget/balance$afterMatchingMeanTarget, + na.rm = TRUE) + inferredComparatorAfterSize <- mean(balance$afterMatchingSumComparator/balance$afterMatchingMeanComparator, + na.rm = TRUE) + + balance$databaseId <- databaseId + balance$targetId <- targetId + balance$comparatorId <- comparatorId + balance$outcomeId <- outcomeId + balance$analysisId <- analysisId + balance$interactionCovariateId <- subgroupId + balance <- balance[, c(""databaseId"", + ""targetId"", + ""comparatorId"", + ""outcomeId"", + ""analysisId"", + ""interactionCovariateId"", + ""covariateId"", + ""beforeMatchingMeanTarget"", + ""beforeMatchingMeanComparator"", + ""beforeMatchingStdDiff"", + ""afterMatchingMeanTarget"", + ""afterMatchingMeanComparator"", + ""afterMatchingStdDiff"")] + colnames(balance) <- c(""databaseId"", + ""targetId"", + ""comparatorId"", + ""outcomeId"", + ""analysisId"", + ""interactionCovariateId"", + ""covariateId"", + ""targetMeanBefore"", + ""comparatorMeanBefore"", + ""stdDiffBefore"", + ""targetMeanAfter"", + ""comparatorMeanAfter"", + ""stdDiffAfter"") + balance$targetMeanBefore[is.na(balance$targetMeanBefore)] <- 0 + balance$comparatorMeanBefore[is.na(balance$comparatorMeanBefore)] <- 0 + balance$stdDiffBefore <- round(balance$stdDiffBefore, 3) + balance$targetMeanAfter[is.na(balance$targetMeanAfter)] <- 0 + balance$comparatorMeanAfter[is.na(balance$comparatorMeanAfter)] <- 0 + balance$stdDiffAfter <- round(balance$stdDiffAfter, 3) + balance <- enforceMinCellValue(balance, + ""targetMeanBefore"", + minCellCount/inferredTargetBeforeSize, + TRUE) + balance <- enforceMinCellValue(balance, + ""comparatorMeanBefore"", + minCellCount/inferredComparatorBeforeSize, + TRUE) + balance <- enforceMinCellValue(balance, + ""targetMeanAfter"", + minCellCount/inferredTargetAfterSize, + TRUE) + balance <- enforceMinCellValue(balance, + ""comparatorMeanAfter"", + minCellCount/inferredComparatorAfterSize, + TRUE) + balance$targetMeanBefore <- round(balance$targetMeanBefore, 3) + balance$comparatorMeanBefore <- round(balance$comparatorMeanBefore, 3) + balance$targetMeanAfter <- round(balance$targetMeanAfter, 3) + balance$comparatorMeanAfter <- round(balance$comparatorMeanAfter, 3) + balance <- balance[balance$targetMeanBefore != 0 & + balance$comparatorMeanBefore != 0 & + balance$targetMeanAfter != 0 & + balance$comparatorMeanAfter != 0, ] # & + # balance$stdDiffBefore != 0 & + # balance$stdDiffAfter != 0, ] + balance <- balance[!is.na(balance$targetId), ] + colnames(balance) <- SqlRender::camelCaseToSnakeCase(colnames(balance)) + write.table(x = balance, + file = fileName, + row.names = FALSE, + col.names = first, + sep = "","", + dec = ""."", + qmethod = ""double"", + append = !first) + first <- FALSE + setTxtProgressBar(pb, i/length(files)) + } + close(pb) + } + + ParallelLogger::logInfo(""- preference_score_dist table"") + preparePlot <- function(i, reference, timeAtRiskLabel) { + psFileName <- file.path(outputFolder, + paste0(""cmOutput"", timeAtRiskLabel), + reference$sharedPsFile[i]) + if (file.exists(psFileName)) { + ps <- readRDS(psFileName) + if (min(ps$propensityScore) < max(ps$propensityScore)) { + ps <- CohortMethod:::computePreferenceScore(ps) + + d1 <- density(ps$preferenceScore[ps$treatment == 1], from = 0, to = 1, n = 100) + d0 <- density(ps$preferenceScore[ps$treatment == 0], from = 0, to = 1, n = 100) + + result <- data.frame(databaseId = databaseId, + targetId = reference$targetId[i], + comparatorId = reference$comparatorId[i], + preferenceScore = d1$x, + targetDensity = d1$y, + comparatorDensity = d0$y) + return(result) + } + } + return(NULL) + } + reference <- readRDS(file.path(outputFolder, paste0(""cmOutput"", timeAtRiskLabel), ""outcomeModelReference.rds"")) + reference <- reference[order(reference$sharedPsFile), ] + reference <- reference[!duplicated(reference$sharedPsFile), ] + reference <- reference[reference$sharedPsFile != """", ] + data <- plyr::llply(1:nrow(reference), + preparePlot, + reference = reference, + timeAtRiskLabel = timeAtRiskLabel, + .progress = ""text"") + data <- do.call(""rbind"", data) + fileName <- file.path(exportFolder, ""preference_score_dist.csv"") + colnames(data) <- SqlRender::camelCaseToSnakeCase(colnames(data)) + write.csv(data, fileName, row.names = FALSE) + + + ParallelLogger::logInfo(""- propensity_model table"") + getPsModel <- function(i, reference) { + psFileName <- file.path(outputFolder, + paste0(""cmOutput"", timeAtRiskLabel), + reference$sharedPsFile[i]) + if (file.exists(psFileName)) { + ps <- readRDS(psFileName) + metaData <- attr(ps, ""metaData"") + if (is.null(metaData$psError)) { + cmDataFile <- file.path(outputFolder, + paste0(""cmOutput"", timeAtRiskLabel), + reference$cohortMethodDataFolder[i]) + cmData <- CohortMethod::loadCohortMethodData(cmDataFile) + model <- CohortMethod::getPsModel(ps, cmData) + model$covariateId[is.na(model$covariateId)] <- 0 + ff::close.ffdf(cmData$covariates) + ff::close.ffdf(cmData$covariateRef) + ff::close.ffdf(cmData$analysisRef) + model$databaseId <- databaseId + model$targetId <- reference$targetId[i] + model$comparatorId <- reference$comparatorId[i] + model <- model[, c(""databaseId"", ""targetId"", ""comparatorId"", ""covariateId"", ""coefficient"")] + return(model) + } + } + return(NULL) + } + reference <- readRDS(file.path(outputFolder, paste0(""cmOutput"", timeAtRiskLabel), ""outcomeModelReference.rds"")) + reference <- reference[order(reference$sharedPsFile), ] + reference <- reference[!duplicated(reference$sharedPsFile), ] + reference <- reference[reference$sharedPsFile != """", ] + data <- plyr::llply(1:nrow(reference), + getPsModel, + reference = reference, + .progress = ""text"") + data <- do.call(""rbind"", data) + fileName <- file.path(exportFolder, ""propensity_model.csv"") + colnames(data) <- SqlRender::camelCaseToSnakeCase(colnames(data)) + write.csv(data, fileName, row.names = FALSE) + + + ParallelLogger::logInfo(""- kaplan_meier_dist table"") + ParallelLogger::logInfo("" Computing KM curves"") + reference <- readRDS(file.path(outputFolder, paste0(""cmOutput"", timeAtRiskLabel), ""outcomeModelReference.rds"")) + outcomesOfInterest <- getOutcomesOfInterest() + reference <- reference[reference$outcomeId %in% outcomesOfInterest, ] + reference <- reference[, c(""strataFile"", + ""studyPopFile"", + ""targetId"", + ""comparatorId"", + ""outcomeId"", + ""analysisId"")] + tempFolder <- file.path(exportFolder, ""temp"") + if (!file.exists(tempFolder)) { + dir.create(tempFolder) + } + cluster <- ParallelLogger::makeCluster(min(4, maxCores)) + tasks <- split(reference, seq(nrow(reference)), drop = TRUE) + ParallelLogger::clusterApply(cluster, + tasks, + prepareKm, + outputFolder = outputFolder, + tempFolder = tempFolder, + databaseId = databaseId, + minCellCount = minCellCount, + timeAtRiskLabel = timeAtRiskLabel) + ParallelLogger::stopCluster(cluster) + ParallelLogger::logInfo("" Writing to single csv file"") + saveKmToCsv <- function(file, first, outputFile) { + data <- readRDS(file) + colnames(data) <- SqlRender::camelCaseToSnakeCase(colnames(data)) + write.table(x = data, + file = outputFile, + row.names = FALSE, + col.names = first, + sep = "","", + dec = ""."", + qmethod = ""double"", + append = !first) + } + outputFile <- file.path(exportFolder, ""kaplan_meier_dist.csv"") + files <- list.files(tempFolder, ""km_.*.rds"", full.names = TRUE) + saveKmToCsv(files[1], first = TRUE, outputFile = outputFile) + if (length(files) > 1) { + plyr::l_ply(files[2:length(files)], saveKmToCsv, first = FALSE, outputFile = outputFile, .progress = ""text"") + } + unlink(tempFolder, recursive = TRUE) +} + +prepareKm <- function(task, + outputFolder, + tempFolder, + databaseId, + minCellCount, + timeAtRiskLabel) { + ParallelLogger::logTrace(""Preparing KM plot for target "", + task$targetId, + "", comparator "", + task$comparatorId, + "", outcome "", + task$outcomeId, + "", analysis "", + task$analysisId) + outputFileName <- file.path(tempFolder, sprintf(""km_t%s_c%s_o%s_a%s.rds"", + task$targetId, + task$comparatorId, + task$outcomeId, + task$analysisId)) + if (file.exists(outputFileName)) { + return(NULL) + } + popFile <- task$strataFile + if (popFile == """") { + popFile <- task$studyPopFile + } + population <- readRDS(file.path(outputFolder, + paste0(""cmOutput"", timeAtRiskLabel), + popFile)) + if (nrow(population) == 0) { + # Can happen when matching and treatment is predictable + return(NULL) + } + data <- prepareKaplanMeier(population) + if (is.null(data)) { + # No shared strata + return(NULL) + } + data$targetId <- task$targetId + data$comparatorId <- task$comparatorId + data$outcomeId <- task$outcomeId + data$analysisId <- task$analysisId + data$databaseId <- databaseId + data <- enforceMinCellValue(data, ""targetAtRisk"", minCellCount) + data <- enforceMinCellValue(data, ""comparatorAtRisk"", minCellCount) + saveRDS(data, outputFileName) +} + +prepareKaplanMeier <- function(population) { + dataCutoff <- 0.9 + population$y <- 0 + population$y[population$outcomeCount != 0] <- 1 + if (is.null(population$stratumId) || length(unique(population$stratumId)) == nrow(population)/2) { + sv <- survival::survfit(survival::Surv(survivalTime, y) ~ treatment, population, conf.int = TRUE) + idx <- summary(sv, censored = T)$strata == ""treatment=1"" + survTarget <- data.frame(time = sv$time[idx], + targetSurvival = sv$surv[idx], + targetSurvivalLb = sv$lower[idx], + targetSurvivalUb = sv$upper[idx]) + idx <- summary(sv, censored = T)$strata == ""treatment=0"" + survComparator <- data.frame(time = sv$time[idx], + comparatorSurvival = sv$surv[idx], + comparatorSurvivalLb = sv$lower[idx], + comparatorSurvivalUb = sv$upper[idx]) + data <- merge(survTarget, survComparator, all = TRUE) + } else { + population$stratumSizeT <- 1 + strataSizesT <- aggregate(stratumSizeT ~ stratumId, population[population$treatment == 1, ], sum) + if (max(strataSizesT$stratumSizeT) == 1) { + # variable ratio matching: use propensity score to compute IPTW + if (is.null(population$propensityScore)) { + stop(""Variable ratio matching detected, but no propensity score found"") + } + weights <- aggregate(propensityScore ~ stratumId, population, mean) + if (max(weights$propensityScore) > 0.99999) { + return(NULL) + } + weights$weight <- weights$propensityScore / (1 - weights$propensityScore) + } else { + # stratification: infer probability of treatment from subject counts + strataSizesC <- aggregate(stratumSizeT ~ stratumId, population[population$treatment == 0, ], sum) + colnames(strataSizesC)[2] <- ""stratumSizeC"" + weights <- merge(strataSizesT, strataSizesC) + if (nrow(weights) == 0) { + warning(""No shared strata between target and comparator"") + return(NULL) + } + weights$weight <- weights$stratumSizeT/weights$stratumSizeC + } + population <- merge(population, weights[, c(""stratumId"", ""weight"")]) + population$weight[population$treatment == 1] <- 1 + idx <- population$treatment == 1 + survTarget <- CohortMethod:::adjustedKm(weight = population$weight[idx], + time = population$survivalTime[idx], + y = population$y[idx]) + survTarget$targetSurvivalUb <- survTarget$s^exp(qnorm(0.975)/log(survTarget$s) * sqrt(survTarget$var)/survTarget$s) + survTarget$targetSurvivalLb <- survTarget$s^exp(qnorm(0.025)/log(survTarget$s) * sqrt(survTarget$var)/survTarget$s) + survTarget$targetSurvivalLb[survTarget$s > 0.9999] <- survTarget$s[survTarget$s > 0.9999] + survTarget$targetSurvival <- survTarget$s + survTarget$s <- NULL + survTarget$var <- NULL + idx <- population$treatment == 0 + survComparator <- CohortMethod:::adjustedKm(weight = population$weight[idx], + time = population$survivalTime[idx], + y = population$y[idx]) + survComparator$comparatorSurvivalUb <- survComparator$s^exp(qnorm(0.975)/log(survComparator$s) * + sqrt(survComparator$var)/survComparator$s) + survComparator$comparatorSurvivalLb <- survComparator$s^exp(qnorm(0.025)/log(survComparator$s) * + sqrt(survComparator$var)/survComparator$s) + survComparator$comparatorSurvivalLb[survComparator$s > 0.9999] <- survComparator$s[survComparator$s > + 0.9999] + survComparator$comparatorSurvival <- survComparator$s + survComparator$s <- NULL + survComparator$var <- NULL + data <- merge(survTarget, survComparator, all = TRUE) + } + data <- data[, c(""time"", ""targetSurvival"", ""targetSurvivalLb"", ""targetSurvivalUb"", ""comparatorSurvival"", ""comparatorSurvivalLb"", ""comparatorSurvivalUb"")] + cutoff <- quantile(population$survivalTime, dataCutoff) + data <- data[data$time <= cutoff, ] + if (cutoff <= 300) { + xBreaks <- seq(0, cutoff, by = 50) + } else if (cutoff <= 600) { + xBreaks <- seq(0, cutoff, by = 100) + } else { + xBreaks <- seq(0, cutoff, by = 250) + } + + targetAtRisk <- c() + comparatorAtRisk <- c() + for (xBreak in xBreaks) { + targetAtRisk <- c(targetAtRisk, + sum(population$treatment == 1 & population$survivalTime >= xBreak)) + comparatorAtRisk <- c(comparatorAtRisk, + sum(population$treatment == 0 & population$survivalTime >= + xBreak)) + } + data <- merge(data, data.frame(time = xBreaks, + targetAtRisk = targetAtRisk, + comparatorAtRisk = comparatorAtRisk), all = TRUE) + if (is.na(data$targetSurvival[1])) { + data$targetSurvival[1] <- 1 + data$targetSurvivalUb[1] <- 1 + data$targetSurvivalLb[1] <- 1 + } + if (is.na(data$comparatorSurvival[1])) { + data$comparatorSurvival[1] <- 1 + data$comparatorSurvivalUb[1] <- 1 + data$comparatorSurvivalLb[1] <- 1 + } + idx <- which(is.na(data$targetSurvival)) + while (length(idx) > 0) { + data$targetSurvival[idx] <- data$targetSurvival[idx - 1] + data$targetSurvivalLb[idx] <- data$targetSurvivalLb[idx - 1] + data$targetSurvivalUb[idx] <- data$targetSurvivalUb[idx - 1] + idx <- which(is.na(data$targetSurvival)) + } + idx <- which(is.na(data$comparatorSurvival)) + while (length(idx) > 0) { + data$comparatorSurvival[idx] <- data$comparatorSurvival[idx - 1] + data$comparatorSurvivalLb[idx] <- data$comparatorSurvivalLb[idx - 1] + data$comparatorSurvivalUb[idx] <- data$comparatorSurvivalUb[idx - 1] + idx <- which(is.na(data$comparatorSurvival)) + } + data$targetSurvival <- round(data$targetSurvival, 4) + data$targetSurvivalLb <- round(data$targetSurvivalLb, 4) + data$targetSurvivalUb <- round(data$targetSurvivalUb, 4) + data$comparatorSurvival <- round(data$comparatorSurvival, 4) + data$comparatorSurvivalLb <- round(data$comparatorSurvivalLb, 4) + data$comparatorSurvivalUb <- round(data$comparatorSurvivalUb, 4) + + # Remove duplicate (except time) entries: + data <- data[order(data$time), ] + data <- data[!duplicated(data[, -1]), ] + return(data) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","UkaTkaSafetyEffectiveness/R/Main.R",".R","9533","195","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of UkaTkaSafetyFull +# +# 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. + +#' Execute the Study +#' +#' @details +#' This function executes the UkaTkaSafetyFull Study. +#' +#' The \code{createCohorts}, \code{synthesizePositiveControls}, \code{runAnalyses}, and \code{runDiagnostics} arguments +#' are intended to be used to run parts of the full study at a time, but none of the parts are considerd to be optional. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param cohortDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param cohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/). Do not use a folder on a network drive since this greatly impacts +#' performance. +#' @param databaseId A short string for identifying the database (e.g. +#' 'Synpuf'). +#' @param databaseName The full name of the database (e.g. 'Medicare Claims +#' Synthetic Public Use Files (SynPUFs)'). +#' @param databaseDescription A short description (several sentences) of the database. +#' @param createCohorts Create the cohortTable table with the exposure and outcome cohorts? +#' @param synthesizePositiveControls Should positive controls be synthesized? +#' @param runAnalyses Perform the cohort method analyses? +#' @param runDiagnostics Compute study diagnostics? +#' @param packageResults Should results be packaged for later sharing? +#' @param maxCores How many parallel cores should be used? If more cores are made available +#' this can speed up the analyses. +#' @param minCellCount The minimum number of subjects contributing to a count before it can be included +#' in packaged results. +#' +#' @examples +#' \dontrun{ +#' connectionDetails <- createConnectionDetails(dbms = ""postgresql"", +#' user = ""joe"", +#' password = ""secret"", +#' server = ""myserver"") +#' +#' execute(connectionDetails, +#' cdmDatabaseSchema = ""cdm_data"", +#' cohortDatabaseSchema = ""study_results"", +#' cohortTable = ""cohort"", +#' oracleTempSchema = NULL, +#' outputFolder = ""c:/temp/study_results"", +#' maxCores = 4) +#' } +#' +#' @export +execute <- function(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema = cdmDatabaseSchema, + cohortTable = ""cohort"", + oracleTempSchema = cohortDatabaseSchema, + outputFolder, + databaseId = ""Unknown"", + databaseName = ""Unknown"", + databaseDescription = ""Unknown"", + createCohorts = TRUE, + synthesizePositiveControls = TRUE, + runAnalyses = TRUE, + runDiagnostics = TRUE, + packageResults = TRUE, + maxCores = 4, + minCellCount= 5) { + if (!file.exists(outputFolder)) + dir.create(outputFolder, recursive = TRUE) + if (!is.null(getOption(""fftempdir"")) && !file.exists(getOption(""fftempdir""))) { + warning(""fftempdir '"", getOption(""fftempdir""), ""' not found. Attempting to create folder"") + dir.create(getOption(""fftempdir""), recursive = TRUE) + } + + ParallelLogger::addDefaultFileLogger(file.path(outputFolder, ""log.txt"")) + + if (createCohorts) { + ParallelLogger::logInfo(""Creating exposure and outcome cohorts"") + createCohorts(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder) + } + + # Set doPositiveControlSynthesis to FALSE if you don't want to use synthetic positive controls: + doPositiveControlSynthesis = TRUE + if (doPositiveControlSynthesis) { + if (synthesizePositiveControls) { + ParallelLogger::logInfo(""Synthesizing positive controls"") + timeAtRisks <- c(""60d"", ""1yr"", ""5yr"", ""91d1yr"", ""91d5yr"") + for (timeAtRisk in timeAtRisks) { + synthesizePositiveControls(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder, + maxCores = maxCores, + timeAtRiskLabel = timeAtRisk) + } + } + } + + if (runAnalyses) { + ParallelLogger::logInfo(""Running CohortMethod analyses"") + timeAtRisks <- c(""60d"", ""1yr"", ""5yr"", ""91d1yr"", ""91d5yr"") + for (timeAtRisk in timeAtRisks) { + runCohortMethod(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder, + maxCores = maxCores, + timeAtRiskLabel = timeAtRisk) + } + } + + if (runDiagnostics) { + ParallelLogger::logInfo(""Running diagnostics"") + timeAtRisks <- c(""60d"", ""1yr"", ""5yr"", ""91d1yr"", ""91d5yr"") + for (timeAtRisk in timeAtRisks) { + generateDiagnostics(outputFolder = outputFolder, + maxCores = maxCores, + timeAtRiskLabel = timeAtRisk) + } + } + + if (packageResults) { + ParallelLogger::logInfo(""Packaging results"") + timeAtRisks <- c(""60d"", ""1yr"", ""5yr"", ""91d1yr"", ""91d5yr"") + for (timeAtRisk in timeAtRisks) { + exportResults(outputFolder = outputFolder, + databaseId = databaseId, + databaseName = databaseName, + databaseDescription = databaseDescription, + minCellCount = minCellCount, + maxCores = maxCores, + timeAtRiskLabel = timeAtRisk) + } + ParallelLogger::logInfo(""Combining TAR-specific results"") + dummyFolder <- file.path(outputFolder, paste0(""export"", timeAtRisks[1])) + resultNames <- list.files(dummyFolder, pattern = "".*\\.csv$"") + fullExportFolder <- file.path(outputFolder, ""exportFull"") + if (!file.exists(fullExportFolder)) { + dir.create(fullExportFolder, recursive = TRUE) + } + for (resultName in resultNames) { + resultFileNames <- NULL + for (timeAtRisk in timeAtRisks) { + resultsFolder <- file.path(outputFolder, paste0(""export"", timeAtRisk)) + resultFileName <- file.path(resultsFolder, resultName) + resultFileNames <- c(resultFileNames, resultFileName) + } + resultsList <- lapply(resultFileNames, read.csv) + results <- do.call(""rbind"", resultsList) + results <- results[!duplicated(results), ] + write.csv(results, file.path(fullExportFolder, resultName), row.names = FALSE) + } + ParallelLogger::logInfo(""Adding results to zip file"") + zipName <- file.path(fullExportFolder, paste0(""Results"", databaseId, "".zip"")) + files <- list.files(fullExportFolder, pattern = "".*\\.csv$"") + oldWd <- setwd(fullExportFolder) + on.exit(setwd(oldWd)) + DatabaseConnector::createZipFile(zipFile = zipName, files = files) + ParallelLogger::logInfo(""Results are ready for sharing at:"", zipName) + } + + invisible(NULL) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","UkaTkaSafetyEffectiveness/R/CreatePlotsAndTables.R",".R","47589","890","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of UkaTkaSafetyFull +# +# 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. + +#' @export +createPlotsAndTables <- function(studyFolder, + createTable1, + createHrTable, + createForestPlot, + createKmPlot, + createDiagnosticsPlot) { + + source(""inst/shiny/EvidenceExplorer/DataPulls.R"") + source(""inst/shiny/EvidenceExplorer/PlotsAndTables.R"") + dataFolder <- file.path(studyFolder, ""shinyDataAll"") + reportFolder <- file.path(studyFolder, ""report"") + if (!file.exists(reportFolder)) { + dir.create(reportFolder) + } + splittableTables <- c(""covariate_balance"", ""preference_score_dist"", ""kaplan_meier_dist"") + connection <- NULL + files <- list.files(dataFolder, pattern = "".rds"") + + # Load data from data folder: + loadFile <- function(file) { + # file = files[3] + tableName <- gsub(""(_t[0-9]+_c[0-9]+)*\\.rds"", """", file) + # tableName <- gsub(""(_t[0-9]+_c[0-9]+)|(_)[^_]*\\.rds"", """", file) + camelCaseName <- SqlRender::snakeCaseToCamelCase(tableName) + if (!(tableName %in% splittableTables)) { + newData <- readRDS(file.path(dataFolder, file)) + colnames(newData) <- SqlRender::snakeCaseToCamelCase(colnames(newData)) + if (exists(camelCaseName, envir = .GlobalEnv)) { + existingData <- get(camelCaseName, envir = .GlobalEnv) + newData <- rbind(existingData, newData) + } + assign(camelCaseName, newData, envir = .GlobalEnv) + } + invisible(NULL) + } + lapply(files, loadFile) + + relabel <- function(var, oldLabel, newLabel) { + levels(var)[levels(var) == oldLabel] <- newLabel + return(var) + } + + # exposures rename + exposureOfInterest$exposureName <- relabel(exposureOfInterest$exposureName, ""[OD4] Patients with unicompartmental knee replacement without limitation on hip-spine-foot pathology"", ""Unicompartmental knee replacement without hip-spine-foot pathology restriction"") + exposureOfInterest$exposureName <- relabel(exposureOfInterest$exposureName, ""[OD4] Patients with unicompartmental knee replacement"", ""Unicompartmental knee replacement"") + exposureOfInterest$exposureName <- relabel(exposureOfInterest$exposureName, ""[OD4] Patients with total knee replacement without limitation on hip-spine-foot pathology"", ""Total knee replacement without hip-spine-foot pathology restriction"") + exposureOfInterest$exposureName <- relabel(exposureOfInterest$exposureName, ""[OD4] Patients with total knee replacement"", ""Total knee replacement"") + exposureOfInterest$order <- match(exposureOfInterest$exposureName, c(""Unicompartmental knee replacement"", + ""Total knee replacement"", + ""Unicompartmental knee replacement without hip-spine-foot pathology restriction"", + ""Total knee replacement without hip-spine-foot pathology restriction"")) + exposureOfInterest <- exposureOfInterest[order(exposureOfInterest$order), ] + + # outcomes rename + outcomeOfInterest$outcomeName <- relabel(outcomeOfInterest$outcomeName, ""[OD4] Post operative infection events"",""Post-operative infection"") + outcomeOfInterest$outcomeName <- relabel(outcomeOfInterest$outcomeName, ""[OD4] Venous thromboembolism events"", ""Venous thromboembolism"") + outcomeOfInterest$outcomeName <- relabel(outcomeOfInterest$outcomeName, ""[OD4] Mortality"", ""Mortality"") + outcomeOfInterest$outcomeName <- relabel(outcomeOfInterest$outcomeName, ""[OD4] Readmission after knee arthroplasty"", ""Readmission"") + outcomeOfInterest$outcomeName <- relabel(outcomeOfInterest$outcomeName, ""[OD4] Persons with knee arthroplasty revision"", ""Revision"") + outcomeOfInterest$outcomeName <- relabel(outcomeOfInterest$outcomeName, ""[OD4] Opioid use after arthroplasty"", ""Opioid use"") + outcomeOfInterest$order <- match(outcomeOfInterest$outcomeName, c(""Venous thromboembolism"", + ""Post-operative infection"", + ""Readmission"", + ""Mortality"", + ""Opioid use"", + ""Revision"")) + outcomeOfInterest <- outcomeOfInterest[order(outcomeOfInterest$order), ] + + # analyses rename + cohortMethodAnalysis$description <- relabel(cohortMethodAnalysis$description, ""1. PS matching variable ratio No trim TAR 60d"", ""10:1 variable ratio matching, 60 day time-at-risk"") + cohortMethodAnalysis$description <- relabel(cohortMethodAnalysis$description, ""2. PS matching variable ratio No trim TAR 1yr"", ""10:1 variable ratio matching, 1 year time-at-risk"") + cohortMethodAnalysis$description <- relabel(cohortMethodAnalysis$description, ""3. PS matching variable ratio No trim TAR 5yr"", ""10:1 variable ratio matching, 5 year time-at-risk"") + cohortMethodAnalysis$description <- relabel(cohortMethodAnalysis$description, ""4. PS matching variable ratio Trim 5% TAR 60d"", ""10:1 variable ratio matching 5% trim, 60 day time-at-risk"") + cohortMethodAnalysis$description <- relabel(cohortMethodAnalysis$description, ""5. PS matching 1-1 ratio No trim TAR 60d"", ""1:1 ratio matching, 60 day time-at-risk"") + cohortMethodAnalysis$description <- relabel(cohortMethodAnalysis$description, ""6. PS matching variable ratio Trim 5% TAR 5yr"", ""10:1 variable ratio matching 5% trim, 5 year time-at-risk"") + cohortMethodAnalysis$description <- relabel(cohortMethodAnalysis$description, ""7. PS matching 1-1 ratio No trim TAR 5yr"", ""1:1 ratio matching, 5 year time-at-risk"") + cohortMethodAnalysis$description <- relabel(cohortMethodAnalysis$description, ""8. PS matching variable ratio No trim TAR 91d-1yr"", ""10:1 variable ratio matching, 91 days to 1 year time-at-risk"") + cohortMethodAnalysis$description <- relabel(cohortMethodAnalysis$description, ""9. PS matching variable ratio No trim TAR 91d-5yr"", ""10:1 variable ratio matching, 91 days to 5 years time-at-risk"") + cohortMethodAnalysis$description <- relabel(cohortMethodAnalysis$description, ""10. PS matching variable ratio Trim 5% TAR 91d-1yr"", ""10:1 variable ratio matching 5% trim, 91 days to 1 year time-at-risk"") + cohortMethodAnalysis$description <- relabel(cohortMethodAnalysis$description, ""11. PS matching 1-1 ratio No trim TAR 91d-1yr"" , ""1:1 ratio matching, 91 days to 1 year time-at-risk"") + + dropRows <- (cohortMethodResult$databaseId %in% c(""CCAE"", ""MDCR"", ""pmtx"") & cohortMethodResult$outcomeId == 8210) | # drop mortality from CCAE, MDCR, PharMetrics + (cohortMethodResult$databaseId %in% c(""thin"", ""pmtx"") & cohortMethodResult$outcomeId == 8211) | # drop readmission from THIN and PharMetrics + (cohortMethodResult$outcomeId %in% c(8208, 8209, 8210, 8211) & cohortMethodResult$analysisId %in% c(6:11)) | + (cohortMethodResult$outcomeId == 8212 & cohortMethodResult$analysisId %in% c(1, 4, 5, 8:11)) | # drop complications analyses (5yr trim, 5yr 1:1, 91d-1yr TARs, 91d-5yr TARs) + (cohortMethodResult$outcomeId == 8233 & cohortMethodResult$analysisId %in% c(1:7)) # drop opioids analyses (60d TAR, 1yr TAR, 5yr TAR) + cohortMethodResult <- cohortMethodResult[!dropRows, ] + + badCalibration <- (cohortMethodResult$databaseId %in% c(""thin"") & cohortMethodResult$outcomeId %in% c(8208, 8209, 8210, 8211) & cohortMethodResult$analysisId %in% c(1,4,5)) # thin 60d complications for removing calibrated results + cohortMethodResult[badCalibration, c(""calibratedP"", ""calibratedRr"", ""calibratedCi95Lb"", ""calibratedCi95Ub"", ""calibratedLogRr"",""calibratedSeLogRr"")] <- NA + + if (createTable1) { + covariateOrder <- c( + """", + ""Characteristic"", + ""Age group"", + "" 40-44"", + "" 45-49"", + "" 50-54"", + "" 55-59"", + "" 60-64"", + "" 65-69"", + "" 70-74"", + "" 75-79"", + "" 80-84"", + "" 85-89"", + "" 90-94"", + ""Gender: female"", + ""Medical history: General"", + "" Acute respiratory disease"", + "" Attention deficit hyperactivity disorder"", + "" Chronic liver disease"", + "" Chronic obstructive lung disease"", + "" Crohn's disease"", + "" Dementia"", + "" Depressive disorder"", + "" Diabetes mellitus"", + "" Gastroesophageal reflux disease"", + "" Gastrointestinal hemorrhage"", + "" Human immunodeficiency virus infection"", + "" Hyperlipidemia"", + "" Hypertensive disorder"", + "" Lesion of liver"", + "" Obesity"", + "" Osteoarthritis"", + "" Pneumonia"", + "" Psoriasis"", + "" Renal impairment"", + "" Schizophrenia"", + "" Ulcerative colitis"", + "" Urinary tract infectious disease"", + "" Viral hepatitis C"", + "" Visual system disorder"", + ""Medical history: Cardiovascular disease"", + "" Atrial fibrillation"", + "" Cerebrovascular disease"", + "" Coronary arteriosclerosis"", + "" Heart disease"", + "" Heart failure"", + "" Ischemic heart disease"", + "" Peripheral vascular disease"", + "" Pulmonary embolism"", + "" Venous thrombosis"", + ""Medical history: Neoplasms"", + "" Hematologic neoplasm"", + "" Malignant lymphoma"", + "" Malignant neoplasm of anorectum"", + "" Malignant neoplastic disease"", + "" Malignant tumor of breast"", + "" Malignant tumor of colon"", + "" Malignant tumor of lung"", + "" Malignant tumor of urinary bladder"", + "" Primary malignant neoplasm of prostate"", + ""Medication use"", + "" Agents acting on the renin-angiotensin system"", + "" Antibacterials for systemic use"", + "" Antidepressants"", + "" Antiepileptics"", + "" Antiinflammatory and antirheumatic products"", + "" Antineoplastic agents"", + "" Antipsoriatics"", + "" Antithrombotic agents"", + "" Beta blocking agents"", + "" Calcium channel blockers"", + "" Diuretics"", + "" Drugs for acid related disorders"", + "" Drugs for obstructive airway diseases"", + "" Drugs used in diabetes"", + "" Immunosuppressants"", + "" Lipid modifying agents"", + "" Opioids"", + "" Psycholeptics"", + "" Psychostimulants, agents used for adhd and nootropics"") + + paperCovariateOrder <- c( + """", + ""Characteristic"", + ""Age group"", + "" 40-44"", + "" 45-49"", + "" 50-54"", + "" 55-59"", + "" 60-64"", + "" 65-69"", + "" 70-74"", + "" 75-79"", + "" 80-84"", + "" 85-89"", + "" 90-94"", + ""Gender: female"", + ""Medical history: General"", + "" Atrial fibrillation"", + "" Chronic obstructive lung disease"", + "" Depressive disorder"", + "" Diabetes mellitus"", + "" Hyperlipidemia"", + "" Hypertensive disorder"", + "" Obesity"", + "" Osteoarthritis"", + "" Renal impairment"", + "" Peripheral vascular disease"", + "" Pulmonary embolism"", + "" Venous thrombosis"", + ""Medication use"", + "" Antibacterials for systemic use"", + "" Antidepressants"", + "" Antiinflammatory and antirheumatic products"", + "" Antithrombotic agents"", + "" Opioids"") + + tcoas <- unique(cohortMethodResult[c(""analysisId"", ""targetId"", ""comparatorId"", ""outcomeId"")]) + tcoas <- tcoas[tcoas$outcomeId %in% outcomeOfInterest$outcomeId, ] + tcoas <- tcoas[order(tcoas$targetId, tcoas$analysisId, tcoas$outcomeId), ] + tcoas <- aggregate(outcomeId ~ analysisId + targetId + comparatorId, tcoas, head, 1) + + for (i in 1) { # 1:nrow(tcoas)) { # i=1 + targetId <- tcoas$targetId[i] + comparatorId <- tcoas$comparatorId[i] + analysisId <- tcoas$analysisId[i] + outcomeId <- tcoas$outcomeId[i] + matching <- c(""before_matching"", ""after_matching"", ""before_and_after_matching"") + for (j in 1:length(matching)) { # j=1 + table1List <- list() + for (databaseId in database$databaseId) { # databaseId=""CCAE"" + balance <- getCovariateBalance2(connection = connection, + dataFolder = dataFolder, + targetId = targetId, + comparatorId = comparatorId, + databaseId = databaseId, + analysisId = analysisId, + outcomeId = outcomeId) + table1 <- prepareTable1(balance = balance, + beforeLabel = ""Before matching"", + afterLabel = ""After matching"", + targetLabel = ""UKR"", + comparatorLabel = ""TKR"", + percentDigits = 1, + stdDiffDigits = 2, + output = ""latex"", + pathToCsv = file.path(""inst"", ""shiny"", ""EvidenceExplorer"", ""Table1Specs.csv"")) + colnames(table1) <- c(""covariate"", + paste0(""bmUkr"", databaseId), paste0(""bmTkr"", databaseId), paste0(""bmSdm"", databaseId), + paste0(""amUkr"", databaseId), paste0(""amTkr"", databaseId), paste0(""amSdm"", databaseId)) + if (matching[j] == matching[1]) { + table1 <- table1[, c(""covariate"", paste0(""bmUkr"", databaseId), paste0(""bmTkr"", databaseId), paste0(""bmSdm"", databaseId))] + } + if (matching[j] == matching[2]) { + table1 <- table1[, c(""covariate"", paste0(""amUkr"", databaseId), paste0(""amTkr"", databaseId), paste0(""amSdm"", databaseId))] + } + if (matching[j] == matching[3]) { + table1 <- table1 + } + table1List[[length(table1List) + 1]] <- table1 + } + table1 <- merge(table1List[[1]], table1List[[2]], by = ""covariate"", all = TRUE) + table1 <- merge(table1, table1List[[3]], by = ""covariate"", all = TRUE) + table1 <- merge(table1, table1List[[4]], by = ""covariate"", all = TRUE) + table1 <- merge(table1, table1List[[5]], by = ""covariate"", all = TRUE) + + table1Full <- table1[match(covariateOrder, table1$covariate), ] + table1FullFileName <- file.path(reportFolder, paste0(""table1_"", matching[j],""_full_t"", targetId, ""_c"", comparatorId, "".csv"")) + write.csv(table1Full, table1FullFileName, row.names = FALSE, na = """") + + table1Reduced <- table1[match(paperCovariateOrder, table1$covariate), ] + table1ReducedFileName <- file.path(reportFolder, paste0(""table1_"", matching[j], ""_reduced_t"", targetId, ""_c"", comparatorId, "".csv"")) + write.csv(table1Reduced, table1ReducedFileName, row.names = FALSE, na = """") + } + } + } + + if (createHrTable) { + tcoads <- unique(cohortMethodResult[c(""analysisId"", ""targetId"", ""comparatorId"", ""outcomeId"", ""databaseId"")]) + tcoads <- tcoads[tcoads$outcomeId %in% unique(outcomeOfInterest$outcomeId), ] + tcoads <- tcoads[order(tcoads$targetId, tcoads$outcomeId, tcoads$databaseId, tcoads$analysisId), ] + hrTable <- data.frame() + for (i in 1:nrow(tcoads)) { # i=56 + outcomeId <- tcoads$outcomeId[i] + databaseId <- tcoads$databaseId[i] + targetId <- tcoads$targetId[i] + comparatorId <- tcoads$comparatorId[i] + analysisId <- tcoads$analysisId[i] + mainResults <- getMainResults(connection = connection, + targetIds = targetId, + comparatorIds = comparatorId, + outcomeIds = outcomeId, + databaseIds = databaseId, + analysisIds = analysisId) + hrs <- prepareMainResultsTable(mainResults = mainResults, analyses = cohortMethodAnalysis) + irs <- preparePowerTable(mainResults = mainResults, analyses = cohortMethodAnalysis) + targetIr <- sprintf(""%s (%s)"", irs$targetOutcomes, irs$targetIr) + comparatorIr <- sprintf(""%s (%s)"", irs$comparatorOutcomes, irs$comparatorIr) + hrs$`UKR IR` <- targetIr + hrs$`TKR IR` <- comparatorIr + hrs$outcomeId <- outcomeId + hrs$databaseId <- databaseId + hrs$targetId <- targetId + hrs$comparatorId <- comparatorId + hrs$analysisId <- analysisId + hrs <- merge(outcomeOfInterest[, c(""outcomeId"", ""outcomeName"")], hrs) + hrs <- hrs[, c(""analysisId"", + ""targetId"", + ""comparatorId"", + ""outcomeId"", + ""outcomeName"", + ""databaseId"", + ""Analysis"", + ""UKR IR"", + ""TKR IR"", + ""HR (95% CI)"", + ""P"", + ""Cal. HR (95% CI)"", + ""Cal. p"")] + hrTable <- rbind(hrTable, hrs) + } + hrTable$Analysis <- as.character(hrTable$Analysis) + hrTable$Analysis[hrTable$targetId == 8260] <- paste(hrTable$Analysis[hrTable$targetId == 8260], ""without prior spine-hip-foot pathology restriction"", sep = ""; "") + primary <- (hrTable$targetId == 8257 & hrTable$outcomeId %in% c(8208, 8209, 8210, 8211) & hrTable$analysisId == 1) | + (hrTable$targetId == 8257 & hrTable$outcomeId %in% c(8212) & hrTable$analysisId == 3) | + (hrTable$targetId == 8257 & hrTable$outcomeId %in% c(8233) & hrTable$analysisId == 8) + hrTable$AnalysisName[primary] <- ""Primary"" + hrTable$AnalysisName[!primary] <- ""Sensitivity"" + hrTable <- hrTable[, c(""analysisId"", + ""targetId"", + ""comparatorId"", + ""outcomeId"", + ""outcomeName"", + ""databaseId"", + ""AnalysisName"", + ""Analysis"", + ""UKR IR"", + ""TKR IR"", + ""HR (95% CI)"", + ""P"", + ""Cal. HR (95% CI)"", + ""Cal. p"")] + hrTable$outcomeIdOrder <- match(hrTable$outcomeId, c(8209, 8208, 8211, 8210, 8233, 8212)) + hrTable <- hrTable[order(hrTable$outcomeIdOrder, hrTable$databaseId, hrTable$targetId, hrTable$AnalysisName, hrTable$analysisId), ] + + hrsTableAllFileName <- file.path(reportFolder, ""hrs_table_primary_and_sensitivity.csv"") + write.csv(hrTable[, -c(1:4, 15)], hrsTableAllFileName, row.names = FALSE) + + hrsTablePrimaryFileName <- file.path(reportFolder, ""hrs_table_primary.csv"") + write.csv(hrTable[hrTable$AnalysisName == ""Primary"", -c(1:4, 15)], hrsTablePrimaryFileName, row.names = FALSE) + } + + if (createForestPlot) { + primary <- (cohortMethodResult$targetId == 8257 & cohortMethodResult$outcomeId %in% c(8208, 8209, 8210, 8211) & cohortMethodResult$analysisId == 1) | + (cohortMethodResult$targetId == 8257 & cohortMethodResult$outcomeId %in% c(8212) & cohortMethodResult$analysisId == 3) | + (cohortMethodResult$targetId == 8257 & cohortMethodResult$outcomeId %in% c(8233) & cohortMethodResult$analysisId == 8) + plotData <- cohortMethodResult[primary, ] + plotData <- merge(plotData, outcomeOfInterest[, c(""outcomeId"", ""outcomeName"")]) + levels(plotData$outcomeName)[levels(plotData$outcomeName) == ""Venous thromboembolism""] <- ""VTE"" + levels(plotData$outcomeName)[levels(plotData$outcomeName) == ""Post-operative infection""] <- ""Infection"" + plotData$TAR[plotData$analysisId == 1] <- ""60 days"" + plotData$TAR[plotData$analysisId == 3] <- ""5 years"" + plotData$TAR[plotData$analysisId == 8] <- ""91 days - 1 year"" + ccae <- generateForestPlot(plotData = plotData, databaseId = ""CCAE"", dropMortality = TRUE) + optum <- generateForestPlot(plotData = plotData, databaseId = ""Optum"") + mdcr <- generateForestPlot(plotData = plotData, databaseId = ""MDCR"", dropMortality = TRUE) + thin <- generateForestPlot(plotData = plotData, databaseId = ""thin"", dropMortality = TRUE, dropReadmission = TRUE, dropInfection = TRUE, dropVTE = TRUE) + pmtx <- generateForestPlot(plotData = plotData, databaseId = ""pmtx"", dropMortality = TRUE, dropReadmission = TRUE, favorsLabel = TRUE, addLegend = TRUE) + row1 <- grid::textGrob(""CCAE"", rot = 90, gp = grid::gpar(fontsize = 18)) + row2 <- grid::textGrob(""Optum"", rot = 90, gp = grid::gpar(fontsize = 18)) + row3 <- grid::textGrob(""MDCR"", rot = 90, gp = grid::gpar(fontsize = 18)) + row4 <- grid::textGrob(""THIN"", rot = 90, gp = grid::gpar(fontsize = 18)) + row5 <- grid::textGrob(""PharMetrics"", rot = 90, gp = grid::gpar(fontsize = 18)) + plot <- gridExtra::grid.arrange(row1, ccae, + row2, optum, + row3, mdcr, + row4, thin, + row5, pmtx, + nrow = 5, + heights = grid::unit(c(5, 6, 5, 3, 6), rep(""cm"", 5)), + widths = grid::unit(c(2, 11), rep(""cm"", 2))) + plotFile <- file.path(reportFolder, ""hr_calibrated_forest_plot_primary.png"") + ggplot2::ggsave(filename = plotFile, plot = plot, height = 26, width = 16, units = ""cm"") + } + + if (createKmPlot) { + refKm <- data.frame(outcomeId = c(8233, 8212), + analysisId = c(8, 3), + yLim = c(0.5, 0.9), + useYLabel = c(TRUE, FALSE), + timeOffset = c(TRUE, FALSE)) + refKm <- merge(refKm, database) + refKm$order <- match(refKm$databaseId, c(""CCAE"", + ""Optum"", + ""MDCR"", + ""thin"", + ""pmtx"")) + refKm <- refKm[order(refKm$order), ] + refKm$legendLabel <- c(rep(TRUE, 2), rep(FALSE, 8)) + kmPlotList <- list() + for (i in 1:nrow(refKm)) { # i=1 + outcomeId <- refKm$outcomeId[i] + databaseId <- refKm$databaseId[i] + analysisId <- refKm$analysisId[i] + yLim <- refKm$yLim[i] + legendLabel <- refKm$legendLabel[i] + useYLabel <- refKm$useYLabel[i] + timeOffset <- refKm$useYLabel[i] + kmData <- getKaplanMeier2(connection = connection, + dataFolder = dataFolder, + targetId = 8257, + comparatorId = 8256, + outcomeId = outcomeId, + databaseId = databaseId, + analysisId = analysisId) + kmPlotList[[length(kmPlotList) + 1]] <- plotKaplanMeier2(kaplanMeier = kmData, + targetName = ""UKR"", + comparatorName = ""TKR"", + legendLabel = legendLabel, + yLimLower = yLim, + useYLabel = useYLabel, + timeOffset = timeOffset) + } + col0 <- grid::textGrob("""") + col1 <- grid::textGrob(""Opioid use"", gp = grid::gpar(fontsize = 25)) + col2 <- grid::textGrob(""Revision"", gp = grid::gpar(fontsize = 25)) + row1 <- grid::textGrob(""CCAE"", rot = 90, gp = grid::gpar(fontsize = 35)) + row2 <- grid::textGrob(""Optum"", rot = 90, gp = grid::gpar(fontsize = 35)) + row3 <- grid::textGrob(""MDCR"", rot = 90, gp = grid::gpar(fontsize = 35)) + row4 <- grid::textGrob(""THIN"", rot = 90, gp = grid::gpar(fontsize = 35)) + row5 <- grid::textGrob(""PharMetrics"", rot = 90, gp = grid::gpar(fontsize = 35)) + plot <- gridExtra::grid.arrange(col0, col1, col2, + row1, kmPlotList[[1]], kmPlotList[[2]], + row2, kmPlotList[[3]], kmPlotList[[4]], + row3, kmPlotList[[5]], kmPlotList[[6]], + row4, kmPlotList[[7]], kmPlotList[[8]], + row5, kmPlotList[[9]], kmPlotList[[10]], + nrow = 6, + heights = grid::unit(c(2, 14, 11, 11, 11, 11), rep(""cm"", 6)), + widths = grid::unit(c(2, 18, 18), rep(""cm"", 2))) + plotFile <- file.path(reportFolder, ""km_plots_long_term_primary.png"") + ggplot2::ggsave(filename = plotFile, plot = plot, height = 60, width = 38, units = ""cm"") + } + + if (createDiagnosticsPlot) { + tcoads <- unique(cohortMethodResult[c(""analysisId"", ""targetId"", ""comparatorId"", ""outcomeId"", ""databaseId"")]) + refPsBal <- tcoads[tcoads$analysisId == 2 & tcoads$targetId == 8257 & tcoads$comparatorId == 8256 & tcoads$outcomeId == 8208, ] + refPsBal$order <- match(refPsBal$databaseId, c(""CCAE"", + ""Optum"", + ""MDCR"", + ""thin"", + ""pmtx"")) + refPsBal <- refPsBal[order(refPsBal$order), ] + psPlotList <- list() + balancePlotList <- list() + for (i in 1:nrow(refPsBal)) { # i=1 + databaseId <- refPsBal$databaseId[i] + analysisId <- refPsBal$analysisId[i] + targetId <- refPsBal$targetId[i] + comparatorId <- refPsBal$comparatorId[i] + outcomeId <- refPsBal$outcomeId[i] + ps <- getPs2(connection = connection, + dataFolder = dataFolder, + targetIds = 8257, + comparatorIds = 8256, + databaseId = databaseId) + psPlotList[[length(psPlotList) + 1]] <- plotPs2(ps = ps, + targetName = ""UKR"", + comparatorName = ""TKR"") + balance <- getCovariateBalance2(connection = connection, + dataFolder = dataFolder, + targetId = targetId, + comparatorId = comparatorId, + databaseId = databaseId, + analysisId = analysisId, + outcomeId = outcomeId) + balancePlotList[[length(balancePlotList) + 1]] <- plotCovariateBalanceScatterPlot2(balance = balance, + beforeLabel = ""Before matching"", + afterLabel = ""After matching"") + } + nullPlotList <- list() + refNull <- data.frame(analysisId = c(1, 8, 3), + targetId = rep(8257, 3), + comparatorId = rep(8256, 3)) + refNull <- merge(refNull, database) + refNull$order <- match(refNull$databaseId, c(""CCAE"", + ""Optum"", + ""MDCR"", + ""thin"", + ""pmtx"")) + refNull <- refNull[order(refNull$order), ] + for (i in 1:nrow(refNull)) { # i=1 + targetId <- refNull$targetId[i] + comparatorId <- refNull$comparatorId[i] + analysisId <- refNull$analysisId[i] + databaseId <- refNull$databaseId[i] + controlResults <- getControlResults(connection = connection, + targetId = targetId, + comparatorId = comparatorId, + analysisId = analysisId, + databaseId = databaseId) + negativeControlResults <- controlResults[controlResults$effectSize == 1,] + nullPlotList[[length(nullPlotList) + 1]] <- plotLargeScatter2(d = negativeControlResults, xLabel = ""Hazard ratio"") + } + col0 <- grid::textGrob("""") + col1 <- grid::textGrob(""Preference score distribution"", gp = grid::gpar(fontsize = 40)) + col2 <- grid::textGrob(""Covariate balance"", gp = grid::gpar(fontsize = 40)) + col3 <- grid::textGrob(""Empirical null, 60 days"", gp = grid::gpar(fontsize = 40)) + col4 <- grid::textGrob(""Empirical null, 1 year"", gp = grid::gpar(fontsize = 40)) + col5 <- grid::textGrob(""Empirical null, 5 years"", gp = grid::gpar(fontsize = 40)) + row1 <- grid::textGrob(""CCAE"", rot = 90, gp = grid::gpar(fontsize = 40)) + row2 <- grid::textGrob(""Optum"", rot = 90, gp = grid::gpar(fontsize = 40)) + row3 <- grid::textGrob(""MDCR"", rot = 90, gp = grid::gpar(fontsize = 40)) + row4 <- grid::textGrob(""THIN"", rot = 90, gp = grid::gpar(fontsize = 40)) + row5 <- grid::textGrob(""PharMetrics"", rot = 90, gp = grid::gpar(fontsize = 40)) + plot <- gridExtra::grid.arrange(col0, col1, col2, col3, col4, col5, + row1, psPlotList[[1]], balancePlotList[[1]], nullPlotList[[1]], nullPlotList[[2]], nullPlotList[[3]], + row2, psPlotList[[2]], balancePlotList[[2]], nullPlotList[[4]], nullPlotList[[5]], nullPlotList[[6]], + row3, psPlotList[[3]], balancePlotList[[3]], nullPlotList[[7]], nullPlotList[[8]], nullPlotList[[9]], + row4, psPlotList[[4]], balancePlotList[[4]], nullPlotList[[10]], nullPlotList[[11]], nullPlotList[[12]], + row5, psPlotList[[5]], balancePlotList[[5]], nullPlotList[[13]], nullPlotList[[14]], nullPlotList[[15]], + nrow = 6, + heights = c(50, rep(500, 5)), + widths = c(50, rep(500, 5))) + plotFile <- file.path(reportFolder, ""diagnostics_primary.png"") + ggplot2::ggsave(filename = plotFile, plot = plot, height = 35, width = 45) + } +} + +generateForestPlot <- function(plotData, + databaseId, + favorsLabel = FALSE, + dropMortality = FALSE, + dropReadmission = FALSE, + dropInfection = FALSE, + dropVTE = FALSE, + addLegend = FALSE) { + results <- plotData[plotData$databaseId == databaseId, ] + data <- data.frame(outcome = results$outcomeName, + logRr = results$calibratedLogRr, + logLb = results$calibratedLogRr + qnorm(0.025) * results$calibratedSeLogRr, + logUb = results$calibratedLogRr + qnorm(0.975) * results$calibratedSeLogRr, + database = results$databaseId, + TAR = as.factor(results$TAR)) + + data$order <- match(data$TAR, c(""60 days"", ""91 days - 1 year"", ""5 years"")) + data <- data[order(data$order), ] + + breaks <- c(0.25, 0.5, 1, 2, 4) + if (favorsLabel) { + labels <- c(0.25, paste(""0.5\nFavours"", ""UKR""), 1, paste(""2\nFavours"", ""TKR""), 4) + } else { + labels <- c(0.25, 0.5, 1, 2, 4) + } + limits <- c(""Revision"", + ""Opioid use"", + ""Mortality"", + ""Readmission"", + ""Infection"", + ""VTE"") + if (dropMortality) { + limits <- limits[! limits %in% ""Mortality""] + } + if (dropReadmission) { + limits <- limits[! limits %in% ""Readmission""] + } + if (dropInfection) { + limits <- limits[! limits %in% ""Infection""] + } + if (dropVTE) { + limits <- limits[! limits %in% ""VTE""] + } + if (addLegend) { + legendPosition <- ""bottom"" + } else { + legendPosition <- ""none"" + } + plot <- ggplot2::ggplot(data, + ggplot2::aes(x = exp(logRr), + y = outcome, + xmin = exp(logLb), + xmax = exp(logUb), + colour = TAR), + environment = environment()) + + ggplot2::geom_vline(xintercept = breaks, colour = ""#AAAAAA"", lty = 1, size = 0.1) + + ggplot2::geom_vline(xintercept = 1, colour = ""#000000"", lty = 1, size = 1) + + ggplot2::geom_errorbarh(height = 0, size = 2, alpha = 0.7) + + ggplot2::geom_point(shape = 16, size = 4.4, alpha = 0.7) + + ggplot2::scale_colour_manual(breaks = data$TAR, + values=c(rgb(0, 0.8, 0), rgb(0, 0, 0.8), rgb(0.8, 0, 0))) + + ggplot2::labs(color = 'Time-at-risk') + + ggplot2::coord_cartesian(xlim = c(0.25, 4)) + + ggplot2::scale_x_continuous(""Hazard ratio"", trans = ""log10"", breaks = breaks, labels = labels) + + ggplot2::scale_y_discrete(limits = limits) + + ggplot2::theme(text = ggplot2::element_text(size = 12), + panel.grid.minor = ggplot2::element_blank(), + panel.background = ggplot2::element_rect(fill = ""#FAFAFA"",colour = NA), + panel.grid.major = ggplot2::element_line(colour = ""#EEEEEE""), + axis.ticks = ggplot2::element_blank(), + axis.title.y = ggplot2::element_blank(), + axis.title.x = ggplot2::element_blank(), + axis.text.y = ggplot2::element_text(size = 12), + axis.text.x = ggplot2::element_text(size = 12), + legend.position = legendPosition) + return(plot) +} + +getKaplanMeier2 <- function(connection, + dataFolder, + targetId, + comparatorId, + outcomeId, + databaseId, + analysisId) { + file <- sprintf(""kaplan_meier_dist_t%s_c%s.rds"", targetId, comparatorId) + km <- readRDS(file.path(dataFolder, file)) + colnames(km) <- SqlRender::snakeCaseToCamelCase(colnames(km)) + km <- km[km$outcomeId == outcomeId & + km$analysisId == analysisId & + km$databaseId == databaseId, ] + return(km) +} + +plotKaplanMeier2 <- function(kaplanMeier, + targetName, + comparatorName, + legendLabel, + yLimLower, + useYLabel, + timeOffset) { + if (timeOffset) { + survTimeOffset <- 91 + xAxisOffset <- 50 + } else { + survTimeOffset <- 0 + xAxisOffset <- 0 + } + data <- rbind(data.frame(time = kaplanMeier$time + survTimeOffset, + s = kaplanMeier$targetSurvival, + lower = kaplanMeier$targetSurvivalLb, + upper = kaplanMeier$targetSurvivalUb, + strata = paste0("" "", targetName, "" "")), + data.frame(time = kaplanMeier$time + survTimeOffset, + s = kaplanMeier$comparatorSurvival, + lower = kaplanMeier$comparatorSurvivalLb, + upper = kaplanMeier$comparatorSurvivalUb, + strata = paste0("" "", comparatorName))) + if (timeOffset) { + xlims <- c(survTimeOffset, max(data$time)) + } else { + xlims <- c(-max(data$time)/40, max(data$time)) + } + xBreaks <- kaplanMeier$time[!is.na(kaplanMeier$targetAtRisk)] + xAxisOffset + xLabel <- ""Days since surgery"" + ylims <- c(yLimLower, 1) + if (useYLabel) { + yLabel <- ""Survival probability"" + } else { + yLabel <- NULL + } + if (legendLabel) { + legendPosition <- ""top"" + } else { + legendPosition <- ""none"" + } + theme1 <- ggplot2::element_text(colour = ""#000000"", size = 20) + theme2 <- ggplot2::element_text(colour = ""#000000"", size = 20) + + plot <- ggplot2::ggplot(data, ggplot2::aes(x = time, + y = s, + color = strata, + fill = strata, + ymin = lower, + ymax = upper)) + + ggplot2::geom_ribbon(color = rgb(0, 0, 0, alpha = 0)) + + ggplot2::geom_step(size = 1) + + ggplot2::scale_color_manual(values = c(rgb(0.8, 0, 0, alpha = 0.8), + rgb(0, 0, 0.8, alpha = 0.8))) + + ggplot2::scale_fill_manual(values = c(rgb(0.8, 0, 0, alpha = 0.3), + rgb(0, 0, 0.8, alpha = 0.3))) + + ggplot2::scale_x_continuous(xLabel, limits = xlims, breaks = xBreaks) + + ggplot2::scale_y_continuous(yLabel, limits = ylims) + + ggplot2::theme(legend.title = ggplot2::element_blank(), + legend.position = legendPosition, + legend.text = ggplot2::element_text(size = 20), + legend.key.size = ggplot2::unit(2, ""lines""), + plot.title = ggplot2::element_text(hjust = 0.5), + text = theme1) + + ggplot2::theme(axis.title.y = ggplot2::element_text(vjust = -10, size = 20)) + + targetAtRisk <- kaplanMeier$targetAtRisk[!is.na(kaplanMeier$targetAtRisk)] + comparatorAtRisk <- kaplanMeier$comparatorAtRisk[!is.na(kaplanMeier$comparatorAtRisk)] + labels <- data.frame(x = c(0, xBreaks, xBreaks), + y = as.factor(c(""Number at risk"", + rep(targetName, length(xBreaks)), + rep(comparatorName, length(xBreaks)))), + label = c("""", + formatC(targetAtRisk, big.mark = "","", mode = ""integer""), + formatC(comparatorAtRisk, big.mark = "","", mode = ""integer""))) + labels$y <- factor(labels$y, levels = c(comparatorName, targetName, ""Number at risk"")) + dataTable <- ggplot2::ggplot(labels, ggplot2::aes(x = x, y = y, label = label)) + + ggplot2::geom_text(size = 4.5, vjust = 0.5) + + ggplot2::scale_x_continuous(xLabel, + limits = xlims, + breaks = xBreaks) + + ggplot2::theme(panel.grid.major = ggplot2::element_blank(), + panel.grid.minor = ggplot2::element_blank(), + legend.position = ""none"", + panel.border = ggplot2::element_blank(), + panel.background = ggplot2::element_blank(), + axis.text.x = ggplot2::element_text(color = ""white""), + axis.title.x = ggplot2::element_text(color = ""white""), + axis.title.y = ggplot2::element_blank(), + axis.ticks = ggplot2::element_line(color = ""white""), + text = theme2) + plots <- list(plot, dataTable) + grobs <- widths <- list() + for (i in 1:length(plots)) { + grobs[[i]] <- ggplot2::ggplotGrob(plots[[i]]) + widths[[i]] <- grobs[[i]]$widths[2:5] + } + maxwidth <- do.call(grid::unit.pmax, widths) + for (i in 1:length(grobs)) { + grobs[[i]]$widths[2:5] <- as.list(maxwidth) + } + plot <- gridExtra::grid.arrange(grobs[[1]], grobs[[2]], heights = c(400, 200)) + return(plot) +} + +getPs2 <- function(connection, + dataFolder, + targetIds, + comparatorIds, + databaseId) { + file <- sprintf(""preference_score_dist_t%s_c%s.rds"", targetIds, comparatorIds) + ps <- readRDS(file.path(dataFolder, file)) + colnames(ps) <- SqlRender::snakeCaseToCamelCase(colnames(ps)) + ps <- ps[ps$databaseId == databaseId, ] + return(ps) +} + +plotPs2 <- function(ps, + targetName, + comparatorName, + legendLabel = TRUE) { + if (legendLabel) { + legendPosition <- ""top"" + } else { + legendPosition <- ""none"" + } + ps <- rbind(data.frame(x = ps$preferenceScore, y = ps$targetDensity, group = targetName), + data.frame(x = ps$preferenceScore, y = ps$comparatorDensity, group = comparatorName)) + ps$group <- factor(ps$group, levels = c(as.character(targetName), as.character(comparatorName))) + theme <- ggplot2::element_text(colour = ""#000000"", size = 25, margin = ggplot2::margin(0, 0.5, 0, 0.1, ""cm"")) + plot <- ggplot2::ggplot(ps, + ggplot2::aes(x = x, y = y, color = group, group = group, fill = group)) + + ggplot2::geom_density(stat = ""identity"") + + ggplot2::scale_fill_manual(values = c(rgb(0.8, 0, 0, alpha = 0.5), + rgb(0, 0, 0.8, alpha = 0.5))) + + ggplot2::scale_color_manual(values = c(rgb(0.8, 0, 0, alpha = 0.5), + rgb(0, 0, 0.8, alpha = 0.5))) + + ggplot2::scale_x_continuous(""Preference score"", limits = c(0, 1)) + + ggplot2::scale_y_continuous(""Density"") + + ggplot2::theme(legend.title = ggplot2::element_blank(), + panel.grid.major = ggplot2::element_blank(), + panel.grid.minor = ggplot2::element_blank(), + legend.position = legendPosition, + legend.text = theme, + axis.text = theme, + axis.title = theme) + return(plot) +} + +getCovariateBalance2 <- function(connection, + dataFolder, + targetId, + comparatorId, + databaseId, + analysisId, + outcomeId = NULL) { + # file <- sprintf(""covariate_balance_t%s_c%s_%s.rds"", targetId, comparatorId, databaseId) + file <- sprintf(""covariate_balance_t%s_c%s.rds"", targetId, comparatorId) + balance <- readRDS(file.path(dataFolder, file)) + colnames(balance) <- SqlRender::snakeCaseToCamelCase(colnames(balance)) + # balance <- balance[balance$analysisId == analysisId & balance$outcomeId == outcomeId, ] + balance <- balance[balance$analysisId == analysisId & balance$outcomeId == outcomeId & balance$databaseId == databaseId, ] + balance <- merge(balance, covariate[covariate$databaseId == databaseId, c(""covariateId"", ""covariateAnalysisId"", ""covariateName"")]) + balance <- balance[ c(""covariateId"", + ""covariateName"", + ""covariateAnalysisId"", + ""targetMeanBefore"", + ""comparatorMeanBefore"", + ""stdDiffBefore"", + ""targetMeanAfter"", + ""comparatorMeanAfter"", + ""stdDiffAfter"")] + colnames(balance) <- c(""covariateId"", + ""covariateName"", + ""analysisId"", + ""beforeMatchingMeanTreated"", + ""beforeMatchingMeanComparator"", + ""beforeMatchingStdDiff"", + ""afterMatchingMeanTreated"", + ""afterMatchingMeanComparator"", + ""afterMatchingStdDiff"") + balance$absBeforeMatchingStdDiff <- abs(balance$beforeMatchingStdDiff) + balance$absAfterMatchingStdDiff <- abs(balance$afterMatchingStdDiff) + return(balance) +} + +plotCovariateBalanceScatterPlot2 <- function(balance, + beforeLabel = ""Before stratification"", + afterLabel = ""After stratification"") { + limits <- c(min(c(balance$absBeforeMatchingStdDiff, balance$absAfterMatchingStdDiff), + na.rm = TRUE), + max(c(balance$absBeforeMatchingStdDiff, balance$absAfterMatchingStdDiff), + na.rm = TRUE)) + theme <- ggplot2::element_text(colour = ""#000000"", size = 25) + plot <- ggplot2::ggplot(balance, ggplot2::aes(x = absBeforeMatchingStdDiff, y = absAfterMatchingStdDiff)) + + ggplot2::geom_point(color = rgb(0, 0, 0.8, alpha = 0.3), shape = 16, size = 4) + + ggplot2::geom_abline(slope = 1, intercept = 0, linetype = ""dashed"", size = 1.5, colour = rgb(0.8, 0, 0)) + + ggplot2::geom_hline(yintercept = 0) + + ggplot2::geom_vline(xintercept = 0) + + ggplot2::scale_x_continuous(beforeLabel, limits = limits) + + ggplot2::scale_y_continuous(afterLabel, limits = limits) + + ggplot2::theme(text = theme) + + return(plot) +} + +plotLargeScatter2 <- function(d, + xLabel) { + d$Significant <- d$ci95Lb > 1 | d$ci95Ub < 1 + + oneRow <- data.frame(nLabel = paste0(formatC(nrow(d), big.mark = "",""), "" estimates""), + meanLabel = paste0(formatC(100 * + mean(!d$Significant, na.rm = TRUE), digits = 1, format = ""f""), ""% of CIs includes 1"")) + + breaks <- c(0.1, 0.25, 0.5, 1, 2, 4, 6, 8, 10) + theme <- ggplot2::element_text(colour = ""#000000"", size = 25) + themeRA <- ggplot2::element_text(colour = ""#000000"", size = 25, hjust = 1) + themeLA <- ggplot2::element_text(colour = ""#000000"", size = 25, hjust = 0) + + alpha <- 1 - min(0.95 * (nrow(d)/50000)^0.1, 0.95) + plot <- ggplot2::ggplot(d, ggplot2::aes(x = logRr, y = seLogRr)) + + ggplot2::geom_vline(xintercept = log(breaks), colour = ""#AAAAAA"", lty = 1, size = 0.5) + + ggplot2::geom_vline(xintercept = 0, + colour = ""black"", + lty = 1, + size = 1.5) + + ggplot2::geom_abline(ggplot2::aes(intercept = 0, slope = 1/qnorm(0.025)), + colour = rgb(0.8, 0, 0), + linetype = ""dashed"", + size = 1.5, + alpha = 0.5) + + ggplot2::geom_abline(ggplot2::aes(intercept = 0, slope = 1/qnorm(0.975)), + colour = rgb(0.8, 0, 0), + linetype = ""dashed"", + size = 1.5, + alpha = 0.5) + + ggplot2::geom_point(size = 4, color = rgb(0, 0, 1, alpha = 0.05), alpha = alpha, shape = 16) + + ggplot2::geom_hline(yintercept = 0) + + ggplot2::scale_x_continuous(xLabel, limits = log(c(0.1, + 10)), breaks = log(breaks), labels = breaks) + + ggplot2::scale_y_continuous(""Standard Error"", limits = c(0, 1)) + + ggplot2::theme(panel.grid.minor = ggplot2::element_blank(), + #panel.background = ggplot2::element_blank(), + panel.grid.major = ggplot2::element_blank(), + axis.ticks = ggplot2::element_blank(), + axis.text.y = themeRA, + axis.text.x = theme, + axis.title = theme, + legend.key = ggplot2::element_blank(), + strip.text.x = theme, + strip.background = ggplot2::element_blank(), + legend.position = ""none"") + return(plot) +} + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","UkaTkaSafetyEffectiveness/R/CreateCohorts.R",".R","3548","69","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of UkaTkaSafetyFull +# +# 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. + +.createCohorts <- function(connection, + cdmDatabaseSchema, + vocabularyDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable, + oracleTempSchema, + outputFolder) { + + # Create study cohort table structure: + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""CreateCohortTable.sql"", + packageName = ""UkaTkaSafetyFull"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + cohort_database_schema = cohortDatabaseSchema, + cohort_table = cohortTable) + DatabaseConnector::executeSql(connection, sql, progressBar = FALSE, reportOverallTime = FALSE) + + + + # Instantiate cohorts: + pathToCsv <- system.file(""settings"", ""CohortsToCreate.csv"", package = ""UkaTkaSafetyFull"") + cohortsToCreate <- read.csv(pathToCsv) + for (i in 1:nrow(cohortsToCreate)) { + writeLines(paste(""Creating cohort:"", cohortsToCreate$name[i])) + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = paste0(cohortsToCreate$name[i], "".sql""), + packageName = ""UkaTkaSafetyFull"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + vocabulary_database_schema = vocabularyDatabaseSchema, + + target_database_schema = cohortDatabaseSchema, + target_cohort_table = cohortTable, + target_cohort_id = cohortsToCreate$cohortId[i]) + DatabaseConnector::executeSql(connection, sql) + } + + # Fetch cohort counts: + sql <- ""SELECT cohort_definition_id, COUNT(*) AS count FROM @cohort_database_schema.@cohort_table GROUP BY cohort_definition_id"" + sql <- SqlRender::renderSql(sql, + cohort_database_schema = cohortDatabaseSchema, + cohort_table = cohortTable)$sql + sql <- SqlRender::translateSql(sql, targetDialect = attr(connection, ""dbms""))$sql + counts <- DatabaseConnector::querySql(connection, sql) + names(counts) <- SqlRender::snakeCaseToCamelCase(names(counts)) + counts <- merge(counts, data.frame(cohortDefinitionId = cohortsToCreate$cohortId, + cohortName = cohortsToCreate$name)) + write.csv(counts, file.path(outputFolder, ""CohortCounts.csv"")) + + +} + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","UkaTkaSafetyEffectiveness/R/SynthesizePositiveControls.R",".R","7961","127","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of UkaTkaSafetyFull +# +# 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. + +#' Synthesize positive controls +#' +#' @details +#' This function will synthesize positve controls based on the negative controls. The simulated outcomes +#' will be added to the cohort table. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param cohortDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param cohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' @param maxCores How many parallel cores should be used? If more cores are made available +#' this can speed up the analyses. +#' +#' @export +synthesizePositiveControls <- function(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable = ""cohort"", + oracleTempSchema, + outputFolder, + maxCores = 1, + timeAtRiskLabel) { + + + synthesisFolder <- file.path(outputFolder, paste0(""positiveControlSynthesis"", timeAtRiskLabel)) + if (!file.exists(synthesisFolder)) + dir.create(synthesisFolder) + + synthesisSummaryFile <- file.path(outputFolder, paste0(""SynthesisSummary"", timeAtRiskLabel, "".csv"")) + if (!file.exists(synthesisSummaryFile)) { + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""UkaTkaSafetyFull"") + negativeControls <- read.csv(pathToCsv) + exposureOutcomePairs <- data.frame(exposureId = negativeControls$targetId, + outcomeId = negativeControls$outcomeId) + exposureOutcomePairs <- unique(exposureOutcomePairs) + pathToJson <- system.file(""settings"", paste0(""positiveControlSynthArgs"", timeAtRiskLabel, "".json""), package = ""UkaTkaSafetyFull"") + args <- ParallelLogger::loadSettingsFromJson(pathToJson) + args$control$threads <- min(c(10, maxCores)) + + result <- MethodEvaluation::injectSignals(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + exposureDatabaseSchema = cohortDatabaseSchema, + exposureTable = cohortTable, + outcomeDatabaseSchema = cohortDatabaseSchema, + outcomeTable = cohortTable, + outputDatabaseSchema = cohortDatabaseSchema, + outputTable = cohortTable, + createOutputTable = FALSE, + exposureOutcomePairs = exposureOutcomePairs, + workFolder = synthesisFolder, + modelThreads = max(1, round(maxCores/8)), + generationThreads = min(6, maxCores), + # External args start here + outputIdOffset = args$outputIdOffset, + firstExposureOnly = args$firstExposureOnly, + firstOutcomeOnly = args$firstOutcomeOnly, + removePeopleWithPriorOutcomes = args$removePeopleWithPriorOutcomes, + modelType = args$modelType, + washoutPeriod = args$washoutPeriod, + riskWindowStart = args$riskWindowStart, + riskWindowEnd = args$riskWindowEnd, + addExposureDaysToEnd = args$addExposureDaysToEnd, + effectSizes = args$effectSizes, + precision = args$precision, + prior = args$prior, + control = args$control, + maxSubjectsForModel = args$maxSubjectsForModel, + minOutcomeCountForModel = args$minOutcomeCountForModel, + minOutcomeCountForInjection = args$minOutcomeCountForInjection, + covariateSettings = args$covariateSettings + # External args stop here + ) + write.csv(result, synthesisSummaryFile, row.names = FALSE) + } else { + result <- read.csv(synthesisSummaryFile) + } + ParallelLogger::logTrace(""Merging positive with negative controls "") + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""UkaTkaSafetyFull"") + negativeControls <- read.csv(pathToCsv) + + synthesisSummary <- read.csv(synthesisSummaryFile) + synthesisSummary$targetId <- synthesisSummary$exposureId + synthesisSummary <- merge(synthesisSummary, negativeControls) + synthesisSummary <- synthesisSummary[synthesisSummary$trueEffectSize != 0, ] + synthesisSummary$outcomeName <- paste0(synthesisSummary$OutcomeName, "", RR="", synthesisSummary$targetEffectSize) + synthesisSummary$oldOutcomeId <- synthesisSummary$outcomeId + synthesisSummary$outcomeId <- synthesisSummary$newOutcomeId + + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""UkaTkaSafetyFull"") + negativeControls <- read.csv(pathToCsv) + negativeControls$targetEffectSize <- 1 + negativeControls$trueEffectSize <- 1 + negativeControls$trueEffectSizeFirstExposure <- 1 + negativeControls$oldOutcomeId <- negativeControls$outcomeId + allControls <- rbind(negativeControls, synthesisSummary[, names(negativeControls)]) + write.csv(allControls, file.path(outputFolder, paste0(""AllControls"", timeAtRiskLabel, "".csv"")), row.names = FALSE) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","UkaTkaSafetyEffectiveness/R/CohortMethod.R",".R","12467","237","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of UkaTkaSafetyFull +# +# 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. + +#' Run CohortMethod package +#' +#' @details +#' Run the CohortMethod package, which implements the comparative cohort design. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param cohortDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param cohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param outputFolder Name of local folder where the results were generated; make sure to use forward slashes +#' (/). Do not use a folder on a network drive since this greatly impacts +#' performance. +#' @param maxCores How many parallel cores should be used? If more cores are made available +#' this can speed up the analyses. +#' +#' @export +runCohortMethod <- function(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable, + oracleTempSchema, + outputFolder, + maxCores, + timeAtRiskLabel) { + cmOutputFolder <- file.path(outputFolder, paste0(""cmOutput"", timeAtRiskLabel)) + if (!file.exists(cmOutputFolder)) { + dir.create(cmOutputFolder) + } + cmAnalysisListFile <- system.file(""settings"", + ""cmAnalysisList.json"", + package = ""UkaTkaSafetyFull"") + cmAnalysisList <- CohortMethod::loadCmAnalysisList(cmAnalysisListFile) + + # select cmAnalysisList elements and Os that correspond with each TAR + + if (timeAtRiskLabel == ""60d"") { + # analysisIds: 1, 4, 5; # Os: 8208, 8209, 8210, 8211 + cmAnalysisList <- cmAnalysisList[c(1, 4, 5)] + tcosList <- createTcos(outputFolder = outputFolder, timeAtRiskLabel = timeAtRiskLabel) + for (i in c(1,2)) { + os <- tcosList[[i]]$outcomeIds + os <- os[! os %in% c(8212, 8233)] # remove revision, opioids + tcosList[[i]]$outcomeIds <- os + } + } + if (timeAtRiskLabel == ""1yr"") { + # analysisIds: 2; # Os: 8208, 8209, 8210, 8211, 8212 + cmAnalysisList <- cmAnalysisList[c(2)] + tcosList <- createTcos(outputFolder = outputFolder, timeAtRiskLabel = timeAtRiskLabel) + for (i in c(1,2)) { + os <- tcosList[[i]]$outcomeIds + os <- os[! os %in% c(8233)] # remove opioids + tcosList[[i]]$outcomeIds <- os + } + } + if (timeAtRiskLabel == ""5yr"") { + # analysisIds: 3, 6, 7; # Os: 8208, 8209, 8210, 8211, 8212 + cmAnalysisList <- cmAnalysisList[c(3, 6, 7)] + tcosList <- createTcos(outputFolder = outputFolder, timeAtRiskLabel = timeAtRiskLabel) + for (i in c(1,2)) { + os <- tcosList[[i]]$outcomeIds + os <- os[! os %in% c(8233)] # remove opioids + tcosList[[i]]$outcomeIds <- os + } + } + if (timeAtRiskLabel == ""91d1yr"") { + # analysisIds: 8, 10, 11; # Os: 8233 + cmAnalysisList <- cmAnalysisList[c(8, 10, 11)] + tcosList <- createTcos(outputFolder = outputFolder, timeAtRiskLabel = timeAtRiskLabel) + for (i in c(1,2)) { + os <- tcosList[[i]]$outcomeIds + os <- os[! os %in% c(8208, 8209, 8210, 8211, 8212)] # remove all but opioids + tcosList[[i]]$outcomeIds <- os + } + } + if (timeAtRiskLabel == ""91d5yr"") { + # analysisIds: 9; # Os: 8233 + cmAnalysisList <- cmAnalysisList[c(9)] + tcosList <- createTcos(outputFolder = outputFolder, timeAtRiskLabel = timeAtRiskLabel) + for (i in c(1,2)) { + os <- tcosList[[i]]$outcomeIds + os <- os[! os %in% c(8208, 8209, 8210, 8211, 8212)] # remove all but opioids + tcosList[[i]]$outcomeIds <- os + } + } + outcomesOfInterest <- getOutcomesOfInterest() + results <- CohortMethod::runCmAnalyses(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + exposureDatabaseSchema = cohortDatabaseSchema, + exposureTable = cohortTable, + outcomeDatabaseSchema = cohortDatabaseSchema, + outcomeTable = cohortTable, + outputFolder = cmOutputFolder, + oracleTempSchema = oracleTempSchema, + cmAnalysisList = cmAnalysisList, + targetComparatorOutcomesList = tcosList, + getDbCohortMethodDataThreads = min(3, maxCores), + createStudyPopThreads = min(3, maxCores), + createPsThreads = max(1, round(maxCores/10)), + psCvThreads = min(10, maxCores), + trimMatchStratifyThreads = min(10, maxCores), + fitOutcomeModelThreads = max(1, round(maxCores/4)), + outcomeCvThreads = min(4, maxCores), + refitPsForEveryOutcome = FALSE, + outcomeIdsOfInterest = outcomesOfInterest) + + ParallelLogger::logInfo(""Summarizing results"") + analysisSummary <- CohortMethod::summarizeAnalyses(referenceTable = results, + outputFolder = cmOutputFolder) + analysisSummary <- addCohortNames(analysisSummary, ""targetId"", ""targetName"") + analysisSummary <- addCohortNames(analysisSummary, ""comparatorId"", ""comparatorName"") + analysisSummary <- addCohortNames(analysisSummary, ""outcomeId"", ""outcomeName"") + analysisSummary <- addAnalysisDescription(analysisSummary, ""analysisId"", ""analysisDescription"") + write.csv(analysisSummary, file.path(outputFolder, paste0(""analysisSummary"", timeAtRiskLabel, "".csv"")), row.names = FALSE) + + ParallelLogger::logInfo(""Computing covariate balance"") + balanceFolder <- file.path(outputFolder, ""balance"") + if (!file.exists(balanceFolder)) { + dir.create(balanceFolder) + } + subset <- results[results$outcomeId %in% outcomesOfInterest,] + subset <- subset[subset$strataFile != """", ] + if (nrow(subset) > 0) { + subset <- split(subset, seq(nrow(subset))) + cluster <- ParallelLogger::makeCluster(min(3, maxCores)) + ParallelLogger::clusterApply(cluster, subset, computeCovariateBalance, cmOutputFolder = cmOutputFolder, balanceFolder = balanceFolder) + ParallelLogger::stopCluster(cluster) + } +} + +computeCovariateBalance <- function(row, cmOutputFolder, balanceFolder) { + outputFileName <- file.path(balanceFolder, + sprintf(""bal_t%s_c%s_o%s_a%s.rds"", row$targetId, row$comparatorId, row$outcomeId, row$analysisId)) + if (!file.exists(outputFileName)) { + ParallelLogger::logTrace(""Creating covariate balance file "", outputFileName) + cohortMethodDataFolder <- file.path(cmOutputFolder, row$cohortMethodDataFolder) + cohortMethodData <- CohortMethod::loadCohortMethodData(cohortMethodDataFolder) + strataFile <- file.path(cmOutputFolder, row$strataFile) + strata <- readRDS(strataFile) + balance <- CohortMethod::computeCovariateBalance(population = strata, cohortMethodData = cohortMethodData) + saveRDS(balance, outputFileName) + } +} + +addAnalysisDescription <- function(data, IdColumnName = ""analysisId"", nameColumnName = ""analysisDescription"") { + cmAnalysisListFile <- system.file(""settings"", + ""cmAnalysisList.json"", + package = ""UkaTkaSafetyFull"") + cmAnalysisList <- CohortMethod::loadCmAnalysisList(cmAnalysisListFile) + idToName <- lapply(cmAnalysisList, function(x) data.frame(analysisId = x$analysisId, description = as.character(x$description))) + idToName <- do.call(""rbind"", idToName) + names(idToName)[1] <- IdColumnName + names(idToName)[2] <- nameColumnName + data <- merge(data, idToName, all.x = TRUE) + # Change order of columns: + idCol <- which(colnames(data) == IdColumnName) + if (idCol < ncol(data) - 1) { + data <- data[, c(1:idCol, ncol(data) , (idCol+1):(ncol(data)-1))] + } + return(data) +} + +createTcos <- function(outputFolder, + timeAtRiskLabel) { + pathToCsv <- system.file(""settings"", ""TcosOfInterest.csv"", package = ""UkaTkaSafetyFull"") + tcosOfInterest <- read.csv(pathToCsv, stringsAsFactors = FALSE) + allControls <- getAllControls(outputFolder, timeAtRiskLabel) + tcs <- unique(rbind(tcosOfInterest[, c(""targetId"", ""comparatorId"")], + allControls[, c(""targetId"", ""comparatorId"")])) + createTco <- function(i) { + targetId <- tcs$targetId[i] + comparatorId <- tcs$comparatorId[i] + outcomeIds <- as.character(tcosOfInterest$outcomeIds[tcosOfInterest$targetId == targetId & tcosOfInterest$comparatorId == comparatorId]) + outcomeIds <- as.numeric(strsplit(outcomeIds, split = "";"")[[1]]) + outcomeIds <- c(outcomeIds, allControls$outcomeId[allControls$targetId == targetId & allControls$comparatorId == comparatorId]) + excludeConceptIds <- as.character(tcosOfInterest$excludedCovariateConceptIds[tcosOfInterest$targetId == targetId & tcosOfInterest$comparatorId == comparatorId]) + excludeConceptIds <- as.numeric(strsplit(excludeConceptIds, split = "";"")[[1]]) + tco <- CohortMethod::createTargetComparatorOutcomes(targetId = targetId, + comparatorId = comparatorId, + outcomeIds = outcomeIds, + excludedCovariateConceptIds = excludeConceptIds) + return(tco) + } + tcosList <- lapply(1:nrow(tcs), createTco) + return(tcosList) +} + +getOutcomesOfInterest <- function() { + pathToCsv <- system.file(""settings"", ""TcosOfInterest.csv"", package = ""UkaTkaSafetyFull"") + tcosOfInterest <- read.csv(pathToCsv, stringsAsFactors = FALSE) + outcomeIds <- as.character(tcosOfInterest$outcomeIds) + outcomeIds <- do.call(""c"", (strsplit(outcomeIds, split = "";""))) + outcomeIds <- unique(as.numeric(outcomeIds)) + return(outcomeIds) +} + +getAllControls <- function(outputFolder, + timeAtRiskLabel) { + allControlsFile <- file.path(outputFolder, paste0(""AllControls"", timeAtRiskLabel, "".csv"")) + if (file.exists(allControlsFile)) { + # Positive controls must have been synthesized. Include both positive and negative controls. + allControls <- read.csv(allControlsFile) + } else { + # Include only negative controls + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""UkaTkaSafetyFull"") + allControls <- read.csv(pathToCsv) + allControls$oldOutcomeId <- allControls$outcomeId + allControls$targetEffectSize <- rep(1, nrow(allControls)) + } + return(allControls) +}","R" +"Pharmacogenetics","OHDSI/StudyProtocols","UkaTkaSafetyEffectiveness/R/CreateAllCohorts.R",".R","5945","114","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of UkaTkaSafetyFull +# +# 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. + +#' Create the exposure and outcome cohorts +#' +#' @details +#' This function will create the exposure and outcome cohorts following the definitions included in +#' this package. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param cohortDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param cohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' +#' @export +createCohorts <- function(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable = ""cohort"", + oracleTempSchema, + outputFolder) { + if (!file.exists(outputFolder)) + dir.create(outputFolder) + + conn <- DatabaseConnector::connect(connectionDetails) + + .createCohorts(connection = conn, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder) + + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""UkaTkaSafetyFull"") + negativeControls <- read.csv(pathToCsv) + + ParallelLogger::logInfo(""Creating negative control outcome cohorts"") + # Currently assuming all negative controls are outcome controls + negativeControlOutcomes <- negativeControls + sql <- SqlRender::loadRenderTranslateSql(""NegativeControlOutcomes.sql"", + ""UkaTkaSafetyFull"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = cohortDatabaseSchema, + target_cohort_table = cohortTable, + outcome_ids = unique(negativeControlOutcomes$outcomeId)) + DatabaseConnector::executeSql(conn, sql) + + # Check number of subjects per cohort: + ParallelLogger::logInfo(""Counting cohorts"") + sql <- SqlRender::loadRenderTranslateSql(""GetCounts.sql"", + ""UkaTkaSafetyFull"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + work_database_schema = cohortDatabaseSchema, + study_cohort_table = cohortTable) + counts <- DatabaseConnector::querySql(conn, sql) + colnames(counts) <- SqlRender::snakeCaseToCamelCase(colnames(counts)) + counts <- addCohortNames(counts) + write.csv(counts, file.path(outputFolder, ""CohortCounts.csv""), row.names = FALSE) + + DatabaseConnector::disconnect(conn) +} + +addCohortNames <- function(data, IdColumnName = ""cohortDefinitionId"", nameColumnName = ""cohortName"") { + pathToCsv <- system.file(""settings"", ""CohortsToCreate.csv"", package = ""UkaTkaSafetyFull"") + cohortsToCreate <- read.csv(pathToCsv) + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""UkaTkaSafetyFull"") + negativeControls <- read.csv(pathToCsv) + + idToName <- data.frame(cohortId = c(cohortsToCreate$cohortId, + negativeControls$outcomeId), + cohortName = c(as.character(cohortsToCreate$atlasName), + as.character(negativeControls$outcomeName))) + idToName <- idToName[order(idToName$cohortId), ] + idToName <- idToName[!duplicated(idToName$cohortId), ] + names(idToName)[1] <- IdColumnName + names(idToName)[2] <- nameColumnName + data <- merge(data, idToName, all.x = TRUE) + # Change order of columns: + idCol <- which(colnames(data) == IdColumnName) + if (idCol < ncol(data) - 1) { + data <- data[, c(1:idCol, ncol(data) , (idCol+1):(ncol(data)-1))] + } + return(data) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","UkaTkaSafetyEffectiveness/R/ShinyApps.R",".R","5963","149","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of UkaTkaSafetyFull +# +# 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. + +#' Prepare results for the Evidence Explorer Shiny app. +#' +#' @param resultsZipFile Path to a zip file containing results from a study executed by this package. +#' @param dataFolder A folder where the data files for the Evidence Explorer app will be stored. +#' +#' @examples +#' +#' \dontrun{ +#' # Add results from three databases to the Shiny app data folder: +#' prepareForEvidenceExplorer(""ResultsMDCD.zip"", ""/shinyData"") +#' prepareForEvidenceExplorer(""ResultsMDCR.zip"", ""/shinyData"") +#' prepareForEvidenceExplorer(""ResultsCCAE.zip"", ""/shinyData"") +#' +#' # Launch the Shiny app: +#' launchEvidenceExplorer(""/shinyData"") +#' } +#' +#' @export +prepareForEvidenceExplorer <- function(resultsZipFile, dataFolder) { + # resultsZipFile <- ""c:/temp/ResultsMDCD.zip"" + # dataFolder <- ""c:/temp/shinyData"" + if (!file.exists(dataFolder)) { + dir.create(dataFolder, recursive = TRUE) + } + tempFolder <- tempdir() + on.exit(unlink(tempFolder, recursive = TRUE)) + utils::unzip(resultsZipFile, exdir = tempFolder) + databaseFileName <- file.path(tempFolder, ""database.csv"") + if (!file.exists(databaseFileName)) { + stop(""Cannot find file database.csv in zip file"") + } + databaseId <- read.csv(databaseFileName, stringsAsFactors = FALSE)$database_id + splittableTables <- c(""covariate_balance"", ""preference_score_dist"", ""kaplan_meier_dist"") + + processSubet <- function(subset, tableName) { + targetId <- subset$target_id[1] + comparatorId <- subset$comparator_id[1] + fileName <- sprintf(""%s_t%s_c%s_%s.rds"", tableName, targetId, comparatorId, databaseId) + saveRDS(subset, file.path(dataFolder, fileName)) + } + + processFile <- function(file) { + tableName <- gsub("".csv$"", """", file) + table <- read.csv(file.path(tempFolder, file)) + if (tableName %in% splittableTables) { + subsets <- split(table, list(table$target_id, table$comparator_id), drop = TRUE) + plyr::l_ply(subsets, processSubet, tableName = tableName) + } else { + saveRDS(table, file.path(dataFolder, sprintf(""%s_%s.rds"", tableName, databaseId))) + } + } + + files <- list.files(tempFolder, "".*.csv"") + plyr::l_ply(files, processFile, .progress = ""text"") +} + + +#' Launch the SqlRender Developer Shiny app +#' +#' @param dataFolder A folder where the data files for the Evidence Explorer app will be stored. Use the +#' \code{\link{prepareForEvidenceExplorer}} to populate this folder. +#' @param blind Should the user be blinded to the main results? +#' @param launch.browser Should the app be launched in your default browser, or in a Shiny window. +#' Note: copying to clipboard will not work in a Shiny window. +#' +#' @details +#' Launches a Shiny app that allows the user to explore the evidence +#' +#' @export +launchEvidenceExplorer <- function(dataFolder, blind = TRUE, launch.browser = TRUE) { + ensure_installed(""DT"") + appDir <- system.file(""shiny"", ""EvidenceExplorer"", package = ""UkaTkaSafetyFull"") + .GlobalEnv$shinySettings <- list(dataFolder = dataFolder, blind = blind) + on.exit(rm(shinySettings, envir=.GlobalEnv)) + shiny::runApp(appDir) +} + +# Borrowed from devtools: https://github.com/hadley/devtools/blob/ba7a5a4abd8258c52cb156e7b26bb4bf47a79f0b/R/utils.r#L44 +is_installed <- function (pkg, version = 0) { + installed_version <- tryCatch(utils::packageVersion(pkg), + error = function(e) NA) + !is.na(installed_version) && installed_version >= version +} + +# Borrowed and adapted from devtools: https://github.com/hadley/devtools/blob/ba7a5a4abd8258c52cb156e7b26bb4bf47a79f0b/R/utils.r#L74 +ensure_installed <- function(pkg) { + if (!is_installed(pkg)) { + msg <- paste0(sQuote(pkg), "" must be installed for this functionality."") + if (interactive()) { + message(msg, ""\nWould you like to install it?"") + if (menu(c(""Yes"", ""No"")) == 1) { + install.packages(pkg) + } else { + stop(msg, call. = FALSE) + } + } else { + stop(msg, call. = FALSE) + } + } +} + +#' @export +compileShinyData <- function(studyFolder, + databases) { + fullShinyDataFolder <- file.path(studyFolder, ""shinyDataAll"") + if (!file.exists(fullShinyDataFolder)) + dir.create(fullShinyDataFolder) + + dummyFolder <- file.path(studyFolder, databases[1], ""shinyData"") + resultNames <- list.files(dummyFolder, pattern = "".*\\.rds$"") + resultNames <- sub(paste0(""_"", databases[1], "".rds""), """", resultNames) + + # rbind database-specific files + for (resultName in resultNames) { + shinyFileNames <- NULL + for (database in databases) { + shinyDataFolder <- file.path(studyFolder, database, ""shinyData"") + shinyFileName <- file.path(shinyDataFolder, paste0(resultName, ""_"", database, "".rds"")) + shinyFileNames <- c(shinyFileNames, shinyFileName) + } + shinyDataList <- lapply(shinyFileNames, readRDS) + if (resultName == ""cohort_method_analysis"") { + shinyData <- shinyDataList[[1]] # settings unique across DBs + } else if (resultName == ""exposure_of_interest"") { + shinyData <- shinyDataList[[1]] # settings unique across DBs + } else { + shinyData <- do.call(""rbind"", shinyDataList) + shinyData <- shinyData[!duplicated(shinyData), ] + } + saveRDS(shinyData, file.path(fullShinyDataFolder, paste0(resultName, "".rds""))) + } +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","UkaTkaSafetyEffectiveness/R/SubmitResults.R",".R","2011","50","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of UkaTkaSafetyFull +# +# 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. + +#' Submit the study results to the study coordinating center +#' +#' @details +#' This will upload the file \code{StudyResults.zip} to the study coordinating center using Amazon S3. +#' This requires an active internet connection. +#' +#' @param outputFolder Name of local folder where the results were generated; make sure to use forward slashes +#' (/). Do not use a folder on a network drive since this greatly impacts +#' performance. +#' @param key The key string as provided by the study coordinator +#' @param secret The secret string as provided by the study coordinator +#' +#' @return +#' TRUE if the upload was successful. +#' +#' @export +submitResults <- function(outputFolder, key, secret) { + zipName <- file.path(outputFolder, ""StudyResults.zip"") + if (!file.exists(zipName)) { + stop(paste(""Cannot find file"", zipName)) + } + writeLines(paste0(""Uploading file '"", zipName, ""' to study coordinating center"")) + result <- OhdsiSharing::putS3File(file = zipName, + bucket = ""ohdsi-study-skeleton"", + key = key, + secret = secret) + if (result) { + writeLines(""Upload complete"") + } else { + writeLines(""Upload failed. Please contact the study coordinator"") + } + invisible(result) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","UkaTkaSafetyEffectiveness/R/Diagnostics.R",".R","11604","195","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of UkaTkaSafetyFull +# +# 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. + +#' Generate diagnostics +#' +#' @details +#' This function generates analyses diagnostics. Requires the study to be executed first. +#' +#' @param outputFolder Name of local folder where the results were generated; make sure to use forward slashes +#' (/). Do not use a folder on a network drive since this greatly impacts +#' performance. +#' @param maxCores How many parallel cores should be used? If more cores are made +#' available this can speed up the analyses. +#' +#' @export +generateDiagnostics <- function(outputFolder, + timeAtRiskLabel, + maxCores) { + cmOutputFolder <- file.path(outputFolder, paste0(""cmOutput"", timeAtRiskLabel)) + diagnosticsFolder <- file.path(outputFolder, ""diagnostics"") + if (!file.exists(diagnosticsFolder)) { + dir.create(diagnosticsFolder) + } + reference <- readRDS(file.path(cmOutputFolder, ""outcomeModelReference.rds"")) + reference <- addCohortNames(reference, ""targetId"", ""targetName"") + reference <- addCohortNames(reference, ""comparatorId"", ""comparatorName"") + reference <- addCohortNames(reference, ""outcomeId"", ""outcomeName"") + reference <- addAnalysisDescription(reference, ""analysisId"", ""analysisDescription"") + analysisSummary <- read.csv(file.path(outputFolder, paste0(""analysisSummary"", timeAtRiskLabel, "".csv""))) + reference <- merge(reference, analysisSummary[, c(""targetId"", ""comparatorId"", ""outcomeId"", ""analysisId"", ""logRr"", ""seLogRr"")]) + allControls <- getAllControls(outputFolder, timeAtRiskLabel) + subsets <- split(reference, list(reference$targetId, reference$comparatorId, reference$analysisId), drop = TRUE) + # subset <- subsets[[1]] + cluster <- ParallelLogger::makeCluster(min(4, maxCores)) + ParallelLogger::clusterApply(cluster = cluster, + x = subsets, + fun = createDiagnosticsForSubset, + allControls = allControls, + outputFolder = outputFolder, + cmOutputFolder = cmOutputFolder, + diagnosticsFolder = diagnosticsFolder) + ParallelLogger::stopCluster(cluster) +} + +createDiagnosticsForSubset <- function(subset, allControls, outputFolder, cmOutputFolder, diagnosticsFolder) { + targetId <- subset$targetId[1] + comparatorId <- subset$comparatorId[1] + analysisId <- subset$analysisId[1] + ParallelLogger::logTrace(""Generating diagnostics for target "", targetId, "", comparator "", comparatorId, "", analysis "", analysisId) + ParallelLogger::logDebug(""Subset has "", nrow(subset),"" entries with "", sum(!is.na(subset$seLogRr)), "" valid estimates"") + title <- paste(paste(subset$targetName[1], subset$comparatorName[1], sep = "" - ""), + subset$analysisDescription[1], sep = ""\n"") + controlSubset <- merge(subset, + allControls[, c(""targetId"", ""comparatorId"", ""outcomeId"", ""oldOutcomeId"", ""targetEffectSize"")]) + + # Empirical calibration ---------------------------------------------------------------------------------- + + # Negative controls + negControlSubset <- controlSubset[controlSubset$targetEffectSize == 1, ] + validNcs <- sum(!is.na(negControlSubset$seLogRr)) + ParallelLogger::logDebug(""Subset has "", validNcs, "" valid negative control estimates"") + if (validNcs >= 5) { + null <- EmpiricalCalibration::fitMcmcNull(negControlSubset$logRr, negControlSubset$seLogRr) + fileName <- file.path(diagnosticsFolder, paste0(""nullDistribution_a"", analysisId, ""_t"", targetId, ""_c"", comparatorId, "".png"")) + EmpiricalCalibration::plotCalibrationEffect(logRrNegatives = negControlSubset$logRr, + seLogRrNegatives = negControlSubset$seLogRr, + null = null, + showCis = TRUE, + title = title, + fileName = fileName) + } else { + null <- NULL + } + + # Positive and negative controls + validPcs <- sum(!is.na(controlSubset$seLogRr[controlSubset$targetEffectSize != 1])) + ParallelLogger::logDebug(""Subset has "", validPcs, "" valid positive control estimates"") + if (validPcs >= 10) { + model <- EmpiricalCalibration::fitSystematicErrorModel(logRr = controlSubset$logRr, + seLogRr = controlSubset$seLogRr, + trueLogRr = log(controlSubset$targetEffectSize), + estimateCovarianceMatrix = FALSE) + + fileName <- file.path(diagnosticsFolder, paste0(""controls_a"", analysisId, ""_t"", targetId, ""_c"", comparatorId, "".png"")) + EmpiricalCalibration::plotCiCalibrationEffect(logRr = controlSubset$logRr, + seLogRr = controlSubset$seLogRr, + trueLogRr = log(controlSubset$targetEffectSize), + model = model, + title = title, + fileName = fileName) + + fileName <- file.path(diagnosticsFolder, paste0(""ciCoverage_a"", analysisId, ""_t"", targetId, ""_c"", comparatorId, "".png"")) + evaluation <- EmpiricalCalibration::evaluateCiCalibration(logRr = controlSubset$logRr, + seLogRr = controlSubset$seLogRr, + trueLogRr = log(controlSubset$targetEffectSize), + crossValidationGroup = controlSubset$oldOutcomeId) + EmpiricalCalibration::plotCiCoverage(evaluation = evaluation, + title = title, + fileName = fileName) + } + + # Statistical power -------------------------------------------------------------------------------------- + outcomeIdsOfInterest <- subset$outcomeId[!(subset$outcomeId %in% controlSubset$outcomeId)] + mdrrs <- data.frame() + for (outcomeId in outcomeIdsOfInterest) { + strataFile <- subset$strataFile[subset$outcomeId == outcomeId] + if (strataFile == """") { + strataFile <- subset$studyPopFile[subset$outcomeId == outcomeId] + } + population <- readRDS(file.path(cmOutputFolder, strataFile)) + modelFile <- subset$outcomeModelFile[subset$outcomeId == outcomeId] + model <- readRDS(file.path(cmOutputFolder, modelFile)) + mdrr <- CohortMethod::computeMdrr(population = population, + alpha = 0.05, + power = 0.8, + twoSided = TRUE, + modelType = model$outcomeModelType) + + mdrr$outcomeId <- outcomeId + mdrr$outcomeName <- subset$outcomeName[subset$outcomeId == outcomeId] + mdrrs <- rbind(mdrrs, mdrr) + } + mdrrs$analysisId <- analysisId + mdrrs$analysisDescription <- subset$analysisDescription[1] + mdrrs$targetId <- targetId + mdrrs$targetName <- subset$targetName[1] + mdrrs$comparatorId <- comparatorId + mdrrs$comparatorName <- subset$comparatorName[1] + fileName <- file.path(diagnosticsFolder, paste0(""mdrr_a"", analysisId, ""_t"", targetId, ""_c"", comparatorId, "".csv"")) + write.csv(mdrrs, fileName, row.names = FALSE) + + # Covariate balance -------------------------------------------------------------------------------------- + outcomeIdsOfInterest <- subset$outcomeId[!(subset$outcomeId %in% controlSubset$outcomeId)] + outcomeId = outcomeIdsOfInterest[1] + for (outcomeId in outcomeIdsOfInterest) { + balanceFileName <- file.path(outputFolder, + ""balance"", + sprintf(""bal_t%s_c%s_o%s_a%s.rds"", targetId, comparatorId, outcomeId, analysisId)) + if (file.exists(balanceFileName)) { + balance <- readRDS(balanceFileName) + fileName = file.path(diagnosticsFolder, + sprintf(""bal_t%s_c%s_o%s_a%s.csv"", targetId, comparatorId, outcomeId, analysisId)) + write.csv(balance, fileName, row.names = FALSE) + + outcomeTitle <- paste(paste(subset$targetName[1], subset$comparatorName[1], sep = "" - ""), + subset$outcomeName[subset$outcomeId == outcomeId], + subset$analysisDescription[1], sep = ""\n"") + fileName = file.path(diagnosticsFolder, + sprintf(""balanceScatter_t%s_c%s_o%s_a%s.png"", targetId, comparatorId, outcomeId, analysisId)) + balanceScatterPlot <- CohortMethod::plotCovariateBalanceScatterPlot(balance = balance, + beforeLabel = ""Before PS adjustment"", + afterLabel = ""After PS adjustment"", + showCovariateCountLabel = TRUE, + showMaxLabel = TRUE, + title = outcomeTitle, + fileName = fileName) + + fileName = file.path(diagnosticsFolder, + sprintf(""balanceTop_t%s_c%s_o%s_a%s.png"", targetId, comparatorId, outcomeId, analysisId)) + balanceTopPlot <- CohortMethod::plotCovariateBalanceOfTopVariables(balance = balance, + beforeLabel = ""Before PS adjustment"", + afterLabel = ""After PS adjustment"", + title = outcomeTitle, + fileName = fileName) + } + } + # Propensity score distribution -------------------------------------------------------------------------- + psFile <- subset$sharedPsFile[1] + if (psFile != """") { + ps <- readRDS(file.path(cmOutputFolder, psFile)) + fileName <- file.path(diagnosticsFolder, paste0(""ps_a"", analysisId, ""_t"", targetId, ""_c"", comparatorId, "".png"")) + CohortMethod::plotPs(data = ps, + targetLabel = subset$targetName[1], + comparatorLabel = subset$comparatorName[1], + showCountsLabel = TRUE, + showAucLabel = TRUE, + showEquiposeLabel = TRUE, + title = subset$analysisDescription[1], + fileName = fileName) + } +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","UkaTkaSafetyEffectiveness/R/MetaAnalysis.R",".R","7987","185","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of UkaTkaSafetyFull +# +# 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. + +#' @export +doMetaAnalysis <- function(outputFolders, + maOutputFolder, + maxCores) { + + OhdsiRTools::logInfo(""Performing meta-analysis"") + shinyDataFolder <- file.path(maOutputFolder, ""shinyData"") + if (!file.exists(shinyDataFolder)) + dir.create(shinyDataFolder) + + loadResults <- function(outputFolder) { + files <- list.files(file.path(outputFolder, ""exportFull""), pattern = ""cohort_method_result.csv"", full.names = TRUE) + OhdsiRTools::logInfo(""Loading "", files[1], "" for meta-analysis"") + return(read.csv(files[1], stringsAsFactors = FALSE)) + } + allResults <- lapply(outputFolders, loadResults) + allResults <- do.call(rbind, allResults) + + allControls <- list() + timeAtRisks <- c(""60d"", ""1yr"", ""5yr"", ""91d1yr"", ""91d5yr"") + for (timeAtRisk in timeAtRisks) { + controls <- lapply(outputFolders, getAllControls, timeAtRiskLabel = timeAtRisk) + controls <- do.call(rbind, controls) + controls <- controls[, c(""targetId"", ""comparatorId"", ""outcomeId"", ""targetEffectSize"")] + allControls[[length(allControls) + 1]] <- controls + } + allControls <- do.call(rbind, allControls) + allControls <- allControls[!duplicated(allControls), ] + + ncIds <- allControls$outcomeId[allControls$targetEffectSize == 1] + allResults$type[allResults$outcome_id %in% ncIds] <- ""Negative control"" + pcIds <- allControls$outcomeId[allControls$targetEffectSize != 1] + allResults$type[allResults$outcome_id %in% pcIds] <- ""Positive control"" + allResults$type[is.na(allResults$type)] <- ""Outcome of interest"" + + groups <- split(allResults, paste(allResults$target_id, allResults$comparator_id, allResults$analysis_id)) + cluster <- ParallelLogger::makeCluster(min(maxCores, 12)) + results <- ParallelLogger::clusterApply(cluster, + groups, + computeGroupMetaAnalysis, + shinyDataFolder = shinyDataFolder, + allControls = allControls) + ParallelLogger::stopCluster(cluster) + results <- do.call(rbind, results) + + fileName <- file.path(resultsFolder, ""cohort_method_results_Meta-analysis.csv"") + write.csv(results, fileName, row.names = FALSE, na = """") + fileName <- file.path(shinyDataFolder, ""cohort_method_result_Meta-analysis.rds"") + saveRDS(results, fileName) +} + +computeGroupMetaAnalysis <- function(group, + shinyDataFolder, + allControls) { + + # group <- groups[[""8257 8256 1""]] + analysisId <- group$analysis_id[1] + targetId <- group$target_id[1] + comparatorId <- group$comparator_id[1] + OhdsiRTools::logTrace(""Performing meta-analysis for target "", targetId, "", comparator "", comparatorId, "", analysis"", analysisId) + outcomeGroups <- split(group, group$outcome_id) + outcomeGroupResults <- lapply(outcomeGroups, computeSingleMetaAnalysis) + groupResults <- do.call(rbind, outcomeGroupResults) + + + ncs <- groupResults[groupResults$type == ""Negative control"", ] + ncs <- ncs[!is.na(ncs$se_log_rr), ] + if (nrow(ncs) > 5) { + null <- EmpiricalCalibration::fitMcmcNull(ncs$log_rr, ncs$se_log_rr) + calibratedP <- EmpiricalCalibration::calibrateP(null = null, + logRr = groupResults$log_rr, + seLogRr = groupResults$se_log_rr) + groupResults$calibrated_p <- calibratedP$p + } else { + groupResults$calibrated_p <- rep(NA, nrow(groupResults)) + } + pcs <- groupResults[groupResults$type == ""Positive control"", ] + pcs <- pcs[!is.na(pcs$se_log_rr), ] + if (nrow(pcs) > 5) { + controls <- merge(groupResults, + allControls, + by.x = c(""target_id"", ""comparator_id"", ""outcome_id""), + by.y = c(""targetId"", ""comparatorId"", ""outcomeId"")) + model <- EmpiricalCalibration::fitSystematicErrorModel(logRr = controls$log_rr, + seLogRr = controls$se_log_rr, + trueLogRr = log(controls$targetEffectSize), + estimateCovarianceMatrix = FALSE) + calibratedCi <- EmpiricalCalibration::calibrateConfidenceInterval(logRr = groupResults$log_rr, + seLogRr = groupResults$se_log_rr, + model = model) + groupResults$calibrated_rr <- exp(calibratedCi$logRr) + groupResults$calibrated_ci_95_lb <- exp(calibratedCi$logLb95Rr) + groupResults$calibrated_ci_95_ub <- exp(calibratedCi$logUb95Rr) + groupResults$calibrated_log_rr <- calibratedCi$logRr + groupResults$calibrated_se_log_rr <- calibratedCi$seLogRr + } else { + groupResults$calibrated_rr <- rep(NA, nrow(groupResults)) + groupResults$calibrated_ci_95_lb <- rep(NA, nrow(groupResults)) + groupResults$calibrated_ci_95_ub <- rep(NA, nrow(groupResults)) + groupResults$calibrated_log_rr <- rep(NA, nrow(groupResults)) + groupResults$calibrated_se_log_rr <- rep(NA, nrow(groupResults)) + } + return(groupResults) +} + +computeSingleMetaAnalysis <- function(outcomeGroup) { + # outcomeGroup <- outcomeGroups[[2]] + maRow <- outcomeGroup[1, ] + outcomeGroup <- outcomeGroup[!is.na(outcomeGroup$se_log_rr), ] + if (nrow(outcomeGroup) == 0) { + maRow$target_subjects <- 0 + maRow$comparator_subjects <- 0 + maRow$target_days <- 0 + maRow$comparator_days <- 0 + maRow$target_outcomes <- 0 + maRow$comparator_outcomes <- 0 + maRow$rr <- NA + maRow$ci_95_lb <- NA + maRow$ci_95_ub <- NA + maRow$p <- NA + maRow$log_rr <- NA + maRow$se_log_rr <- NA + maRow$i_2 <- NA + } else if (nrow(outcomeGroup) == 1) { + maRow <- outcomeGroup[1, ] + maRow$i_2 <- 0 + } else { + maRow$target_subjects <- sum(outcomeGroup$target_subjects) + maRow$comparator_subjects <- sum(outcomeGroup$comparator_subjects) + maRow$target_days <- sum(outcomeGroup$target_days) + maRow$comparator_days <- sum(outcomeGroup$comparator_days) + maRow$target_outcomes <- sum(outcomeGroup$target_outcomes) + maRow$comparator_outcomes <- sum(outcomeGroup$comparator_outcomes) + meta <- meta::metagen(outcomeGroup$log_rr, outcomeGroup$se_log_rr, sm = ""RR"", hakn = FALSE) + s <- summary(meta) + maRow$i_2 <- s$I2$TE + if (maRow$i_2 < .40) { + rnd <- s$random + maRow$rr <- exp(rnd$TE) + maRow$ci_95_lb <- exp(rnd$lower) + maRow$ci_95_ub <- exp(rnd$upper) + maRow$p <- rnd$p + maRow$log_rr <- rnd$TE + maRow$se_log_rr <- rnd$seTE + } else { + maRow$rr <- NA + maRow$ci_95_lb <- NA + maRow$ci_95_ub <- NA + maRow$p <- NA + maRow$log_rr <- NA + maRow$se_log_rr <- NA + } + } + if (is.na(maRow$log_rr)) { + maRow$mdrr <- NA + } else { + alpha <- 0.05 + power <- 0.8 + z1MinAlpha <- qnorm(1 - alpha/2) + zBeta <- -qnorm(1 - power) + pA <- maRow$target_subjects / (maRow$target_subjects + maRow$comparator_subjects) + pB <- 1 - pA + totalEvents <- maRow$target_outcomes + maRow$comparator_outcomes + maRow$mdrr <- exp(sqrt((zBeta + z1MinAlpha)^2/(totalEvents * pA * pB))) + } + maRow$database_id <- ""Meta-analysis"" + return(maRow) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","UkaTkaSafetyEffectiveness/R/Package.R",".R","947","27","# @file Package.R +# +# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of UkaTkaSafetyFull +# +# 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. + +#' UkaTkaSafetyFull +#' +#' @docType package +#' @name UkaTkaSafetyFull +#' @importFrom stats aggregate density pnorm qnorm quantile +#' @importFrom utils read.csv write.csv install.packages menu setTxtProgressBar txtProgressBar write.table +#' @import DatabaseConnector +NULL +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","UkaTkaSafetyEffectiveness/extras/PackageMaintenance.R",".R","2629","54","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of UkaTkaSafetyFull +# +# 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. + +# Format and check code --------------------------------------------------- +OhdsiRTools::formatRFolder() +OhdsiRTools::checkUsagePackage(""UkaTkaSafetyFull"") +OhdsiRTools::updateCopyrightYearFolder() + +# Create manual ----------------------------------------------------------- +shell(""rm extras/UkaTkaSafetyFull.pdf"") +shell(""R CMD Rd2pdf ./ --output=extras/UkaTkaSafetyFull.pdf"") + +# Create vignettes --------------------------------------------------------- +rmarkdown::render(""vignettes/UsingSkeletonPackage.Rmd"", + output_file = ""../inst/doc/UsingSkeletonPackage.pdf"", + rmarkdown::pdf_document(latex_engine = ""pdflatex"", + toc = TRUE, + number_sections = TRUE)) + +rmarkdown::render(""vignettes/DataModel.Rmd"", + output_file = ""../inst/doc/DataModel.pdf"", + rmarkdown::pdf_document(latex_engine = ""pdflatex"", + toc = TRUE, + number_sections = TRUE)) + +# Insert cohort definitions from ATLAS into package ----------------------- +OhdsiRTools::insertCohortDefinitionSetInPackage(fileName = ""CohortsToCreate.csv"", + baseUrl = Sys.getenv(""baseUrl""), + insertTableSql = TRUE, + insertCohortCreationR = TRUE, + generateStats = FALSE, + packageName = ""UkaTkaSafetyFull"") + +# Create analysis details ------------------------------------------------- +source(""extras/CreateStudyAnalysisDetails.R"") +createAnalysesDetails(""inst/settings/"") +createPositiveControlSynthesisArgs(""inst/settings/"") + +# Store environment in which the study was executed ----------------------- +OhdsiRTools::insertEnvironmentSnapshotInPackage(""UkaTkaSafetyFull"") +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","UkaTkaSafetyEffectiveness/extras/CreateCodeSetWorkbook.R",".R","477","7","# Create codeset workbook ------------------------------------------------------ +OhdsiRTools::createConceptSetWorkbook(conceptSetIds = 7468:7484, + workFolder = ""S:/StudyResults/UkaTkaSafetyFull/report"", + baseUrl = Sys.getenv(""baseUrl""), + included = TRUE, + mapped = TRUE, + formatName = TRUE)","R" +"Pharmacogenetics","OHDSI/StudyProtocols","UkaTkaSafetyEffectiveness/extras/CodeToRun.R",".R","5121","122","library(UkaTkaSafetyFull) +options(fftempdir = ""S:/FFTemp"") +maxCores <- parallel::detectCores() +studyFolder <- ""S:/StudyResults/UkaTkaSafetyFull"" + +# server connection: +connectionDetails <- DatabaseConnector::createConnectionDetails(dbms = ""pdw"", + server = Sys.getenv(""server""), + user = NULL, + password = NULL, + port = Sys.getenv(""port"")) + +mailSettings <- list(from = Sys.getenv(""emailAddress""), + to = c(Sys.getenv(""emailAddress"")), + smtp = list(host.name = Sys.getenv(""emailHost""), port = 25, + user.name = Sys.getenv(""emailAddress""), + passwd = Sys.getenv(""emailPassword""), ssl = FALSE), + authenticate = FALSE, + send = TRUE) + +# MDCR settings ---------------------------------------------------------------- +databaseId <- ""MDCR"" +databaseName <- ""MDCR"" +databaseDescription <- ""MDCR"" +cdmDatabaseSchema = """" +outputFolder <- file.path(studyFolder, databaseName) +cohortDatabaseSchema <- ""scratch.dbo"" +cohortTable <- """" + +# MDCD settings ---------------------------------------------------------------- +databaseId <- ""MDCD"" +databaseName <- ""MDCD"" +databaseDescription <- ""MDCD"" +cdmDatabaseSchema = """" +outputFolder <- file.path(studyFolder, databaseId) +cohortDatabaseSchema <- ""scratch.dbo"" +cohortTable <- """" + +# CCAE settings ---------------------------------------------------------------- +databaseId <- ""CCAE"" +databaseName <- ""CCAE"" +databaseDescription <- ""CCAE"" +cdmDatabaseSchema <- """" +outputFolder <- file.path(studyFolder, databaseId) +cohortDatabaseSchema = ""scratch.dbo"" +cohortTable = ""uka_tka_safety_ccae"" + +# Optum DOD settings ----------------------------------------------------------- +databaseId <- ""Optum"" +databaseName <- ""Optum"" +databaseDescription <- ""Optum DOD"" +cdmDatabaseSchema = """" +outputFolder <- file.path(studyFolder, databaseId) +cohortDatabaseSchema <- ""scratch.dbo"" +cohortTable <- ""uka_tka_safety_optum"" + +# THIN settings ---------------------------------------------------------------- +databaseId <- ""thin"" +databaseName <- ""thin"" +databaseDescription <- ""thin"" +cdmDatabaseSchema = """" +outputFolder <- file.path(studyFolder, databaseId) +cohortDatabaseSchema <- """" +cohortTable <- """" + +# Pharmetrics settings --------------------------------------------------------- +databaseId <- ""pmtx"" +databaseName <- ""pmtx"" +databaseDescription <- ""pmtx"" +cdmDatabaseSchema = """" +outputFolder <- file.path(studyFolder, databaseId) +cohortDatabaseSchema <- """" +cohortTable <- """" + +# Run -------------------------------------------------------------------------- +OhdsiRTools::runAndNotify(expression = { + execute(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = NULL, + outputFolder = outputFolder, + databaseId = databaseId, + databaseName = databaseName, + databaseDescription = databaseDescription, + createCohorts = FALSE, + synthesizePositiveControls = FALSE, + runAnalyses = FALSE, + runDiagnostics = FALSE, + packageResults = FALSE, + maxCores = maxCores) +}, mailSettings = mailSettings, label = paste0(""Uka Tka "", databaseId), stopOnWarning = FALSE) + +resultsZipFile <- file.path(outputFolder, ""exportFull"", paste0(""Results"", databaseId, "".zip"")) +dataFolder <- file.path(outputFolder, ""shinyData"") +prepareForEvidenceExplorer(resultsZipFile = resultsZipFile, dataFolder = dataFolder) + +# meta-analysis ---------------------------------------------------------------- +doMetaAnalysis(outputFolders = c(file.path(studyFolder, ""CCAE""), + file.path(studyFolder, ""MDCR""), + file.path(studyFolder, ""Optum""), + file.path(studyFolder, ""thin""), + file.path(studyFolder, ""pmtx"")), + maOutputFolder = file.path(studyFolder, ""MetaAnalysis""), + maxCores = maxCores) +# prepare meta analysis results for shiny -------------------------------------- + +# compile results for Shiny here ----------------------------------------------- +compileShinyData(studyFolder = studyFolder, + databases = c(""CCAE"", ""MDCR"", ""Optum"", ""thin"", ""pmtx"")) + +fullShinyDataFolder <- file.path(studyFolder, ""shinyDataAll"") +launchEvidenceExplorer(dataFolder = fullShinyDataFolder, blind = FALSE, launch.browser = FALSE) + +# Plots and tables for manuscript ---------------------------------------------- +createPlotsAndTables(studyFolder = studyFolder, + createTable1 = TRUE, + createHrTable = TRUE, + createForestPlot = TRUE, + createKmPlot = TRUE, + createDiagnosticsPlot = TRUE) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","UkaTkaSafetyEffectiveness/extras/prepareMetaForEvidenceExplorer.R",".R","1603","24","# AUTOMATE ALL BELOW WITH A PREPARE FUNCTION ------------------------------------------------------ +# moved outcome_of_interest_DB -> outcome_of_interest_Meta-analysis.rds +# moved exposure_of_interest_DB -> exposure_of_interest_Meta-analysis.rds +# moved and altered database_D.rds -> database_Meta-analysis.rds +database <- data.frame(database_id = ""Meta-analysis"", + database_name = ""Meta-analysis"", + description = ""Meta-analysis"", + is_meta_analysis = 1) +fileName <- file.path(""D:/jweave17/UkaTkaSafetyFullMetaAnalysis/results/shinyData"", ""database_Meta-analysis.rds"") +saveRDS(database, fileName) +# moved cohort_method_analysis_DB.rds -> cohort_method_analysis_Meta-analysis.rds +# moved negative/positive control outcome rds files +#files from export seem to have fewer than full negative controls +pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""UkaTkaSafetyFull"") +negativeControls <- read.csv(pathToCsv) +negativeControls <- negativeControls[tolower(negativeControls$type) == ""outcome"", ] +negativeControls <- negativeControls[, c(""outcomeId"", ""outcomeName"")] +colnames(negativeControls) <- SqlRender::camelCaseToSnakeCase(colnames(negativeControls)) +saveRDS(negativeControls, ""D:/jweave17/UkaTkaSafetyFullMetaAnalysis/results/shinyData/negative_control_outcome_Meta-analysis.rds"") + +dataFolder <- ""D:/jweave17/UkaTkaSafetyFullMetaAnalysis/results/shinyData"" +dataFolder <- ""S:/StudyResults/UkaTkaSafetyFull/metaAnalysis/shinyData"" +launchEvidenceExplorer(dataFolder = dataFolder, blind = FALSE, launch.browser = FALSE) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","PGxDrugStudy/R/SkeletonStudy-package.r",".r","90","6","#' @docType package +#' @import DBI +#' @import SqlRender +#' @import DatabaseConnector +NULL +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","PGxDrugStudy/R/TestCode.R",".R","314","15","#' @keywords internal +test <- function() { + + dbms <- ""postgresql"" + server <- Sys.getenv(""CDM4HOST"") + user <- ""ohdsi"" + password <- Sys.getenv(""CDM4PASSWORD"") + cdmSchema <- ""cdm4_sim"" + port <- NULL + + result <- execute(dbms, user, password, server, port, cdmSchema) + + result +} + ","R" +"Pharmacogenetics","OHDSI/StudyProtocols","PGxDrugStudy/R/StudyInvariant.R",".R","4791","156","#' @title Load OHSDI study +#' +#' @details +#' This function loads an OHDSI study results from disk file. +#' +#' @param file (Optional) Name of local file to place results; makre sure to use forward slashes (/) +#' @param verbose Logical: print R object names that are loaded +#' +#' @return +#' A list of class type \code{OhsiStudy} that contains all saved study objects +#' +#' @export +loadOhdsiStudy <- function(file, + verbose = FALSE) { + + if (missing(file)) file <- getDefaultStudyFileName() + + # Return list of results + tmp <- new.env() + load(file, envir = tmp, verbose = verbose) + result <- mget(ls(tmp), envir = tmp) + class(result) <- ""OhdsiStudy"" + return (result) +} + +#' @title Save OHDSI study +#' +#' @details +#' This function saves an OHDSI study to disk file. All objects are written using \code{\link{save}} +#' format and can be read back from file at a later time by using the function \code{\link{loadOhdsiStudy}}. +#' +#' @param list A list of R objects to save to disk file. +#' @param file (Optional) Name of local file to place results; makre sure to use forward slashes (/) +#' @param compress Logical or character string specifying the use of compression. See \code{\link{save}} +#' @param includeMetadata Logical: include metadata about user and system in saved file +#' +#' @export +saveOhdsiStudy <- function(list, + file, + compress = TRUE, + includeMetadata = TRUE) { + + if (missing(list)) { + stop(""Must provide object list to save"") + } + + if (missing(file)) file <- getDefaultStudyFileName() + + if (includeMetadata) { + metadata <- list() + + metadata$r.version <- R.Version()$version.string + info <- Sys.info() + metadata$sysname <- info[[""sysname""]] + metadata$user <- info[[""user""]] + metadata$nodename <- info[[""nodename""]] + metadata$time <- Sys.time() + assign(""metadata"", metadata, envir = parent.frame()) # place in same environment as named objects + list <- c(list, ""metadata"") + } + + save(list = list, + file = file, + envir = parent.frame(1), + compress = compress) +} + +#' @keywords internal +invokeSql <- function(fileName, dbms, conn, text, cdmVersion, use.ffdf = FALSE, quiet = TRUE) { + + if (cdmVersion != 4 && cdmVersion != 5) { + stop(paste(""Invalid CDM version:"", cdmVersion)) + } + + parameterizedSql <- SqlRender::readSql(system.file(paste(""sql/"",""sql_server"", sep = """"), + fileName, + package=""PGxDrugStudy"")) + renderedSql <- SqlRender::renderSql(parameterizedSql, + cdmVersion = cdmVersion)$sql + translatedSql <- SqlRender::translateSql(renderedSql, + sourceDialect = ""sql server"", + targetDialect = dbms)$sql + writeLines(text) + + if (quiet) { + ops <- options(warn = -1) + on.exit(options(ops)) + } + + if (use.ffdf) { + return(DatabaseConnector::querySql.ffdf(conn, translatedSql)) + } else { + return(DatabaseConnector::querySql(conn, translatedSql)) + } +} + +#' @title Email results +#' +#' @details +#' This function emails the result CSV files to the study coordinator. +#' +#' @return +#' A list of files that were emailed. +#' +#' @param from Return email address +#' @param to (Optional) Delivery email address (must be a gmail.com acccount) +#' @param subject (Optional) Subject line of email +#' @param dataDescription A short description of the database +#' @param file (Optional) Name of local file with results; makee sure to use forward slashes (/) +#' +#' @export +email <- function(from, + to, + subject, + dataDescription, + file) { + + if (missing(from)) stop(""Must provide return address"") + if (missing(dataDescription)) stop(""Must provide a data description"") + + if (missing(to)) to <- getDestinationAddress() + if (missing(subject)) subject <- getDefaultStudyEmailSubject() + if (missing(file)) file <- getDefaultStudyFileName() + + if(!file.exists(file)) stop(paste(c(""No results file named '"",file,""' exists""),sep = """")) + + tryCatch({ + result <- mailR::send.mail(from = from, + to = to, + subject = subject, + body = paste(""\n"", dataDescription, ""\n"", + sep = """"), + smtp = list(host.name = ""aspmx.l.google.com"", + port = 25), + attach.files = file, + authenticate = FALSE, + send = TRUE) + if (result$isSendPartial()) { + stop(""Unknown error in sending email"") + } else { + writeLines(c( + ""Sucessfully emailed the following file:"", + paste(""\t"", file, sep = """"), + paste(""to:"", to) + )) + } + }, error = function(e) { + writeLines(c( + ""Error in automatically emailing results, most likely due to security settings."", + ""Please manually email the following file:"", + paste(""\t"", file, sep = """"), + paste(""to:"", to) + )) + }) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","PGxDrugStudy/R/StudySpecific.R",".R","8958","187","#' @title Execute OHDSI Study PGxDrugStudy +#' +#' @details +#' This function executes OHDSI Study ""Incidence of exposure to drugs for which pre-emptive pharmacogenomic testing is available"" (PGxDrugStudy). +#' This is a study to derive data that large healthcare organizations can combine with data on risks of adverse events and cost data to conduct cost-effectiveness / cost-benefit analyses for pre-emptive pharmacogenomics testing. +#' Detailed information and protocol are available on the OHDSI Wiki (http://www.ohdsi.org/web/wiki/doku.php?id=research:pgx_drug_exposure). +#' +#' @return +#' Study results are placed in CSV format files in specified local folder and returned +#' as an R object class \code{OhdsiStudy} when sufficiently small. The properties of an +#' \code{OhdsiStudy} may differ from study to study. + +#' @param dbms The type of DBMS running on the server. Valid values are +#' \itemize{ +#' \item{""mysql"" for MySQL} +#' \item{""oracle"" for Oracle} +#' \item{""postgresql"" for PostgreSQL} +#' \item{""redshift"" for Amazon Redshift} +#' \item{""sql server"" for Microsoft SQL Server} +#' \item{""pdw"" for Microsoft Parallel Data Warehouse (PDW)} +#' \item{""netezza"" for IBM Netezza} +#' } +#' @param user The user name used to access the server. If the user is not specified for SQL Server, +#' Windows Integrated Security will be used, which requires the SQL Server JDBC drivers +#' to be installed. +#' @param domain (optional) The Windows domain for SQL Server only. +#' @param password The password for that user +#' @param server The name of the server +#' @param port (optional) The port on the server to connect to +#' @param cdmSchema Schema name where your patient-level data in OMOP CDM format resides +#' @param cdmVersion Define the OMOP CDM version used: currently support 4 and 5. Default = 4 +#' @param file (Optional) Name of local file to place results; make sure to use forward slashes (/) +#' +#' @examples \dontrun{ +#' # Run study +#' execute(dbms = ""postgresql"", +#' user = ""joebruin"", +#' password = ""supersecret"", +#' server = ""myserver"", +#' cdmSchema = ""cdm_schema"", +#' cdmVersion = 5) +#' +#' # Email result file +#' email(from = ""collaborator@@ohdsi.org"", +#' dataDescription = ""CDM4 Simulated Data"") +#' } +#' +#' @importFrom DBI dbDisconnect +#' @export +execute <- function(dbms, user = NULL, domain = NULL, password = NULL, server, + port = NULL, + cdmSchema, cdmVersion = 4, + file) { + # Open DB connection + connectionDetails <- DatabaseConnector::createConnectionDetails(dbms=dbms, + server=server, + user=user, + domain=domain, + password=password, + schema=cdmSchema, + port = port) + conn <- DatabaseConnector::connect(connectionDetails) + if (is.null(conn)) { + stop(""Failed to connect to db server."") + } + + # Record start time + start <- Sys.time() + + # Count gender + gender0to13 <- invokeSql(""CountGender0to13.sql"", dbms, conn, ""Executing gender count 0 to 13 ..."", cdmVersion) + gender14to39 <- invokeSql(""CountGender14to39.sql"", dbms, conn, ""Executing gender count 14 to 39 ..."", cdmVersion) + gender40to64 <- invokeSql(""CountGender40to64.sql"", dbms, conn, ""Executing gender count 40 to 64 ..."", cdmVersion) + gender65Plus <- invokeSql(""CountGender65Plus.sql"", dbms, conn, ""Executing gender count 65 plus ..."", cdmVersion) + + # Get frequencies + frequencies0to13 <- invokeSql(""GetFrequencies0to13.sql"", dbms, conn, ""Executing frequency count 0 to 13 ..."", cdmVersion) + frequencies14to39 <- invokeSql(""GetFrequencies14to39.sql"", dbms, conn, ""Executing frequency count 14 to 39 ..."", cdmVersion) + frequencies40to64 <- invokeSql(""GetFrequencies40to64.sql"", dbms, conn, ""Executing frequency count 40 to 64 ..."", cdmVersion) + frequencies65Plus <- invokeSql(""GetFrequencies65Plus.sql"", dbms, conn, ""Executing frequency count 65+ ..."", cdmVersion) + + # Age by exposure + ageAtExposureAllPgx0to13 <- invokeSql(""AgeAtExposureAllPgx0to13.sql"", dbms, conn, ""Executing age by exposure ALL pgx count 0 to 13 ..."", cdmVersion) + ageAtExposureAllPgx14to39 <- invokeSql(""AgeAtExposureAllPgx14to39.sql"", dbms, conn, ""Executing age by exposure ALL pgx count 14 to 39 ..."", cdmVersion) + ageAtExposureAllPgx40to64 <- invokeSql(""AgeAtExposureAllPgx40to64.sql"", dbms, conn, ""Executing age by exposure ALL pgx count 40 to 64 ..."", cdmVersion) + ageAtExposureAllPgx65Plus <- invokeSql(""AgeAtExposureAllPgx65Plus.sql"", dbms, conn, ""Executing age by exposure ALL pgx count 65+ ..."", cdmVersion) + + ageAtExposureCorePgx0to13 <- invokeSql(""AgeAtExposureCorePgx0to13.sql"", dbms, conn, ""Executing age by exposure CORE pgx count 0 to 13 ..."", cdmVersion) + ageAtExposureCorePgx14to39 <- invokeSql(""AgeAtExposureCorePgx14to39.sql"", dbms, conn, ""Executing age by exposure CORE pgx count 14 to 39 ..."", cdmVersion) + ageAtExposureCorePgx40to64 <- invokeSql(""AgeAtExposureCorePgx40to64.sql"", dbms, conn, ""Executing age by exposure CORE pgx count 40 to 64 ..."", cdmVersion) + ageAtExposureCorePgx65Plus <- invokeSql(""AgeAtExposureCorePgx65Plus.sql"", dbms, conn, ""Executing age by exposure CORE pgx count 65+ ..."", cdmVersion) + + # Count people + # TODO: should consider a loop instead of code-duplication + tmp <- invokeSql(""CountPerson0to13.sql"", dbms, conn, text =""Executing person count 0 to 13 ..."", cdmVersion, use.ffdf = TRUE) # Cache to disk in case table is large + person0to13 <- list() + person0to13$count <- length(tmp[,1]) + if (length(tmp[,1]) > 0) { + person0to13$min <- min(tmp[,1]) + person0to13$median <- median(tmp[,1]) + person0to13$max <- max(tmp[,1]) + } + rm(tmp) # discard potentially large file + + tmp <- invokeSql(""CountPerson14to39.sql"", dbms, conn, text =""Executing person count 14 to 39 ..."", cdmVersion, use.ffdf = TRUE) # Cache to disk in case table is large + person14to39 <- list() + person14to39$count <- length(tmp[,1]) + if (length(tmp[,1]) > 0) { + person14to39$min <- min(tmp[,1]) + person14to39$median <- median(tmp[,1]) + person14to39$max <- max(tmp[,1]) + } + rm(tmp) # discard potentially large file + + tmp <- invokeSql(""CountPerson40to64.sql"", dbms, conn, text =""Executing person count 40 to 64 ..."", cdmVersion, use.ffdf = TRUE) # Cache to disk in case table is large + person40to64 <- list() + person40to64$count <- length(tmp[,1]) + if (length(tmp[,1]) > 0) { + person40to64$min <- min(tmp[,1]) + person40to64$median <- median(tmp[,1]) + person40to64$max <- max(tmp[,1]) + } + rm(tmp) # discard potentially large file + + tmp <- invokeSql(""CountPerson65Plus.sql"", dbms, conn, text =""Executing person count 65+ ..."", cdmVersion, use.ffdf = TRUE) # Cache to disk in case table is large + person65Plus <- list() + person65Plus$count <- length(tmp[,1]) + if (length(tmp[,1]) > 0) { + person65Plus$min <- min(tmp[,1]) + person65Plus$median <- median(tmp[,1]) + person65Plus$max <- max(tmp[,1]) + } + rm(tmp) # discard potentially large file + + # Execution duration + executionTime <- Sys.time() - start + + # List of R objects to save + objectsToSave <- c( + ""gender0to13"", + ""gender14to39"", + ""gender40to64"", + ""gender65Plus"", + ""frequencies0to13"", + ""frequencies14to39"", + ""frequencies40to64"", + ""frequencies65Plus"", + ""ageAtExposureAllPgx0to13"", + ""ageAtExposureAllPgx14to39"", + ""ageAtExposureAllPgx40to64"", + ""ageAtExposureAllPgx65Plus"", + ""ageAtExposureCorePgx0to13"", + ""ageAtExposureCorePgx14to39"", + ""ageAtExposureCorePgx40to64"", + ""ageAtExposureCorePgx65Plus"", + ""person0to13"", + ""person14to39"", + ""person40to64"", + ""person65Plus"", + ""executionTime"" + ) + + # Save results to disk + if (missing(file)) file <- getDefaultStudyFileName() + saveOhdsiStudy(list = objectsToSave, file = file) + + # Clean up + DBI::dbDisconnect(conn) + + # Package and return result if return value is used + result <- mget(objectsToSave) + class(result) <- ""OhdsiStudy"" + invisible(result) +} + +# Package must provide a default gmail address to receive result files +#' @keywords internal +getDestinationAddress <- function() { return(""codehop.dev@gmail.com"") } + +# Package must provide a default result file name +#' @keywords internal +getDefaultStudyFileName <- function() { return(""PGxStudy.rda"") } + +# Packge must provide default email subject +#' @keywords internal +getDefaultStudyEmailSubject <- function() { return(""OHDSI PGxDrugStudy Results"") } +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","PGxDrugStudy/tests/testthat.R",".R","71","3","library(testthat) +test_check(""SkeletonStudy"") # Change to package name +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","PGxDrugStudy/tests/testthat/test-nullDatabase.R",".R","1635","47","library(testthat) + +test_that(""Fail to connect"", { + + expect_error(execute(dbms = """", + user = """", + password = """", + server = """", + cdmSchema = """", + resultsScheme = """"), regexp = ""Failed to connect"") +}) + +# test_that(""Execute against empty OMOP CDM databases"", { +# +# executeResultSize <- 2 # Set to count of objects generated in execute() +# +# result1 <- execute(dbms = ""postgresql"", +# server=""jenkins.ohdsi.org/sandbox"", +# user = ""patrick"", +# password = ""gh_56Fd8L"", +# port = 5432, +# cdmSchema = ""CDMV5"", +# resultsScheme = ""patrick"") +# +# expect_equal(length(result1),executeResultSize) +# +# result2 <- execute(dbms = ""sql server"", +# server=""jenkins.ohdsi.org"", +# user = ""patrick"", +# password = ""gh_56Fd8L"", +# port = 1433, +# cdmSchema = ""CDMV5"", +# resultsScheme = ""patrick"") +# +# expect_equal(length(result2),executeResultSize) +# +# result3 <- execute(dbms = ""oracle"", +# server=""jenkins.ohdsi.org/XE"", +# user = ""patrick"", +# password = ""gh_56Fd8L"", +# #port = 1521, +# cdmSchema = ""CDMV5"", +# resultsScheme = ""patrick"") +# +# expect_equal(length(result3),executeResultSize) +# }) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AhasHfBkleAmputation/R/CountCohorts.R",".R","1704","35","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of AhasHfBkleAmputation +# +# 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. + +countCohorts <- function(connection, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable = ""cohort"", + oracleTempSchema, + outputFolder) { + sql <- SqlRender::loadRenderTranslateSql(""GetCounts.sql"", + ""AhasHfBkleAmputation"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + work_database_schema = cohortDatabaseSchema, + study_cohort_table = cohortTable) + counts <- DatabaseConnector::querySql(connection, sql) + colnames(counts) <- SqlRender::snakeCaseToCamelCase(colnames(counts)) + counts <- addCohortNames(counts) + write.csv(counts, file.path(outputFolder, ""CohortCounts.csv""), row.names = FALSE) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AhasHfBkleAmputation/R/Main.R",".R","7779","146","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of AhasHfBkleAmputation +# +# 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. + +#' Execute AhasHfBkleAmputation Study +#' +#' @details +#' This function executes the AhasHfBkleAmputation Study. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param cohortDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param cohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/). Do not use a folder on a network drive since this greatly impacts +#' performance. +#' @param createCohorts Create the cohortTable table with the exposure and outcome cohorts? +#' @param runAnalyses Perform the cohort method analyses? +#' @param getPriorExposureData Get data on prior exposure to AHAs? +#' @param runDiagnostics Should study diagnostics be generated? +#' @param prepareResults Prepare results for analysis? +#' @param maxCores How many parallel cores should be used? If more cores are made available +#' this can speed up the analyses. +#' +#' @examples +#' \dontrun{ +#' connectionDetails <- createConnectionDetails(dbms = ""postgresql"", +#' user = ""joe"", +#' password = ""secret"", +#' server = ""myserver"") +#' +#' execute(connectionDetails, +#' cdmDatabaseSchema = ""cdm_data"", +#' cohortDatabaseSchema = ""results"", +#' cohortTable = ""cohort"", +#' oracleTempSchema = NULL, +#' outputFolder = ""c:/temp/study_results"", +#' maxCores = 4) +#' } +#' +#' @export +execute <- function(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema = cdmDatabaseSchema, + cohortTable = ""cohort"", + oracleTempSchema = cohortDatabaseSchema, + outputFolder, + databaseName, + createCohorts = TRUE, + runAnalyses = TRUE, + getPriorExposureData = TRUE, + runDiagnostics = TRUE, + prepareResults = TRUE, + maxCores = 4) { + if (!file.exists(outputFolder)) + dir.create(outputFolder, recursive = TRUE) + + OhdsiRTools::addDefaultFileLogger(file.path(outputFolder, ""log.txt"")) + + if (createCohorts) { + OhdsiRTools::logInfo(""Creating exposure and outcome cohorts"") + createCohorts(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder) + } + + if (runAnalyses) { + OhdsiRTools::logInfo(""Running analyses"") + cmOutputFolder <- file.path(outputFolder, ""cmOutput"") + if (!file.exists(cmOutputFolder)) + dir.create(cmOutputFolder) + cmAnalysisListFile <- system.file(""settings"", + ""cmAnalysisList.json"", + package = ""AhasHfBkleAmputation"") + cmAnalysisList <- CohortMethod::loadCmAnalysisList(cmAnalysisListFile) + cmAnalysisList <- setOutcomeDatabaseSchemaAndTable(cmAnalysisList, cohortDatabaseSchema, cohortTable) + dcosList <- createTcos(outputFolder = outputFolder) + results <- CohortMethod::runCmAnalyses(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + exposureDatabaseSchema = cohortDatabaseSchema, + exposureTable = cohortTable, + outcomeDatabaseSchema = cohortDatabaseSchema, + outcomeTable = cohortTable, + outputFolder = cmOutputFolder, + oracleTempSchema = oracleTempSchema, + cmAnalysisList = cmAnalysisList, + drugComparatorOutcomesList = dcosList, + getDbCohortMethodDataThreads = min(3, maxCores), + createStudyPopThreads = min(3, maxCores), + createPsThreads = max(1, round(maxCores/10)), + psCvThreads = min(10, maxCores), + computeCovarBalThreads = min(3, maxCores), + trimMatchStratifyThreads = min(10, maxCores), + fitOutcomeModelThreads = max(1, round(maxCores/4)), + outcomeCvThreads = min(4, maxCores), + refitPsForEveryOutcome = FALSE, + refitPsForEveryStudyPopulation = FALSE, + outcomeIdsOfInterest = c(5432, 5433)) + } + if (getPriorExposureData) { + OhdsiRTools::logInfo(""Getting prior AHA exposure data from server"") + getPriorAhaExposureData(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder) + } + if (runDiagnostics) { + OhdsiRTools::logInfo(""Running diagnostics"") + generateDiagnostics(outputFolder = outputFolder) + } + if (prepareResults) { + OhdsiRTools::logInfo(""Preparing results for analysis"") + prepareResultsForAnalysis(outputFolder = outputFolder, + databaseName = databaseName, + maxCores = maxCores) + } + invisible(NULL) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AhasHfBkleAmputation/R/PriorOutcomeCovariateBuilder.R",".R","6175","122","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of AhasHfBkleAmputation +# +# 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. + + +#' Create settings for adding prior outcomes as covariates +#' +#' @param outcomeDatabaseSchema The name of the database schema that is the location +#' where the data used to define the outcome cohorts is +#' available. +#' @param outcomeTable The tablename that contains the outcome cohorts. +#' @param outcomeIds A vector of cohort_definition_ids used to define outcomes +#' @param outcomeNames A vector of names of the outcomes, to be used to create +#' covariate names. +#' @param windowStart Start day of the window where covariates are captured, +#' relative to the index date (0 = index date). +#' @param windowEnd End day of the window where covariates are captured, +#' relative to the index date (0 = index date). +#' +#' @return +#' A covariateSettings object. +#' +#' @export +createPriorOutcomesCovariateSettings <- function(outcomeDatabaseSchema = ""unknown"", + outcomeTable = ""unknown"", + outcomeIds, + outcomeNames, + windowStart = -365, + windowEnd = -1) { + covariateSettings <- list(outcomeDatabaseSchema = outcomeDatabaseSchema, + outcomeTable = outcomeTable, + outcomeIds = outcomeIds, + outcomeNames = outcomeNames, + windowStart = windowStart, + windowEnd = windowEnd) + attr(covariateSettings, ""fun"") <- ""AhasHfBkleAmputation::getDbPriorOutcomesCovariateData"" + class(covariateSettings) <- ""covariateSettings"" + return(covariateSettings) +} + +#' @export +getDbPriorOutcomesCovariateData <- function(connection, + oracleTempSchema = NULL, + cdmDatabaseSchema, + cohortTable = ""#cohort_person"", + cohortId = -1, + cdmVersion = ""5"", + rowIdField = ""subject_id"", + covariateSettings, + aggregated = FALSE) { + if (aggregated) + stop(""Aggregation not supported"") + writeLines(""Creating covariates based on prior outcomes"") + sql <- SqlRender::loadRenderTranslateSql(""getPriorOutcomeCovariates.sql"", + packageName = ""AhasHfBkleAmputation"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + window_start = covariateSettings$windowStart, + window_end = covariateSettings$windowEnd, + row_id_field = rowIdField, + cohort_temp_table = cohortTable, + cohort_id = cohortId, + outcome_database_schema = covariateSettings$outcomeDatabaseSchema, + outcome_table = covariateSettings$outcomeTable, + outcome_ids = covariateSettings$outcomeIds) + covariates <- DatabaseConnector::querySql.ffdf(connection, sql) + colnames(covariates) <- SqlRender::snakeCaseToCamelCase(colnames(covariates)) + covariateRef <- data.frame(covariateId = covariateSettings$outcomeIds * 1000 + 999, + covariateName = paste(""Prior outcome:"", covariateSettings$outcomeNames), + analysisId = 999, + conceptId = 0) + covariateRef <- ff::as.ffdf(covariateRef) + + # Construct analysis reference: + analysisRef <- data.frame(analysisId = as.numeric(1), + analysisName = ""Prior outcome"", + domainId = ""Cohort"", + startDay = as.numeric(covariateSettings$windowStart), + endDay = as.numeric(covariateSettings$windowEnd), + isBinary = ""Y"", + missingMeansZero = ""Y"") + analysisRef <- ff::as.ffdf(analysisRef) + # Construct analysis reference: + metaData <- list(sql = sql, call = match.call()) + result <- list(covariates = covariates, + covariateRef = covariateRef, + analysisRef = analysisRef, + metaData = metaData) + class(result) <- ""covariateData"" + return(result) +} + +#' @export +setOutcomeDatabaseSchemaAndTable <-function(settings, outcomeDatabaseSchema, outcomeTable) { + if (class(settings) == ""covariateSettings"") { + if (!is.null(settings$outcomeDatabaseSchema)) { + settings$outcomeDatabaseSchema <- outcomeDatabaseSchema + settings$outcomeTable <- outcomeTable + } + } else { + if (is.list(settings) && length(settings) != 0) { + for (i in 1:length(settings)) { + if (is.list(settings[[i]])) { + settings[[i]] <- setOutcomeDatabaseSchemaAndTable(settings[[i]], outcomeDatabaseSchema, outcomeTable) + } + } + } + } + return(settings) +}","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AhasHfBkleAmputation/R/GetPriorAhaExposureData.R",".R","4395","76","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of AhasHfBkleAmputation +# +# 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. + +#' Get data on prior exposure to AHAs. +#' +#' @details +#' Downloads data on prior exposure to anti-hyperglycemic agents for the cohorts of interest. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param cohortDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param cohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' +#' @export +getPriorAhaExposureData <- function(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable = ""cohort"", + oracleTempSchema, + outputFolder) { + if (!file.exists(outputFolder)) + dir.create(outputFolder, recursive = TRUE) + + conn <- DatabaseConnector::connect(connectionDetails) + + pathToCsv <- system.file(""settings"", ""TcosOfInterest.csv"", package = ""AhasHfBkleAmputation"") + tcosOfInterest <- read.csv(pathToCsv, stringsAsFactors = FALSE) + sql <- SqlRender::loadRenderTranslateSql(""PriorAhaExposureCovariates.sql"", + ""AhasHfBkleAmputation"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + cohort_database_schema = cohortDatabaseSchema, + cohort_table = cohortTable, + cohort_ids = unique(c(tcosOfInterest$targetId, + tcosOfInterest$comparatorId))) + covariates <- DatabaseConnector::querySql.ffdf(conn, sql) + colnames(covariates) <- SqlRender::snakeCaseToCamelCase(colnames(covariates)) + + sql <- SqlRender::loadRenderTranslateSql(""PriorAhaExposureCovariateRef.sql"", + ""AhasHfBkleAmputation"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema) + covariateRef <- DatabaseConnector::querySql.ffdf(conn, sql) + colnames(covariateRef) <- SqlRender::snakeCaseToCamelCase(colnames(covariateRef)) + + DatabaseConnector::disconnect(conn) + + ffbase::save.ffdf(covariates, covariateRef, dir = file.path(outputFolder, ""priorAhaExposures"")) +}","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AhasHfBkleAmputation/R/CreateCohorts.R",".R","3564","69","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of AhasHfBkleAmputation +# +# 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. + +.createCohorts <- function(connection, + cdmDatabaseSchema, + vocabularyDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable, + oracleTempSchema, + outputFolder) { + + # Create study cohort table structure: + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""CreateCohortTable.sql"", + packageName = ""AhasHfBkleAmputation"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + cohort_database_schema = cohortDatabaseSchema, + cohort_table = cohortTable) + DatabaseConnector::executeSql(connection, sql, progressBar = FALSE, reportOverallTime = FALSE) + + + + # Instantiate cohorts: + pathToCsv <- system.file(""settings"", ""CohortsToCreate.csv"", package = ""AhasHfBkleAmputation"") + cohortsToCreate <- read.csv(pathToCsv) + for (i in 1:nrow(cohortsToCreate)) { + writeLines(paste(""Creating cohort:"", cohortsToCreate$name[i])) + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = paste0(cohortsToCreate$name[i], "".sql""), + packageName = ""AhasHfBkleAmputation"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + vocabulary_database_schema = vocabularyDatabaseSchema, + + target_database_schema = cohortDatabaseSchema, + target_cohort_table = cohortTable, + target_cohort_id = cohortsToCreate$cohortId[i]) + DatabaseConnector::executeSql(connection, sql) + } + + # Fetch cohort counts: + sql <- ""SELECT cohort_definition_id, COUNT(*) AS count FROM @cohort_database_schema.@cohort_table GROUP BY cohort_definition_id"" + sql <- SqlRender::renderSql(sql, + cohort_database_schema = cohortDatabaseSchema, + cohort_table = cohortTable)$sql + sql <- SqlRender::translateSql(sql, targetDialect = attr(connection, ""dbms""))$sql + counts <- DatabaseConnector::querySql(connection, sql) + names(counts) <- SqlRender::snakeCaseToCamelCase(names(counts)) + counts <- merge(counts, data.frame(cohortDefinitionId = cohortsToCreate$cohortId, + cohortName = cohortsToCreate$name)) + write.csv(counts, file.path(outputFolder, ""CohortCounts.csv"")) + + +} + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AhasHfBkleAmputation/R/PrepareResultsForAnalysis.R",".R","15188","279","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of AhasHfBkleAmputation +# +# 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. + +#' Prepare results for analysis +#' +#' @details +#' This function generates analyses results, and prepares data for the Shiny app. Requires the study to be executed first. +#' +#' @param outputFolder Name of local folder where the results were generated; make sure to use forward slashes +#' (/). Do not use a folder on a network drive since this greatly impacts +#' performance. +#' @param databaseName A unique name for the database. +#' @param maxCores How many parallel cores should be used? If more cores are made available +#' this can speed up the analyses. +#' +#' @export +prepareResultsForAnalysis <- function(outputFolder, databaseName, maxCores) { + packageName <- ""AhasHfBkleAmputation"" + cmOutputFolder <- file.path(outputFolder, ""cmOutput"") + + resultsFolder <- file.path(outputFolder, ""results"") + if (!file.exists(resultsFolder)) + dir.create(resultsFolder) + shinyDataFolder <- file.path(resultsFolder, ""shinyData"") + if (!file.exists(shinyDataFolder)) + dir.create(shinyDataFolder) + balanceDataFolder <- file.path(resultsFolder, ""balance"") + if (!file.exists(balanceDataFolder)) + dir.create(balanceDataFolder) + + pathToCsv <- system.file(""settings"", ""TcosOfInterest.csv"", package = packageName) + tcosOfInterest <- read.csv(pathToCsv, stringsAsFactors = FALSE) + pathToCsv <- system.file(""settings"", ""Analyses.csv"", package = packageName) + analyses <- read.csv(pathToCsv, stringsAsFactors = FALSE) + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = packageName) + negativeControls <- read.csv(pathToCsv, stringsAsFactors = FALSE) + + reference <- readRDS(file.path(cmOutputFolder, ""outcomeModelReference.rds"")) + reference$cohortMethodDataFolder <- gsub(""^[a-z]:/"", ""r:/"", reference$cohortMethodDataFolder) + reference$studyPopFile <- gsub(""^[a-z]:/"", ""r:/"", reference$studyPopFile) + reference$sharedPsFile <- gsub(""^[a-z]:/"", ""r:/"", reference$sharedPsFile) + reference$psFile <- gsub(""^[a-z]:/"", ""r:/"", reference$psFile) + reference$strataFile <- gsub(""^[a-z]:/"", ""r:/"", reference$strataFile) + reference$outcomeModelFile <- gsub(""^[a-z]:/"", ""r:/"", reference$outcomeModelFile) + + analysisSummary <- CohortMethod::summarizeAnalyses(reference) + # saveRDS(analysisSummary, ""analysisSummary.rds"") + # analysisSummary <- readRDS(""analysisSummary.rds"") + analysisSummary <- merge(analysisSummary, analyses) + subset <- tcosOfInterest + subset$excludedCovariateConceptIds <- NULL + subset$outcomeIds <- NULL + subset$outcomeNames <- NULL + analysisSummary <- merge(analysisSummary, subset) + analysisSummary <- merge(analysisSummary, negativeControls[, c(""outcomeId"", ""outcomeName"")], all.x = TRUE) + analysisSummary$type <- ""Outcome of interest"" + analysisSummary$type[analysisSummary$outcomeId %in% negativeControls$outcomeId] <- ""Negative control"" + analysisSummary$database <- databaseName + + # Present analyses without censoring at switch as another time-at-risk + analysisSummary$timeAtRisk[!analysisSummary$censorAtSwitch] <- paste(analysisSummary$timeAtRisk[!analysisSummary$censorAtSwitch], ""(no censor at switch)"") + analysisSummary <- analysisSummary[!(analysisSummary$timeAtRisk %in% c(""Intent to Treat (no censor at switch)"", + ""Modified ITT (no censor at switch)"")), ] + analysisSummary$censorAtSwitch <- NULL + # chunk <- analysisSummary[analysisSummary$targetId == 5357 & analysisSummary$comparatorId == 5363, ] + runTc <- function(chunk, tcosOfInterest, negativeControls, shinyDataFolder, balanceDataFolder, outputFolder, databaseName, reference) { + ffbase::load.ffdf(file.path(outputFolder, ""priorAhaExposures"")) + targetId <- chunk$targetId[1] + comparatorId <- chunk$comparatorId[1] + OhdsiRTools::logTrace(""Preparing results for target ID "", targetId, "", comparator ID"", comparatorId) + idx <- which(tcosOfInterest$targetId == targetId & tcosOfInterest$comparatorId == comparatorId)[1] + outcomeIds <- as.character(tcosOfInterest$outcomeIds[idx]) + outcomeIds <- as.numeric(strsplit(outcomeIds, split = "";"")[[1]]) + outcomeNames <- as.character(tcosOfInterest$outcomeNames[idx]) + outcomeNames <- strsplit(outcomeNames, split = "";"")[[1]] + for (analysisId in unique(reference$analysisId)) { + OhdsiRTools::logTrace(""Analysis ID "", analysisId) + negControlSubset <- chunk[chunk$targetId == targetId & + chunk$comparatorId == comparatorId & + chunk$outcomeId %in% negativeControls$outcomeId & + chunk$analysisId == analysisId, ] + validNcs <- sum(!is.na(negControlSubset$seLogRr)) + if (validNcs >= 5) { + fileName <- file.path(shinyDataFolder, paste0(""null_a"",analysisId,""_t"",targetId,""_c"",comparatorId,""_"",databaseName,"".rds"")) + if (file.exists(fileName)) { + null <- readRDS(fileName) + } else { + null <- EmpiricalCalibration::fitMcmcNull(negControlSubset$logRr, negControlSubset$seLogRr) + saveRDS(null, fileName) + } + idx <- chunk$targetId == targetId & + chunk$comparatorId == comparatorId & + chunk$analysisId == analysisId + calibratedP <- EmpiricalCalibration::calibrateP(null = null, + logRr = chunk$logRr[idx], + seLogRr = chunk$seLogRr[idx]) + chunk$calP[idx] <- calibratedP$p + chunk$calP_lb95ci[idx] <- calibratedP$lb95ci + chunk$calP_ub95ci[idx] <- calibratedP$ub95ci + } + + for (outcomeId in outcomeIds) { + OhdsiRTools::logTrace(""Outcome ID "", outcomeId) + outcomeName <- outcomeNames[outcomeIds == outcomeId] + idx <- chunk$targetId == targetId & + chunk$comparatorId == comparatorId & + chunk$outcomeId == outcomeId & + chunk$analysisId == analysisId + + # Compute MDRR + strataFile <- reference$strataFile[reference$analysisId == analysisId & + reference$targetId == targetId & + reference$comparatorId == comparatorId & + reference$outcomeId == outcomeId] + population <- readRDS(strataFile) + mdrr <- CohortMethod::computeMdrr(population, alpha = 0.05, power = 0.8, twoSided = TRUE, modelType = ""cox"") + chunk$mdrr[idx] <- mdrr$mdrr + chunk$outcomeName[idx] <- outcomeName + + # Compute time-at-risk distribtion stats + distTarget <- quantile(population$timeAtRisk[population$treatment == 1], c(0, 0.1, 0.25, 0.5, 0.75, 0.9, 1)) + distComparator <- quantile(population$timeAtRisk[population$treatment == 0], c(0, 0.1, 0.25, 0.5, 0.75, 0.9, 1)) + chunk$tarTargetMean[idx] <- mean(population$timeAtRisk[population$treatment == 1]) + chunk$tarTargetSd[idx] <- sd(population$timeAtRisk[population$treatment == 1]) + chunk$tarTargetMin[idx] <- distTarget[1] + chunk$tarTargetP10[idx] <- distTarget[2] + chunk$tarTargetP25[idx] <- distTarget[3] + chunk$tarTargetMedian[idx] <- distTarget[4] + chunk$tarTargetP75[idx] <- distTarget[5] + chunk$tarTargetP90[idx] <- distTarget[6] + chunk$tarTargetMax[idx] <- distTarget[7] + chunk$tarComparatorMean[idx] <- mean(population$timeAtRisk[population$treatment == 0]) + chunk$tarComparatorSd[idx] <- sd(population$timeAtRisk[population$treatment == 0]) + chunk$tarComparatorMin[idx] <- distComparator[1] + chunk$tarComparatorP10[idx] <- distComparator[2] + chunk$tarComparatorP25[idx] <- distComparator[3] + chunk$tarComparatorMedian[idx] <- distComparator[4] + chunk$tarComparatorP75[idx] <- distComparator[5] + chunk$tarComparatorP90[idx] <- distComparator[6] + chunk$tarComparatorMax[idx] <- distComparator[7] + + # Compute covariate balance + refRow <- reference[reference$analysisId == analysisId & + reference$targetId == targetId & + reference$comparatorId == comparatorId & + reference$outcomeId == outcomeId, ] + psAfterMatching <- readRDS(refRow$strataFile) + cmData <- CohortMethod::loadCohortMethodData(refRow$cohortMethodDataFolder) + fileName <- file.path(balanceDataFolder, paste0(""bal_a"",analysisId,""_t"",targetId,""_c"",comparatorId,""_o"",outcomeId,""_"",databaseName,"".rds"")) + if (!file.exists(fileName)) { + balance <- CohortMethod::computeCovariateBalance(psAfterMatching, cmData) + saveRDS(balance, fileName) + } + + # Compute balance for prior AHA exposure covariates + fileName <- file.path(shinyDataFolder, paste0(""ahaBal_a"",analysisId,""_t"",targetId,""_c"",comparatorId,""_o"",outcomeId,""_"",databaseName,"".rds"")) + if (!file.exists(fileName)) { + dummyCmData <- cmData + dummyCmData$covariates <- merge(covariates, + ff::as.ffdf(cmData$cohorts[, c(""rowId"", ""subjectId"", ""cohortStartDate"")])) + dummyCmData$covariateRef <- covariateRef + balance <- CohortMethod::computeCovariateBalance(psAfterMatching, dummyCmData) + balance$conceptId <- NULL + balance$beforeMatchingSd <- NULL + balance$afterMatchingSd <- NULL + balance$beforeMatchingSumTreated <- NULL + balance$beforeMatchingSumComparator <- NULL + balance$afterMatchingSumTreated <- NULL + balance$afterMatchingSumComparator <- NULL + if (nrow(balance) > 0) + balance$analysisId <- as.integer(balance$analysisId) + saveRDS(balance, fileName) + } + + # Create KM plot + fileName <- file.path(shinyDataFolder, paste0(""km_a"",analysisId,""_t"",targetId,""_c"",comparatorId,""_o"",outcomeId,""_"",databaseName,"".rds"")) + if (!file.exists(fileName)) { + plot <- CohortMethod::plotKaplanMeier(psAfterMatching) + # plot <- CohortMethod::plotKaplanMeier(psAfterMatching, + # treatmentLabel = chunk$targetDrug[chunk$targetId == targetId][1], + # comparatorLabel = chunk$comparatorDrug[chunk$comparatorId == comparatorId][1]) + saveRDS(plot, fileName) + } + + # Add cohort sizes before matching/stratification + chunk$treatedBefore[idx] <- sum(cmData$cohorts$treatment == 1) + chunk$comparatorBefore[idx] <- sum(cmData$cohorts$treatment == 0) + } + fileName <- file.path(shinyDataFolder, paste0(""ps_a"",analysisId,""_t"",targetId,""_c"",comparatorId,""_"",databaseName,"".rds"")) + if (!file.exists(fileName)) { + exampleRef <- reference[reference$analysisId == analysisId & + reference$targetId == targetId & + reference$comparatorId == comparatorId & + reference$outcomeId == outcomeIds[1], ] + ps <- readRDS(exampleRef$sharedPsFile) + preparedPsPlot <- EvidenceSynthesis::preparePsPlot(ps) + saveRDS(preparedPsPlot, fileName) + } + } + OhdsiRTools::logDebug(""Finished chunk with "", nrow(chunk), "" rows"") + return(chunk) + } + # OhdsiRTools::addDefaultFileLogger(""s:/temp/log.log"") + cluster <- OhdsiRTools::makeCluster(min(maxCores, 10)) + comparison <- paste(analysisSummary$targetId, analysisSummary$comparatorId) + chunks <- split(analysisSummary, comparison) + analysisSummaries <- OhdsiRTools::clusterApply(cluster = cluster, + x = chunks, + fun = runTc, + tcosOfInterest = tcosOfInterest, + negativeControls = negativeControls, + shinyDataFolder = shinyDataFolder, + balanceDataFolder = balanceDataFolder, + outputFolder = outputFolder, + databaseName = databaseName, + reference = reference) + OhdsiRTools::stopCluster(cluster) + analysisSummary <- do.call(rbind, analysisSummaries) + + fileName <- file.path(resultsFolder, paste0(""results_"", databaseName,"".csv"")) + write.csv(analysisSummary, fileName, row.names = FALSE) + + hois <- analysisSummary[analysisSummary$type == ""Outcome of interest"", ] + fileName <- file.path(shinyDataFolder, paste0(""resultsHois_"", databaseName,"".rds"")) + saveRDS(hois, fileName) + + ncs <- analysisSummary[analysisSummary$type == ""Negative control"", c(""targetId"", ""comparatorId"", ""outcomeId"", ""analysisId"", ""database"", ""logRr"", ""seLogRr"")] + fileName <- file.path(shinyDataFolder, paste0(""resultsNcs_"", databaseName,"".rds"")) + saveRDS(ncs, fileName) + + OhdsiRTools::logInfo(""Minimizing balance files for Shiny app"") + allCovarNames <- data.frame() + balanceFiles <- list.files(balanceDataFolder, ""bal.*.rds"") + pb <- txtProgressBar(style = 3) + for (i in 1:length(balanceFiles)) { + fileName <- balanceFiles[i] + balance <- readRDS(file.path(balanceDataFolder, fileName)) + idx <- !(balance$covariateId %in% allCovarNames$covariateId) + if (any(idx)) { + allCovarNames <- rbind(allCovarNames, balance[idx, c(""covariateId"", ""covariateName"")]) + } + balance$covariateName <- NULL + balance$conceptId <- NULL + balance$beforeMatchingSd <- NULL + balance$afterMatchingSd <- NULL + balance$beforeMatchingSumTreated <- NULL + balance$beforeMatchingSumComparator <- NULL + balance$afterMatchingSumTreated <- NULL + balance$afterMatchingSumComparator <- NULL + balance$analysisId <- as.integer(balance$analysisId) + saveRDS(balance, file.path(shinyDataFolder, fileName)) + if (i %% 100 == 0) { + setTxtProgressBar(pb, i/length(balanceFiles)) + } + } + setTxtProgressBar(pb, 1) + close(pb) + fileName <- file.path(shinyDataFolder, paste0(""covarNames_"", databaseName,"".rds"")) + saveRDS(allCovarNames, fileName) +} + +# files <- list.files(shinyDataFolder, ""ahaBal_a.*.rds"", full.names = TRUE) +# targetFiles <- gsub(shinyDataFolder, balanceDataFolder, sourceFiles) +# file.rename(sourceFiles, targetFiles) +# unlink(files) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AhasHfBkleAmputation/R/CreateAllCohorts.R",".R","5759","111","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of AhasHfBkleAmputation +# +# 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. + +#' Create the exposure and outcome cohorts +#' +#' @details +#' This function will create the exposure and outcome cohorts following the definitions included in +#' this package. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param cohortDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param cohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' +#' @export +createCohorts <- function(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable = ""cohort"", + oracleTempSchema, + outputFolder) { + if (!file.exists(outputFolder)) + dir.create(outputFolder, recursive = TRUE) + + conn <- DatabaseConnector::connect(connectionDetails) + + .createCohorts(connection = conn, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder) + + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""AhasHfBkleAmputation"") + negativeControls <- read.csv(pathToCsv) + + OhdsiRTools::logInfo(""Creating negative control outcome cohorts"") + negativeControlOutcomes <- negativeControls[negativeControls$type == ""Outcome"", ] + sql <- SqlRender::loadRenderTranslateSql(""NegativeControlOutcomes.sql"", + ""AhasHfBkleAmputation"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = cohortDatabaseSchema, + target_cohort_table = cohortTable, + outcome_ids = negativeControlOutcomes$outcomeId) + DatabaseConnector::executeSql(conn, sql) + + # Check number of subjects per cohort: + OhdsiRTools::logInfo(""Counting cohorts"") + countCohorts(connection = conn, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder) + DatabaseConnector::disconnect(conn) +} + +addCohortNames <- function(data, IdColumnName = ""cohortDefinitionId"", nameColumnName = ""cohortName"") { + pathToCsv <- system.file(""settings"", ""CohortsToCreate.csv"", package = ""AhasHfBkleAmputation"") + cohortsToCreate <- read.csv(pathToCsv) + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""AhasHfBkleAmputation"") + negativeControls <- read.csv(pathToCsv) + + idToName <- data.frame(cohortId = c(cohortsToCreate$cohortId, + negativeControls$targetId, + negativeControls$comparatorId, + negativeControls$outcomeId), + cohortName = c(as.character(cohortsToCreate$name), + as.character(negativeControls$targetName), + as.character(negativeControls$comparatorName), + as.character(negativeControls$outcomeName))) + idToName <- idToName[order(idToName$cohortId), ] + idToName <- idToName[!duplicated(idToName$cohortId), ] + names(idToName)[1] <- IdColumnName + names(idToName)[2] <- nameColumnName + data <- merge(data, idToName, all.x = TRUE) + # Change order of columns: + idCol <- which(colnames(data) == IdColumnName) + if (idCol < ncol(data) - 1) { + data <- data[, c(1:idCol, ncol(data) , (idCol+1):(ncol(data)-1))] + } + return(data) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AhasHfBkleAmputation/R/Diagnostics.R",".R","13322","213","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of AhasHfBkleAmputation +# +# 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. + +abbreviateLabel <- function(label) { + # label <- ""new users of any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA with established cardiovascular disease and at least 1 prior non-metformin AHA exposure in 365 days prior to first exposure of any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA "" + label <- gsub(""new users of "", """", label) + label <- gsub("" with established cardiovascular disease"", "" with CV"", label) + label <- gsub("" at least 1 prior non-metformin AHA exposure in 365 days prior to.*"", "" prior AHA"", label) + label <- gsub("" no prior non-metformin AHA exposure in 365 days prior to.*"", "" no prior AHA"", label) + label <- gsub(""any DPP-4 inhibitor, GLP-1 agonist, or other select AHA"", ""traditional AHAs"", label) + label <- gsub(""any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA"", ""traditional AHAs + insulin"", label) + label <- gsub("" exposure to"", """", label) + return(label) +} + +#' Generate diagnostics +#' +#' @details +#' This function generates analyses diagnostics. Requires the study to be executed first. +#' +#' @param outputFolder Name of local folder where the results were generated; make sure to use forward slashes +#' (/). Do not use a folder on a network drive since this greatly impacts +#' performance. +#' +#' @export +generateDiagnostics <- function(outputFolder) { + packageName <- ""AhasHfBkleAmputation"" + modelType <- ""cox"" # For MDRR computation + psStrategy <- ""matching"" # For covariate balance labels + cmOutputFolder <- file.path(outputFolder, ""cmOutput"") + + diagnosticsFolder <- file.path(outputFolder, ""diagnostics"") + if (!file.exists(diagnosticsFolder)) + dir.create(diagnosticsFolder) + + pathToCsv <- system.file(""settings"", ""TcosOfInterest.csv"", package = packageName) + tcosOfInterest <- read.csv(pathToCsv, stringsAsFactors = FALSE) + + reference <- readRDS(file.path(cmOutputFolder, ""outcomeModelReference.rds"")) + analysisSummary <- CohortMethod::summarizeAnalyses(reference) + analysisSummary <- addCohortNames(analysisSummary, ""targetId"", ""targetName"") + analysisSummary <- addCohortNames(analysisSummary, ""comparatorId"", ""comparatorName"") + analysisSummary <- addCohortNames(analysisSummary, ""outcomeId"", ""outcomeName"") + cmAnalysisList <- CohortMethod::loadCmAnalysisList(system.file(""settings"", ""cmAnalysisList.json"", package = packageName)) + analyses <- data.frame(analysisId = unique(reference$analysisId), + analysisDescription = """", + stringsAsFactors = FALSE) + for (i in 1:length(cmAnalysisList)) { + analyses$analysisDescription[analyses$analysisId == cmAnalysisList[[i]]$analysisId] <- cmAnalysisList[[i]]$description + } + analysisSummary <- merge(analysisSummary, analyses) + negativeControls <- read.csv(system.file(""settings"", ""NegativeControls.csv"", package = packageName)) + tcsOfInterest <- unique(tcosOfInterest[, c(""targetId"", ""comparatorId"")]) + mdrrs <- data.frame() + models <- data.frame() + for (i in 1:nrow(tcsOfInterest)) { + targetId <- tcsOfInterest$targetId[i] + comparatorId <- tcsOfInterest$comparatorId[i] + idx <- which(tcosOfInterest$targetId == targetId & tcosOfInterest$comparatorId == comparatorId)[1] + targetLabel <- tcosOfInterest$targetName[idx] + comparatorLabel <- tcosOfInterest$comparatorName[idx] + outcomeIds <- as.character(tcosOfInterest$outcomeIds[idx]) + outcomeIds <- as.numeric(strsplit(outcomeIds, split = "";"")[[1]]) + outcomeNames <- as.character(tcosOfInterest$outcomeNames[idx]) + outcomeNames <- strsplit(outcomeNames, split = "";"")[[1]] + for (analysisId in unique(reference$analysisId)) { + analysisDescription <- analyses$analysisDescription[analyses$analysisId == analysisId] + negControlSubset <- analysisSummary[analysisSummary$targetId == targetId & + analysisSummary$comparatorId == comparatorId & + analysisSummary$outcomeId %in% negativeControls$outcomeId & + analysisSummary$analysisId == analysisId, ] + + # Outcome controls + label <- ""OutcomeControls"" + + validNcs <- sum(!is.na(negControlSubset$seLogRr)) + if (validNcs >= 5) { + null <- EmpiricalCalibration::fitMcmcNull(negControlSubset$logRr, negControlSubset$seLogRr) + + fileName <- file.path(diagnosticsFolder, paste0(""nullDistribution_a"", analysisId, ""_t"", targetId, ""_c"", comparatorId, ""_"", label, "".png"")) + plot <- EmpiricalCalibration::plotCalibrationEffect(logRrNegatives = negControlSubset$logRr, + seLogRrNegatives = negControlSubset$seLogRr, + null = null, + showCis = TRUE) + title <- paste(abbreviateLabel(targetLabel), abbreviateLabel(comparatorLabel), sep = "" vs.\n"") + plot <- plot + ggplot2::ggtitle(title) + plot <- plot + ggplot2::theme(plot.title = ggplot2::element_text(colour = ""#000000"", size = 10, hjust = 0.5)) + ggplot2::ggsave(fileName, plot, width = 6, height = 5, dpi = 400) + } else { + null <- NULL + } + # fileName <- file.path(diagnosticsFolder, paste0(""trueAndObs_a"", analysisId, ""_t"", targetId, ""_c"", comparatorId, ""_"", label, "".png"")) + # EmpiricalCalibration::plotTrueAndObserved(logRr = controlSubset$logRr, + # seLogRr = controlSubset$seLogRr, + # trueLogRr = log(controlSubset$targetEffectSize), + # fileName = fileName) + + for (outcomeId in outcomeIds) { + outcomeName <- outcomeNames[outcomeIds == outcomeId] + # Compute MDRR + strataFile <- reference$strataFile[reference$analysisId == analysisId & + reference$targetId == targetId & + reference$comparatorId == comparatorId & + reference$outcomeId == outcomeId] + population <- readRDS(strataFile) + mdrr <- CohortMethod::computeMdrr(population, alpha = 0.05, power = 0.8, twoSided = TRUE, modelType = modelType) + mdrr$targetId <- targetId + mdrr$targetName <- targetLabel + mdrr$comparatorId <- comparatorLabel + mdrr$comparatorName <- comparatorLabel + mdrr$outcomeId <- outcomeId + mdrr$outcomeName <- outcomeName + mdrr$analysisId <- mdrr$analysisId + mdrr$analysisDescription <- analysisDescription + mdrrs <- rbind(mdrrs, mdrr) + # fileName <- file.path(diagnosticsFolder, paste0(""attrition_a"",analysisId,""_t"",targetId,""_c"",comparatorId, ""_o"", outcomeId, "".png"")) + # CohortMethod::drawAttritionDiagram(population, treatmentLabel = targetLabel, comparatorLabel = comparatorLabel, fileName = fileName) + if (!is.null(null)) { + fileName <- file.path(diagnosticsFolder, paste0(""type1Error_a"",analysisId,""_t"",targetId,""_c"",comparatorId, ""_o"", outcomeId,""_"", label, "".png"")) + title <- paste0(abbreviateLabel(targetLabel), "" vs.\n"", abbreviateLabel(comparatorLabel), "" for\n"", outcomeName) + plot <- EmpiricalCalibration::plotExpectedType1Error(seLogRrPositives = mdrr$se, + null = null, + showCis = TRUE, + title = title, + fileName = fileName) + } + } + exampleRef <- reference[reference$analysisId == analysisId & + reference$targetId == targetId & + reference$comparatorId == comparatorId & + reference$outcomeId == outcomeIds[1], ] + + ps <- readRDS(exampleRef$sharedPsFile) + psAfterMatching <- readRDS(exampleRef$strataFile) + cmData <- CohortMethod::loadCohortMethodData(exampleRef$cohortMethodDataFolder) + + fileName <- file.path(diagnosticsFolder, paste0(""psBefore"",psStrategy,""_a"",analysisId,""_t"",targetId,""_c"",comparatorId,"".png"")) + psPlot <- CohortMethod::plotPs(data = ps, + treatmentLabel = abbreviateLabel(targetLabel), + comparatorLabel = abbreviateLabel(comparatorLabel)) + psPlot <- psPlot + ggplot2::theme(legend.title = ggplot2::element_blank(), legend.position = ""top"", legend.direction = ""vertical"") + ggplot2::ggsave(fileName, psPlot, width = 3.5, height = 4, dpi = 400) + + fileName = file.path(diagnosticsFolder, paste(""followupDist_a"",analysisId,""_t"",targetId,""_c"",comparatorId, "".png"",sep="""")) + plot <- CohortMethod::plotFollowUpDistribution(psAfterMatching, + targetLabel = abbreviateLabel(targetLabel), + comparatorLabel = abbreviateLabel(comparatorLabel), + title = NULL) + plot <- plot + ggplot2::theme(legend.title = ggplot2::element_blank(), legend.position = ""top"", legend.direction = ""vertical"") + ggplot2::ggsave(fileName, plot, width = 4, height = 3.5, dpi = 400) + + model <- CohortMethod::getPsModel(ps, cmData) + model$targetId <- targetId + model$targetName <- targetLabel + model$comparatorId <- comparatorLabel + model$comparatorName <- comparatorLabel + model$analysisId <- mdrr$analysisId + model$analysisDescription <- analysisDescription + models <- rbind(models, model) + + fileName = file.path(diagnosticsFolder, paste(""time_a"",analysisId,""_t"",targetId,""_c"",comparatorId, "".png"",sep="""")) + cohorts <- cmData$cohorts + cohorts$group <- abbreviateLabel(targetLabel) + cohorts$group[cohorts$treatment == 0] <- abbreviateLabel(comparatorLabel) + plot <- ggplot2::ggplot(cohorts, ggplot2::aes(x = cohortStartDate, color = group, fill = group, group = group)) + + ggplot2::geom_density(alpha = 0.5) + + ggplot2::xlab(""Cohort start date"") + + ggplot2::ylab(""Density"") + + ggplot2::theme(legend.title = ggplot2::element_blank(), + legend.position = ""top"", + legend.direction = ""vertical"") + ggplot2::ggsave(filename = fileName, plot = plot, width = 5, height = 3.5, dpi = 400) + + balance <- CohortMethod::computeCovariateBalance(psAfterMatching, cmData) + + fileName = file.path(diagnosticsFolder, paste(""balanceScatter_a"",analysisId,""_t"",targetId,""_c"",comparatorId,"".png"",sep="""")) + balanceScatterPlot <- CohortMethod::plotCovariateBalanceScatterPlot(balance = balance, + beforeLabel = paste(""Before"", psStrategy), + afterLabel = paste(""After"", psStrategy)) + title <- paste(abbreviateLabel(targetLabel), abbreviateLabel(comparatorLabel), sep = "" vs.\n"") + balanceScatterPlot <- balanceScatterPlot + ggplot2::ggtitle(title) + balanceScatterPlot <- balanceScatterPlot + ggplot2::theme(plot.title = ggplot2::element_text(colour = ""#000000"", size = 8, hjust = 0.5)) + ggplot2::ggsave(fileName, balanceScatterPlot, width = 4, height = 4.5, dpi = 400) + + fileName = file.path(diagnosticsFolder, paste(""balanceTop_a"",analysisId,""_t"",targetId,""_c"",comparatorId,"".png"",sep="""")) + balanceTopPlot <- CohortMethod::plotCovariateBalanceOfTopVariables(balance = balance, + beforeLabel = paste(""Before"", psStrategy), + afterLabel = paste(""After"", psStrategy)) + title <- paste(abbreviateLabel(targetLabel), abbreviateLabel(comparatorLabel), sep = "" vs.\n"") + balanceTopPlot <- balanceTopPlot + ggplot2::ggtitle(title) + balanceTopPlot <- balanceTopPlot + ggplot2::theme(plot.title = ggplot2::element_text(colour = ""#000000"", size = 9, hjust = 0.5)) + ggplot2::ggsave(fileName, balanceTopPlot, width = 10, height = 6.5, dpi = 400) + } + } + fileName <- file.path(diagnosticsFolder, paste0(""mdrr.csv"")) + write.csv(mdrrs, fileName, row.names = FALSE) + fileName <- file.path(diagnosticsFolder, paste0(""propensityModels.csv"")) + write.csv(models, fileName, row.names = FALSE) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AhasHfBkleAmputation/R/MetaAnalysis.R",".R","7638","184","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of AhasHfBkleAmputation +# +# 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. + +#' Create figures and tables for report +#' +#' @details +#' This function generates tables and figures for the report on the study results. +#' +#' @param outputFolders Vector of names of local folders where the results were generated; make sure +#' to use forward slashes (/). D +#' @param maOutputFolder A local folder where the meta-anlysis results will be written. +#' @param maxCores How many parallel cores should be used? If more cores are made available +#' this can speed up the analyses. +#' +#' @export +doMetaAnalysis <- function(outputFolders, maOutputFolder, maxCores) { + OhdsiRTools::logInfo(""Performing meta-analysis"") + resultsFolder <- file.path(maOutputFolder, ""results"") + if (!file.exists(resultsFolder)) + dir.create(resultsFolder, recursive = TRUE) + shinyDataFolder <- file.path(resultsFolder, ""shinyData"") + if (!file.exists(shinyDataFolder)) + dir.create(shinyDataFolder) + + loadResults <- function(outputFolder) { + files <- list.files(file.path(outputFolder, ""results""), pattern = ""results_.*.csv"", full.names = TRUE) + OhdsiRTools::logInfo(""Loading "", files[1], "" for meta-analysis"") + return(read.csv(files[1])) + } + allResults <- lapply(outputFolders, loadResults) + allResults <- do.call(rbind, allResults) + groups <- split(allResults, paste(allResults$targetId, allResults$comparatorId, allResults$analysisId)) + # Meta-analysis 1: use Hartung-Knapp-Sidik-Jonkman + OhdsiRTools::logInfo(""Meta-analysis using Hartung-Knapp-Sidik-Jonkman"") + cluster <- OhdsiRTools::makeCluster(min(maxCores, 15)) + results <- OhdsiRTools::clusterApply(cluster, groups, computeGroupMetaAnalysis, shinyDataFolder = shinyDataFolder, hksj = TRUE) + OhdsiRTools::stopCluster(cluster) + results <- do.call(rbind, results) + + fileName <- file.path(resultsFolder, paste0(""results_Meta-analysis_HKSJ.csv"")) + write.csv(results, fileName, row.names = FALSE) + + hois <- results[results$type == ""Outcome of interest"", ] + fileName <- file.path(shinyDataFolder, paste0(""resultsHois_Meta-analysis_HKSJ.rds"")) + saveRDS(hois, fileName) + + ncs <- results[results$type == ""Negative control"", c(""targetId"", ""comparatorId"", ""outcomeId"", ""analysisId"", ""database"", ""logRr"", ""seLogRr"")] + fileName <- file.path(shinyDataFolder, paste0(""resultsNcs_Meta-analysis_HKSJ.rds"")) + saveRDS(ncs, fileName) + + # Meta-analysis 1: use DerSimonian-Laird + OhdsiRTools::logInfo(""Meta-analysis using DerSimonian-Laird"") + cluster <- OhdsiRTools::makeCluster(min(maxCores, 15)) + results <- OhdsiRTools::clusterApply(cluster, groups, computeGroupMetaAnalysis, shinyDataFolder = shinyDataFolder, hksj = FALSE) + OhdsiRTools::stopCluster(cluster) + results <- do.call(rbind, results) + + fileName <- file.path(resultsFolder, paste0(""results_Meta-analysis_DL.csv"")) + write.csv(results, fileName, row.names = FALSE) + + hois <- results[results$type == ""Outcome of interest"", ] + fileName <- file.path(shinyDataFolder, paste0(""resultsHois_Meta-analysis_DL.rds"")) + saveRDS(hois, fileName) + + ncs <- results[results$type == ""Negative control"", c(""targetId"", ""comparatorId"", ""outcomeId"", ""analysisId"", ""database"", ""logRr"", ""seLogRr"")] + fileName <- file.path(shinyDataFolder, paste0(""resultsNcs_Meta-analysis_DL.rds"")) + saveRDS(ncs, fileName) +} + +computeGroupMetaAnalysis <- function(group, shinyDataFolder, hksj) { + # group <- groups[[2]] + analysisId <- group$analysisId[1] + targetId <- group$targetId[1] + comparatorId <- group$comparatorId[1] + OhdsiRTools::logTrace(""Performing meta-analysis for target "", targetId, "", comparator "", comparatorId, "", analysis"", analysisId) + outcomeGroups <- split(group, group$outcomeId) + outcomeGroupResults <- lapply(outcomeGroups, computeSingleMetaAnalysis, hksj = hksj) + groupResults <- do.call(rbind, outcomeGroupResults) + negControlSubset <- groupResults[groupResults$type == ""Negative control"", ] + validNcs <- sum(!is.na(negControlSubset$seLogRr)) + if (validNcs >= 5) { + if (hksj) { + fileName <- file.path(shinyDataFolder, paste0(""null_a"",analysisId,""_t"",targetId,""_c"",comparatorId,""_Meta-analysis_HKJS.rds"")) + } else { + fileName <- file.path(shinyDataFolder, paste0(""null_a"",analysisId,""_t"",targetId,""_c"",comparatorId,""_Meta-analysis_DL.rds"")) + } + null <- EmpiricalCalibration::fitMcmcNull(negControlSubset$logRr, negControlSubset$seLogRr) + saveRDS(null, fileName) + + calibratedP <- EmpiricalCalibration::calibrateP(null = null, + logRr = groupResults$logRr, + seLogRr = groupResults$seLogRr) + groupResults$calP <- calibratedP$p + groupResults$calP_lb95ci <- calibratedP$lb95ci + groupResults$calP_ub95ci <- calibratedP$ub95ci + } else { + groupResults$calP <- NA + groupResults$calP_lb95ci <- NA + groupResults$calP_ub95ci <- NA + } + return(groupResults) +} + +computeSingleMetaAnalysis <- function(outcomeGroup, hksj) { + # outcomeGroup <- outcomeGroups[[1]] + maRow <- outcomeGroup[1, ] + outcomeGroup <- outcomeGroup[!is.na(outcomeGroup$seLogRr), ] + if (nrow(outcomeGroup) == 0) { + maRow$treated <- 0 + maRow$comparator <- 0 + maRow$treatedDays <- 0 + maRow$comparatorDays <- 0 + maRow$eventsTreated <- 0 + maRow$eventsComparator <- 0 + maRow$rr <- NA + maRow$ci95lb <- NA + maRow$ci95ub <- NA + maRow$p <- NA + maRow$logRr <- NA + maRow$seLogRr <- NA + maRow$i2 <- NA + } else if (nrow(outcomeGroup) == 1) { + maRow <- outcomeGroup[1, ] + maRow$i2 <- 0 + } else { + maRow$treated <- sum(outcomeGroup$treated) + maRow$comparator <- sum(outcomeGroup$comparator) + maRow$treatedDays <- sum(outcomeGroup$treatedDays) + maRow$comparatorDays <- sum(outcomeGroup$comparatorDays) + maRow$eventsTreated <- sum(outcomeGroup$eventsTreated) + maRow$eventsComparator <- sum(outcomeGroup$eventsComparator) + meta <- meta::metagen(outcomeGroup$logRr, outcomeGroup$seLogRr, sm = ""RR"", hakn = hksj) + s <- summary(meta) + maRow$i2 <- s$I2$TE + if (maRow$i2 < .40) { + rnd <- s$random + maRow$rr <- exp(rnd$TE) + maRow$ci95lb <- exp(rnd$lower) + maRow$ci95ub <- exp(rnd$upper) + maRow$p <- rnd$p + maRow$logRr <- rnd$TE + maRow$seLogRr <- rnd$seTE + } else { + maRow$rr <- NA + maRow$ci95lb <- NA + maRow$ci95ub <- NA + maRow$p <- NA + maRow$logRr <- NA + maRow$seLogRr <- NA + } + } + if (is.na(maRow$logRr)) { + maRow$mdrr <- NA + } else { + alpha <- 0.05 + power <- 0.8 + z1MinAlpha <- qnorm(1 - alpha/2) + zBeta <- -qnorm(1 - power) + pA <- maRow$treated / (maRow$treated + maRow$comparator) + pB <- 1 - pA + totalEvents <- maRow$eventsTreated + maRow$eventsComparator + maRow$mdrr <- exp(sqrt((zBeta + z1MinAlpha)^2/(totalEvents * pA * pB))) + } + if (hksj) { + maRow$database <- ""Meta-analysis (HKSJ)"" + } else { + maRow$database <- ""Meta-analysis (DL)"" + } + return(maRow) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AhasHfBkleAmputation/R/CreateStudyAnalysisDetails.R",".R","28460","384","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of AhasHfBkleAmputation +# +# 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. + +#' Create the analyses details +#' +#' @details +#' This function creates files specifying the analyses that will be performed. +#' +#' @param workFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' +#' @export +createAnalysesDetails <- function(workFolder) { + defaultPrior <- Cyclops::createPrior(""laplace"", + exclude = c(0), + useCrossValidation = TRUE) + + defaultControl <- Cyclops::createControl(cvType = ""auto"", + startingVariance = 0.01, + noiseLevel = ""quiet"", + tolerance = 1e-06, + maxIterations = 2500, + cvRepetitions = 10, + seed = 1234) + + defaultCovariateSettings <- FeatureExtraction::createCovariateSettings(useDemographicsGender = TRUE, + useDemographicsAgeGroup = TRUE, + useDemographicsIndexYear = TRUE, + useDemographicsIndexMonth = TRUE, + useConditionGroupEraLongTerm = TRUE, + useDrugExposureLongTerm = TRUE, + useDrugGroupEraLongTerm = TRUE, + useProcedureOccurrenceLongTerm = TRUE, + useMeasurementLongTerm = TRUE, + useCharlsonIndex = TRUE, + useDistinctConditionCountLongTerm = TRUE, + useDistinctIngredientCountLongTerm = TRUE, + useDistinctProcedureCountLongTerm = TRUE, + useDistinctMeasurementCountLongTerm = TRUE, + useDistinctObservationCountLongTerm = TRUE, + useVisitCountLongTerm = TRUE, + useVisitConceptCountLongTerm = TRUE, + longTermStartDays = -365, + mediumTermStartDays = -180, + shortTermStartDays = -30, + endDays = 0, + addDescendantsToExclude = TRUE) + + priorOutcomesCovariateSettings <- createPriorOutcomesCovariateSettings(windowStart = -99999, + windowEnd = -1, + outcomeIds = c(5432, 5433), + outcomeNames = c(""hospitalizations for heart failure (primary inpatient diagnosis)"", ""Below Knee Lower Extremity Amputation events"")) + + covariateSettings <- list(priorOutcomesCovariateSettings, defaultCovariateSettings) + + getDbCmDataArgs <- CohortMethod::createGetDbCohortMethodDataArgs(washoutPeriod = 0, + firstExposureOnly = FALSE, + removeDuplicateSubjects = FALSE, + restrictToCommonPeriod = TRUE, + maxCohortSize = 0, + excludeDrugsFromCovariates = FALSE, + covariateSettings = covariateSettings) + + timeToFirstEverEventOnTreatment <- CohortMethod::createCreateStudyPopulationArgs(removeSubjectsWithPriorOutcome = TRUE, + firstExposureOnly = FALSE, + washoutPeriod = 0, + removeDuplicateSubjects = FALSE, + minDaysAtRisk = 1, + riskWindowStart = 1, + addExposureDaysToStart = FALSE, + riskWindowEnd = 0, + addExposureDaysToEnd = TRUE, + censorAtNewRiskWindow = FALSE) + + timeToFirstPostIndexEventOnTreatment <- CohortMethod::createCreateStudyPopulationArgs(removeSubjectsWithPriorOutcome = FALSE, + firstExposureOnly = FALSE, + washoutPeriod = 0, + removeDuplicateSubjects = FALSE, + minDaysAtRisk = 1, + riskWindowStart = 1, + addExposureDaysToStart = FALSE, + riskWindowEnd = 0, + addExposureDaysToEnd = TRUE, + censorAtNewRiskWindow = FALSE) + + timeToFirstEverEventITT <- CohortMethod::createCreateStudyPopulationArgs(removeSubjectsWithPriorOutcome = TRUE, + firstExposureOnly = FALSE, + washoutPeriod = 0, + removeDuplicateSubjects = FALSE, + minDaysAtRisk = 1, + riskWindowStart = 1, + addExposureDaysToStart = FALSE, + riskWindowEnd = 9999, + addExposureDaysToEnd = FALSE, + censorAtNewRiskWindow = FALSE) + + timeToFirstPostIndexEventITT <- CohortMethod::createCreateStudyPopulationArgs(removeSubjectsWithPriorOutcome = FALSE, + firstExposureOnly = FALSE, + washoutPeriod = 0, + removeDuplicateSubjects = FALSE, + minDaysAtRisk = 1, + riskWindowStart = 1, + addExposureDaysToStart = FALSE, + riskWindowEnd = 9999, + addExposureDaysToEnd = FALSE, + censorAtNewRiskWindow = FALSE) + + timeToFirstEverEventLag <- CohortMethod::createCreateStudyPopulationArgs(removeSubjectsWithPriorOutcome = TRUE, + firstExposureOnly = FALSE, + washoutPeriod = 0, + removeDuplicateSubjects = FALSE, + minDaysAtRisk = 1, + riskWindowStart = 60, + addExposureDaysToStart = FALSE, + riskWindowEnd = 60, + addExposureDaysToEnd = TRUE, + censorAtNewRiskWindow = FALSE) + + timeToFirstPostIndexEventLag <- CohortMethod::createCreateStudyPopulationArgs(removeSubjectsWithPriorOutcome = FALSE, + firstExposureOnly = FALSE, + washoutPeriod = 0, + removeDuplicateSubjects = FALSE, + minDaysAtRisk = 1, + riskWindowStart = 60, + addExposureDaysToStart = FALSE, + riskWindowEnd = 60, + addExposureDaysToEnd = TRUE, + censorAtNewRiskWindow = FALSE) + + timeToFirstEverEventModifiedITT <- CohortMethod::createCreateStudyPopulationArgs(removeSubjectsWithPriorOutcome = TRUE, + firstExposureOnly = FALSE, + washoutPeriod = 0, + removeDuplicateSubjects = FALSE, + minDaysAtRisk = 1, + riskWindowStart = 1, + addExposureDaysToStart = FALSE, + riskWindowEnd = 9999, + addExposureDaysToEnd = FALSE, + censorAtNewRiskWindow = TRUE) + + timeToFirstPostIndexEventModifiedITT <- CohortMethod::createCreateStudyPopulationArgs(removeSubjectsWithPriorOutcome = FALSE, + firstExposureOnly = FALSE, + washoutPeriod = 0, + removeDuplicateSubjects = FALSE, + minDaysAtRisk = 1, + riskWindowStart = 1, + addExposureDaysToStart = FALSE, + riskWindowEnd = 9999, + addExposureDaysToEnd = FALSE, + censorAtNewRiskWindow = TRUE) + + createPsArgs1 <- CohortMethod::createCreatePsArgs(control = defaultControl, + errorOnHighCorrelation = FALSE, + stopOnError = FALSE) + + matchOnPsArgs1 <- CohortMethod::createMatchOnPsArgs(maxRatio = 100) + + stratifyByPsArgs <- CohortMethod::createStratifyByPsArgs(numberOfStrata = 10) + + fitOutcomeModelArgs1 <- CohortMethod::createFitOutcomeModelArgs(useCovariates = FALSE, + modelType = ""cox"", + stratified = TRUE, + prior = defaultPrior, + control = defaultControl) + + a1 <- CohortMethod::createCmAnalysis(analysisId = 1, + description = ""Time to First Ever Event On Treatment, Matching"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstEverEventOnTreatment, + createPs = TRUE, + createPsArgs = createPsArgs1, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgs1, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + a2 <- CohortMethod::createCmAnalysis(analysisId = 2, + description = ""Time to First Post Index Event On Treatment, Matching"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstPostIndexEventOnTreatment, + createPs = TRUE, + createPsArgs = createPsArgs1, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgs1, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + a3 <- CohortMethod::createCmAnalysis(analysisId = 3, + description = ""Time to First Ever Event Intent to Treat, Matching"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstEverEventITT, + createPs = TRUE, + createPsArgs = createPsArgs1, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgs1, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + a4 <- CohortMethod::createCmAnalysis(analysisId = 4, + description = ""Time to First Post Index Event Intent to Treat, Matching"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstPostIndexEventITT, + createPs = TRUE, + createPsArgs = createPsArgs1, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgs1, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + a5 <- CohortMethod::createCmAnalysis(analysisId = 5, + description = ""Time to First Ever Event Lag, Matching"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstEverEventLag, + createPs = TRUE, + createPsArgs = createPsArgs1, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgs1, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + a6 <- CohortMethod::createCmAnalysis(analysisId = 6, + description = ""Time to First Post Index Event Lag, Matching"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstPostIndexEventLag, + createPs = TRUE, + createPsArgs = createPsArgs1, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgs1, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + a7 <- CohortMethod::createCmAnalysis(analysisId = 7, + description = ""Time to First Ever Event Modified ITT, Matching"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstEverEventModifiedITT, + createPs = TRUE, + createPsArgs = createPsArgs1, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgs1, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + a8 <- CohortMethod::createCmAnalysis(analysisId = 8, + description = ""Time to First Post Index Event Modified ITT, Matching"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstPostIndexEventModifiedITT, + createPs = TRUE, + createPsArgs = createPsArgs1, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgs1, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + a9 <- CohortMethod::createCmAnalysis(analysisId = 9, + description = ""Time to First Ever Event On Treatment, Stratification"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstEverEventOnTreatment, + createPs = TRUE, + createPsArgs = createPsArgs1, + stratifyByPs = TRUE, + stratifyByPsArgs = stratifyByPsArgs, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + a10 <- CohortMethod::createCmAnalysis(analysisId = 10, + description = ""Time to First Post Index Event On Treatment, Stratification"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstPostIndexEventOnTreatment, + createPs = TRUE, + createPsArgs = createPsArgs1, + stratifyByPs = TRUE, + stratifyByPsArgs = stratifyByPsArgs, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + a11 <- CohortMethod::createCmAnalysis(analysisId = 11, + description = ""Time to First Ever Event Intent to Treat, Stratification"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstEverEventITT, + createPs = TRUE, + createPsArgs = createPsArgs1, + stratifyByPs = TRUE, + stratifyByPsArgs = stratifyByPsArgs, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + a12 <- CohortMethod::createCmAnalysis(analysisId = 12, + description = ""Time to First Post Index Event Intent to Treat, Stratification"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstPostIndexEventITT, + createPs = TRUE, + createPsArgs = createPsArgs1, + stratifyByPs = TRUE, + stratifyByPsArgs = stratifyByPsArgs, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + a13 <- CohortMethod::createCmAnalysis(analysisId = 13, + description = ""Time to First Ever Event Lag, Stratification"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstEverEventLag, + createPs = TRUE, + createPsArgs = createPsArgs1, + stratifyByPs = TRUE, + stratifyByPsArgs = stratifyByPsArgs, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + a14 <- CohortMethod::createCmAnalysis(analysisId = 14, + description = ""Time to First Post Index Event Lag, Stratification"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstPostIndexEventLag, + createPs = TRUE, + createPsArgs = createPsArgs1, + stratifyByPs = TRUE, + stratifyByPsArgs = stratifyByPsArgs, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + a15 <- CohortMethod::createCmAnalysis(analysisId = 15, + description = ""Time to First Ever Event Modified ITT, Stratification"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstEverEventModifiedITT, + createPs = TRUE, + createPsArgs = createPsArgs1, + stratifyByPs = TRUE, + stratifyByPsArgs = stratifyByPsArgs, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + a16 <- CohortMethod::createCmAnalysis(analysisId = 16, + description = ""Time to First Post Index Event Modified ITT, Stratification"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstPostIndexEventModifiedITT, + createPs = TRUE, + createPsArgs = createPsArgs1, + stratifyByPs = TRUE, + stratifyByPsArgs = stratifyByPsArgs, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + cmAnalysisList <- list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16) + #cmAnalysisList <- list(a1) + + CohortMethod::saveCmAnalysisList(cmAnalysisList, file.path(workFolder, ""cmAnalysisList.json"")) +} + +createTcos <- function(outputFolder) { + pathToCsv <- system.file(""settings"", ""TcosOfInterest.csv"", package = ""AhasHfBkleAmputation"") + tcosOfInterest <- read.csv(pathToCsv, stringsAsFactors = FALSE) + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""AhasHfBkleAmputation"") + negativeControls <- read.csv(pathToCsv) + negativeControlOutcomes <- negativeControls[negativeControls$type == ""Outcome"", ] + dcosList <- list() + tcs <- unique(tcosOfInterest[, c(""targetId"", ""comparatorId"")]) + for (i in 1:nrow(tcs)) { + targetId <- tcs$targetId[i] + comparatorId <- tcs$comparatorId[i] + outcomeIds <- as.character(tcosOfInterest$outcomeIds[tcosOfInterest$targetId == targetId & tcosOfInterest$comparatorId == comparatorId]) + outcomeIds <- as.numeric(strsplit(outcomeIds, split = "";"")[[1]]) + outcomeIds <- c(outcomeIds, negativeControlOutcomes$outcomeId) + excludeConceptIds <- tcosOfInterest$excludedCovariateConceptIds[tcosOfInterest$targetId == targetId & tcosOfInterest$comparatorId == comparatorId] + excludeConceptIds <- as.numeric(strsplit(excludeConceptIds, split = "";"")[[1]]) + dcos <- CohortMethod::createDrugComparatorOutcomes(targetId = targetId, + comparatorId = comparatorId, + outcomeIds = outcomeIds, + excludedCovariateConceptIds = excludeConceptIds) + dcosList[[length(dcosList) + 1]] <- dcos + } + return(dcosList) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AhasHfBkleAmputation/R/CreateTablesAndFiguresForReport.R",".R","71309","1261","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of AhasHfBkleAmputation +# +# 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. + +#' Create figures and tables for report +#' +#' @details +#' This function generates tables and figures for the report on the study results. +#' +#' @param outputFolders Vector of names of local folders where the results were generated; make sure +#' to use forward slashes (/). D +#' @param databaseNames A vector of unique names for the databases. +#' @param maOutputFolder A local folder where the meta-anlysis results were be written. +#' @param reportFolder A local folder where the tables and figures will be written. +#' +#' @export +createTableAndFiguresForReport <- function(outputFolders, databaseNames, maOutputFolder, reportFolder) { + # outputFolders = c(file.path(studyFolder, ""ccae""), file.path(studyFolder, ""mdcd""), file.path(studyFolder, ""mdcr""), file.path(studyFolder, ""optum"")) + # databaseNames = c(""CCAE"", ""MDCD"", ""MDCR"", ""Optum"") + # reportFolder = file.path(studyFolder, ""report"") + # maOutputFolder = file.path(studyFolder, ""metaAnalysis"") + if (!file.exists(reportFolder)) + dir.create(reportFolder, recursive = TRUE) + createPopCharTable(outputFolders, databaseNames, reportFolder) + createHrTable(outputFolders, databaseNames, maOutputFolder, reportFolder) + createSensAnalysesFigure(outputFolders, databaseNames, maOutputFolder, reportFolder) + createIrTable(outputFolders, databaseNames, reportFolder) + selectKaplanMeierPlots(outputFolders, databaseNames, reportFolder) + createTimeAtRiskTable(outputFolders, databaseNames, reportFolder) + outputAllEstimatesToSingleTable(outputFolders, databaseNames, reportFolder) +} + +createIrTable <- function(outputFolders, databaseNames, reportFolder) { + loadResultsHois <- function(outputFolder, fileName) { + shinyDataFolder <- file.path(outputFolder, ""results"", ""shinyData"") + file <- list.files(shinyDataFolder, pattern = ""resultsHois_.*.rds"", full.names = TRUE) + x <- readRDS(file) + if (is.null(x$i2)) + x$i2 <- NA + return(x) + } + results <- lapply(outputFolders, loadResultsHois) + results <- do.call(rbind, results) + results$comparison <- paste(results$targetDrug, results$comparatorDrug, sep = "" - "") + comparisonsOfInterest <- c(""canagliflozin - any DPP-4 inhibitor, GLP-1 agonist, or other select AHA"", + ""empagliflozin or dapagliflozin - any DPP-4 inhibitor, GLP-1 agonist, or other select AHA"", + ""canagliflozin - any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA"") + results <- results[results$psStrategy == ""Stratification"" & + results$priorExposure == ""no restrictions"" & + results$timeAtRisk %in% c(""On Treatment"", ""Intent to Treat"") & + results$evenType == ""First Post Index Event"" & + results$comparison %in% comparisonsOfInterest, ] + for (establishedCvd in unique(results$establishedCvd)) { + outcomeNames <- c(""BKLE amputation"", ""Heart failure"") + timeAtRisks <-c(""On Treatment"", ""Intent to Treat"") + mainTable <- data.frame() + for (database in databaseNames) { + dbTable <- data.frame() + for (outcomeName in outcomeNames) { + # outcomeName <- outcomeNames[1] + for (timeAtRisk in timeAtRisks) { + # timeAtRisk <- timeAtRisks[1] + subset <- results[results$database == database & + results$outcomeName == outcomeName & + results$timeAtRisk == timeAtRisk & + results$establishedCvd == establishedCvd, ] + cana <- subset[subset$targetDrug == ""canagliflozin"", ][1,] + empaDapa <- subset[subset$targetDrug == ""empagliflozin or dapagliflozin"", ][1,] + nonSglt2 <- subset[subset$comparatorDrug == ""any DPP-4 inhibitor, GLP-1 agonist, or other select AHA"", ][1,] + nonSglt2All <- subset[subset$comparatorDrug == ""any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA"", ][1,] + subTable <- data.frame(outcomeName = gsub(""Heart failure"", ""Hospitalization for heart failure"", outcomeName), + timeAtRisk = timeAtRisk, + exposure = c(""canagliflozin"", ""other SGLT2i"", ""all non-SGLT2i"", ""select non-SGLT2i""), + subjects = c(cana$treated, empaDapa$treated, nonSglt2All$comparator, nonSglt2$comparator), + personTime = c(cana$treatedDays, empaDapa$treatedDays, nonSglt2All$comparatorDays, nonSglt2$comparatorDays) / 365.25, + events = c(cana$eventsTreated, empaDapa$eventsTreated, nonSglt2All$eventsComparator, nonSglt2$eventsComparator)) + subTable$ir <- 1000 * subTable$events / subTable$personTime + dbTable <- rbind(dbTable, subTable) + } + } + colnames(dbTable)[4:7] <- paste(colnames(dbTable)[4:7], database, sep = ""_"") + if (ncol(mainTable) == 0) { + mainTable <- dbTable + } else { + if (!all.equal(mainTable$outcomeName, dbTable$outcomeName) || + !all.equal(mainTable$timeAtRisk, dbTable$timeAtRisk) || + !all.equal(mainTable$exposure, dbTable$exposure)) { + stop(""Something wrong with data ordering"") + } + mainTable <- cbind(mainTable, dbTable[, 4:7]) + } + } + + fileName <- file.path(reportFolder, paste0(""IRs_"", if (establishedCvd == ""required"") ""cvd"" else ""all"", "".xlsx"")) + unlink(fileName) + wb <- XLConnect::loadWorkbook(fileName, create = TRUE) + XLConnect::createSheet(wb, name = ""Incidence"") + + header0 <- c("""", """", """", rep(databaseNames, each = 4)) + XLConnect::writeWorksheet(wb, + sheet = ""Incidence"", + data = as.data.frame(t(header0)), + startRow = 1, + startCol = 1, + rownames = FALSE, + header = FALSE) + XLConnect::mergeCells(wb, sheet = ""Incidence"", reference = ""D1:G1"") + XLConnect::mergeCells(wb, sheet = ""Incidence"", reference = ""H1:K1"") + XLConnect::mergeCells(wb, sheet = ""Incidence"", reference = ""L1:O1"") + XLConnect::mergeCells(wb, sheet = ""Incidence"", reference = ""P1:S1"") + + header1 <- c(""Outcome"", ""Time-at-risk"", ""Exposure"", rep(c(""Persons"", ""Person-time"", ""Events"", ""IR""), length(databaseNames))) + XLConnect::writeWorksheet(wb, + sheet = ""Incidence"", + data = as.data.frame(t(header1)), + startRow = 2, + startCol = 1, + rownames = FALSE, + header = FALSE) + + XLConnect::writeWorksheet(wb, + sheet = ""Incidence"", + data = mainTable, + startRow = 3, + startCol = 1, + rownames = FALSE, + header = FALSE) + countStyle <- XLConnect::createCellStyle(wb) + XLConnect::setDataFormat(countStyle, format = ""###,###,##0"") + rateStyle <- XLConnect::createCellStyle(wb) + XLConnect::setDataFormat(rateStyle, format = ""##0.0"") + for (i in 1:length(databaseNames)) { + XLConnect::setCellStyle(wb, sheet = ""Incidence"", row = 3:18, col = i*4 + rep(0, 30), cellstyle = countStyle) + XLConnect::setCellStyle(wb, sheet = ""Incidence"", row = 3:18, col = i*4 + rep(1, 30), cellstyle = countStyle) + XLConnect::setCellStyle(wb, sheet = ""Incidence"", row = 3:18, col = i*4 + rep(2, 30), cellstyle = countStyle) + XLConnect::setCellStyle(wb, sheet = ""Incidence"", row = 3:18, col = i*4 + rep(3, 30), cellstyle = rateStyle) + } + XLConnect::mergeCells(wb, sheet = ""Incidence"", reference = ""A3:A10"") + XLConnect::mergeCells(wb, sheet = ""Incidence"", reference = ""A11:A18"") + XLConnect::mergeCells(wb, sheet = ""Incidence"", reference = ""B3:B6"") + XLConnect::mergeCells(wb, sheet = ""Incidence"", reference = ""B7:B10"") + XLConnect::mergeCells(wb, sheet = ""Incidence"", reference = ""B11:B14"") + XLConnect::mergeCells(wb, sheet = ""Incidence"", reference = ""B15:B18"") + XLConnect::saveWorkbook(wb) + } +} + +createSensAnalysesFigure <- function(outputFolders, databaseNames, maOutputFolder, reportFolder) { + loadResultsHois <- function(outputFolder, fileName) { + shinyDataFolder <- file.path(outputFolder, ""results"", ""shinyData"") + file <- list.files(shinyDataFolder, pattern = ""resultsHois_.*.rds"", full.names = TRUE) + x <- lapply(file, readRDS) + x <- do.call(rbind, x) + if (is.null(x$i2)) + x$i2 <- NA + return(x) + } + results <- lapply(c(outputFolders, maOutputFolder), loadResultsHois) + results <- do.call(rbind, results) + results$comparison <- paste(results$targetDrug, results$comparatorDrug, sep = "" - "") + outcomeNames <- unique(results$outcomeName) + comparisonsOfInterest <- c(""canagliflozin - any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA"", + ""canagliflozin - any DPP-4 inhibitor, GLP-1 agonist, or other select AHA"", + ""canagliflozin - empagliflozin or dapagliflozin"", + ""empagliflozin or dapagliflozin - any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA"") + for (outcomeName in outcomeNames) { + # outcomeName <- outcomeNames[1] + + results$dbOrder <- match(results$database, c(""CCAE"", ""MDCD"",""MDCR"", ""Optum"", ""Meta-analysis (HKSJ)"", ""Meta-analysis (DL)"")) + results$comparisonOrder <- match(results$comparison, comparisonsOfInterest) + results$timeAtRiskOrder <- match(results$timeAtRisk, c(""On Treatment"", + ""On Treatment (no censor at switch)"", + ""Lag"", + ""Lag (no censor at switch)"", + ""Intent to Treat"", + ""Modified ITT"")) + + subset <- results[results$outcomeName == outcomeName & + results$comparison %in% comparisonsOfInterest, ] + subset <- subset[order(subset$comparisonOrder, + subset$dbOrder, + subset$timeAtRiskOrder, + subset$establishedCvd, + subset$evenType, + subset$psStrategy, + subset$priorExposure), ] + subset$rr[is.na(subset$seLogRr)] <- NA + facetCount <- (length(unique(subset$comparison)) * length(unique(subset$database))) + subset$displayOrder <- rep((nrow(subset)/facetCount):1, facetCount)#nrow(subset):1 + formatQuestion <- function(x) { + result <- rep(""canagliflozin vs. other SGLT2i"", length(x)) + result[x == ""canagliflozin - any DPP-4 inhibitor, GLP-1 agonist, or other select AHA""] <- ""canagliflozin vs. select non-SGLT2i"" + result[x == ""empagliflozin or dapagliflozin - any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA""] <- ""other SGLT2i vs. all non-SGLT2"" + result[x == ""canagliflozin - any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA""] <- ""canagliflozin vs. all non-SGLT2i"" + return(result) + } + formatTimeAtRisk <- function(x) { + result <- x + result[x == ""Intent to Treat""] <- ""Intent-to-treat"" + result[x == ""On Treatment""] <- ""On treatment"" + result[x == ""On Treatment (no censor at switch)""] <- ""On treatment (no censor at switch)"" + result[x == ""Lag""] <- ""On treatment lagged"" + result[x == ""Lag (no censor at switch)""] <- ""On treatment lagged (no censor at switch)"" + return(result) + } + subset$comparison <- formatQuestion(subset$comparison) + subset$timeAtRisk <- formatTimeAtRisk(subset$timeAtRisk) + breaks <- c(0.1, 0.25, 0.5, 1, 2, 4, 6, 8, 10) + col <- c(rgb(0, 0, 0.8, alpha = 1), rgb(0.8, 0.4, 0, alpha = 1)) + colFill <- c(rgb(0, 0, 1, alpha = 0.5), rgb(1, 0.4, 0, alpha = 0.5)) + subset$database <- factor(subset$database, levels = c(""CCAE"", ""MDCD"",""MDCR"", ""Optum"", ""Meta-analysis (HKSJ)"", ""Meta-analysis (DL)"")) + subset$comparison <- factor(subset$comparison, levels = c(""canagliflozin vs. all non-SGLT2i"", + ""canagliflozin vs. select non-SGLT2i"", + ""canagliflozin vs. other SGLT2i"", + ""other SGLT2i vs. all non-SGLT2"")) + subset$timeAtRisk <- factor(subset$timeAtRisk, levels = c(""On treatment"", ""On treatment (no censor at switch)"", ""On treatment lagged"", ""On treatment lagged (no censor at switch)"", ""Intent-to-treat"", ""Modified ITT"")) + plot <- ggplot2::ggplot(subset, ggplot2::aes(x = rr, + y = displayOrder, + xmin = ci95lb, + xmax = ci95ub, + colour = timeAtRisk, + fill = timeAtRisk), environment = environment()) + + ggplot2::geom_vline(xintercept = breaks, colour = ""#AAAAAA"", lty = 1, size = 0.2) + + ggplot2::geom_vline(xintercept = 1, colour = ""#000000"", lty = 1, size = 0.5) + + ggplot2::geom_errorbarh(height = 0, alpha = 0.7) + + ggplot2::geom_point(shape = 16, size = 1, alpha = 0.7) + + # ggplot2::scale_colour_manual(values = col) + + # ggplot2::scale_fill_manual(values = colFill) + + ggplot2::coord_cartesian(xlim = c(0.1, 10)) + + ggplot2::scale_x_continuous(""Hazard ratio"", trans = ""log10"", breaks = breaks, labels = breaks) + + ggplot2::facet_grid(database ~ comparison, scales = ""free_y"", space = ""free"") + + ggplot2::labs(color = ""Time-at-risk"", fill = ""Time-at-risk"") + + ggplot2::theme(panel.grid.minor = ggplot2::element_blank(), + panel.background = ggplot2::element_rect(fill = ""#FAFAFA"",colour = NA), + panel.grid.major = ggplot2::element_line(colour = ""#EEEEEE""), + axis.ticks = ggplot2::element_blank(), + axis.title.y = ggplot2::element_blank(), + axis.title.x = ggplot2::element_blank(), + axis.text.y = ggplot2::element_blank(), + legend.position = ""top"") + + fileName <- file.path(reportFolder, paste0(""SensAnalyses "", outcomeName, "".png"")) + ggplot2::ggsave(fileName, plot, width = 10, height = 14, dpi = 400) + } +} + +createHrTable <- function(outputFolders, databaseNames, maOutputFolder, reportFolder) { + requireNamespace(""XLConnect"") + loadResultsHois <- function(outputFolder, fileName) { + shinyDataFolder <- file.path(outputFolder, ""results"", ""shinyData"") + file <- list.files(shinyDataFolder, pattern = ""resultsHois_.*.rds"", full.names = TRUE) + x <- readRDS(file) + if (is.null(x$i2)) + x$i2 <- NA + return(x) + } + results <- lapply(c(outputFolders, maOutputFolder), loadResultsHois) + results <- do.call(rbind, results) + results$comparison <- paste(results$targetDrug, results$comparatorDrug, sep = "" - "") + outcomeNames <- unique(results$outcomeName) + establishedCvds <- unique(results$establishedCvd) + comparisonsOfInterest <- c(""canagliflozin - any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA"", + ""canagliflozin - any DPP-4 inhibitor, GLP-1 agonist, or other select AHA"", + ""canagliflozin - empagliflozin or dapagliflozin"", + ""empagliflozin or dapagliflozin - any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA"") + for (outcomeName in outcomeNames) { + # outcomeName <- outcomeNames[1] + for (establishedCvd in establishedCvds) { + #establishedCvd <- establishedCvds[1] + fileName <- file.path(reportFolder, paste0(""HRs "", outcomeName, if (establishedCvd == ""required"") ""_cvd"" else ""_all"", "".xlsx"")) + unlink(fileName) + wb <- XLConnect::loadWorkbook(fileName, create = TRUE) + XLConnect::createSheet(wb, name = ""Hazard ratios"") + + header0 <- rep("""", 14) + header0[5] <- ""On treatment"" + header0[10] <- ""Intent-to-treat"" + XLConnect::writeWorksheet(wb, + sheet = ""Hazard ratios"", + data = as.data.frame(t(header0)), + startRow = 1, + startCol = 1, + rownames = FALSE, + header = FALSE) + XLConnect::mergeCells(wb, sheet = ""Hazard ratios"", reference = ""E1:I1"") + XLConnect::mergeCells(wb, sheet = ""Hazard ratios"", reference = ""J1:N1"") + header1 <- c("""", """", ""Exposed (#/PY)"", """", ""Outcomes"", """", ""HR (95% CI)"", ""p"", ""Cal. p"", ""Outcomes"", "" "", ""HR (95% CI)"", ""p"", ""Cal. p"") + XLConnect::writeWorksheet(wb, + sheet = ""Hazard ratios"", + data = as.data.frame(t(header1)), + startRow = 2, + startCol = 1, + rownames = FALSE, + header = FALSE) + XLConnect::mergeCells(wb, sheet = ""Hazard ratios"", reference = ""C2:D2"") + XLConnect::mergeCells(wb, sheet = ""Hazard ratios"", reference = ""E2:F2"") + XLConnect::mergeCells(wb, sheet = ""Hazard ratios"", reference = ""J2:K2"") + header2 <- c(""Question"", + ""Source"", + ""T"", + ""C"", + ""T"", + ""C"", + """", + """", + """", + ""T"", + ""C"") + XLConnect::writeWorksheet(wb, + sheet = ""Hazard ratios"", + data = as.data.frame(t(header2)), + startRow = 3, + startCol = 1, + rownames = FALSE, + header = FALSE) + idx <- results$outcomeName == outcomeName & + results$comparison %in% comparisonsOfInterest & + results$psStrategy == ""Matching"" & + results$priorExposure == ""no restrictions"" & + results$evenType == ""First Post Index Event"" & + results$establishedCvd == establishedCvd + + results$dbOrder <- match(results$database, c(""CCAE"", ""MDCD"",""MDCR"", ""Optum"", ""Meta-analysis"")) + results$comparisonOrder <- match(results$comparison, comparisonsOfInterest) + onTreatment <- results[idx & results$timeAtRisk == ""On Treatment"", ] + itt <- results[idx & results$timeAtRisk == ""Intent to Treat"", ] + onTreatment <- onTreatment[order(onTreatment$establishedCvd, + onTreatment$comparisonOrder, + onTreatment$dbOrder), ] + itt <- itt[order(itt$establishedCvd, + itt$comparisonOrder, + itt$dbOrder), ] + if (!all.equal(onTreatment$establishedCvd, itt$establishedCvd) || + !all.equal(onTreatment$comparison, itt$comparison) || + !all.equal(onTreatment$database, itt$database)) { + stop(""Problem with sorting of data"") + } + formatSampleSize <- function(subjects, days) { + paste(formatC(subjects, big.mark = "","", format=""d""), + formatC(days/365.25, big.mark = "","", format=""d""), + sep = "" / "") + } + formatHr <- function(hr, lb, ub) { + sprintf(""%s (%s-%s)"", + formatC(hr, digits = 2, format = ""f""), + formatC(lb, digits = 2, format = ""f""), + formatC(ub, digits = 2, format = ""f"")) + } + formatEstablishCvd <- function(x) { + result <- rep(""With established CV disease"", length(x)) + result[x == ""not required""] <- ""All"" + return(result) + } + formatQuestion <- function(x) { + result <- rep(""canagliflozin vs. other SGLT2i"", length(x)) + result[x == ""canagliflozin - any DPP-4 inhibitor, GLP-1 agonist, or other select AHA""] <- ""canagliflozin vs. select non-SGLT2i"" + result[x == ""empagliflozin or dapagliflozin - any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA""] <- ""other SGLT2i vs. all non-SGLT2"" + result[x == ""canagliflozin - any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA""] <- ""canagliflozin vs. all non-SGLT2i"" + return(result) + } + + mainTable <- data.frame(question = formatQuestion(onTreatment$comparison), + source = onTreatment$database, + t = formatSampleSize(onTreatment$treated, onTreatment$treatedDays), + c = formatSampleSize(onTreatment$comparator, onTreatment$comparatorDays), + oTonTreatment = onTreatment$eventsTreated, + oConTreatment = onTreatment$eventsComparator, + hrOnTreatment = formatHr(onTreatment$rr, onTreatment$ci95lb, onTreatment$ci95ub), + pOnTreatment = onTreatment$p, + calPOnTreatment = onTreatment$calP, + oTitt = itt$eventsTreated, + oCitt = itt$eventsComparator, + hrItt = formatHr(itt$rr, itt$ci95lb, itt$ci95ub), + pItt = itt$p, + calItt = itt$calP) + XLConnect::writeWorksheet(wb, + data = mainTable, + sheet = ""Hazard ratios"", + startRow = 4, + startCol = 1, + header = FALSE, + rownames = FALSE) + pStyle <- XLConnect::createCellStyle(wb) + XLConnect::setDataFormat(pStyle, format = ""0.00"") + countStyle <- XLConnect::createCellStyle(wb) + XLConnect::setDataFormat(countStyle, format = ""#,##0"") + XLConnect::setCellStyle(wb, sheet = ""Hazard ratios"", row = 4:23, col = rep(5, 19), cellstyle = countStyle) + XLConnect::setCellStyle(wb, sheet = ""Hazard ratios"", row = 4:23, col = rep(6, 19), cellstyle = countStyle) + XLConnect::setCellStyle(wb, sheet = ""Hazard ratios"", row = 4:23, col = rep(8, 19), cellstyle = pStyle) + XLConnect::setCellStyle(wb, sheet = ""Hazard ratios"", row = 4:23, col = rep(9, 19), cellstyle = pStyle) + XLConnect::setCellStyle(wb, sheet = ""Hazard ratios"", row = 4:23, col = rep(10, 19), cellstyle = countStyle) + XLConnect::setCellStyle(wb, sheet = ""Hazard ratios"", row = 4:23, col = rep(11, 19), cellstyle = countStyle) + XLConnect::setCellStyle(wb, sheet = ""Hazard ratios"", row = 4:23, col = rep(13, 19), cellstyle = pStyle) + XLConnect::setCellStyle(wb, sheet = ""Hazard ratios"", row = 4:23, col = rep(14, 19), cellstyle = pStyle) + XLConnect::mergeCells(wb, sheet = ""Hazard ratios"", reference = ""A4:A8"") + XLConnect::mergeCells(wb, sheet = ""Hazard ratios"", reference = ""A9:A13"") + XLConnect::mergeCells(wb, sheet = ""Hazard ratios"", reference = ""A14:A18"") + XLConnect::mergeCells(wb, sheet = ""Hazard ratios"", reference = ""A19:A23"") + XLConnect::setColumnWidth(wb, sheet = ""Hazard ratios"", column = 1, width = -1) + XLConnect::setColumnWidth(wb, sheet = ""Hazard ratios"", column = 2, width = -1) + XLConnect::saveWorkbook(wb) + } + } +} + +createPopCharTable <- function(outputFolders, databaseNames, reportFolder) { + primaryAnalysisId <- 2 #Time to First Post Index Event On Treatment, Matching + pathToCsv <- system.file(""settings"", ""TcosOfInterest.csv"", package = ""AhasHfBkleAmputation"") + tcosOfInterest <- read.csv(pathToCsv, stringsAsFactors = FALSE) + tcosOfInterest$comparison <- paste(tcosOfInterest$targetDrug, tcosOfInterest$comparatorDrug, sep = "" - "") + comparisonsOfInterest <- c(""canagliflozin - any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA"", + ""canagliflozin - any DPP-4 inhibitor, GLP-1 agonist, or other select AHA"", + ""canagliflozin - empagliflozin or dapagliflozin"", + ""empagliflozin or dapagliflozin - any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA"") + primaryTcos <- tcosOfInterest[tcosOfInterest$censorAtSwitch == TRUE & + tcosOfInterest$priorExposure == ""no restrictions"" & + tcosOfInterest$comparison %in% comparisonsOfInterest, ] + pathToCsv <- system.file(""settings"", ""Analyses.csv"", package = ""AhasHfBkleAmputation"") + analyses <- read.csv(pathToCsv, stringsAsFactors = FALSE) + + loadBalance <- function(outputFolder, fileName) { + shinyDataFolder <- file.path(outputFolder, ""results"", ""shinyData"") + file <- list.files(shinyDataFolder, pattern = fileName, full.names = TRUE) + return(readRDS(file)) + } + + for (i in 1:nrow(primaryTcos)) { + outcomeIds <- as.character(tcosOfInterest$outcomeIds[i]) + outcomeIds <- as.numeric(strsplit(outcomeIds, split = "";"")[[1]]) + outcomeNames <- as.character(tcosOfInterest$outcomeNames[i]) + outcomeNames <- strsplit(outcomeNames, split = "";"")[[1]] + # One outcome only: + for (j in 1:1){#length(outcomeIds)) { + outcomeId <- outcomeIds[j] + outcomeName <- outcomeNames[j] + allBalance <- list() + tables <- list() + header3 <- c(""Characteristic"") + for (k in 1:length(databaseNames)) { + databaseName <- databaseNames[k] + shinyDataFolder <- file.path(outputFolders[k], ""results"", ""shinyData"") + fileName <- paste0(""bal_a"",primaryAnalysisId,""_t"",primaryTcos$targetId[i],""_c"",primaryTcos$comparatorId[i],""_o"",outcomeId,""_"",databaseName,"".rds"") + balance <- readRDS(file.path(outputFolders[k], ""results"", ""balance"", fileName)) + # Infer population sizes before matching: + beforeTargetPopSize <- round(mean(balance$beforeMatchingSumTreated / balance$beforeMatchingMeanTreated, na.rm = TRUE)) + beforeComparatorPopSize <- round(mean(balance$beforeMatchingSumComparator / balance$beforeMatchingMeanComparator, na.rm = TRUE)) + + fileName <- paste0(""ahaBal_a"",primaryAnalysisId,""_t"",primaryTcos$targetId[i],""_c"",primaryTcos$comparatorId[i],""_o"",outcomeId,""_"",databaseName,"".rds"") + priorAhaBalance <- readRDS(file.path(shinyDataFolder, fileName)) + balance <- balance[, names(priorAhaBalance)] + balance <- rbind(balance, priorAhaBalance) + # Abbreviate some covariate names: + balance$covariateName <- gsub(""hospitalizations for heart failure.*"", ""Hospitalization for heart failure"", balance$covariateName) + balance$covariateName <- gsub(""Below Knee Lower Extremity Amputation events"", ""BKLE amputations"", balance$covariateName) + balance$covariateName <- gsub(""Neurologic disorder associated with diabetes mellitus"", ""Neurologic disorder associated with DM"", balance$covariateName) + tables[[k]] <- prepareTable1(balance) + allBalance[[k]] <- balance + fileName <- file.path(shinyDataFolder, paste0(""resultsHois_"", databaseName,"".rds"")) + resultsHois <- readRDS(fileName) + row <- resultsHois[resultsHois$targetId == primaryTcos$targetId[i] & + resultsHois$comparatorId == primaryTcos$comparatorId[i] & + resultsHois$outcomeId == outcomeId & + resultsHois$analysisId == primaryAnalysisId, ] + # header3 <- c(header3, + # paste0(""% (n = "",format(beforeTargetPopSize, big.mark = "",""), "")""), + # paste0(""% (n = "",format(beforeComparatorPopSize, big.mark = "",""), "")""), + # ""Std.diff"", + # paste0(""% (n = "",format(row$treated, big.mark = "",""), "")""), + # paste0(""% (n = "",format(row$comparator, big.mark = "",""), "")""), + # ""Std.diff"") + header3 <- c(header3, + ""%"", + ""%"", + ""Std.d."", + ""%"", + ""%"", + ""Std.d."") + } + # Create main table by combining all balances to get complete list of covariates: + allBalance <- do.call(rbind, allBalance) + allBalance <- allBalance[order(allBalance$covariateName), ] + allBalance <- allBalance[!duplicated(allBalance$covariateName), ] + headerCol <- prepareTable1(allBalance)[, 1] + mainTable <- matrix(NA, nrow = length(headerCol), ncol = length(tables) * 6) + for (k in 1:length(databaseNames)) { + mainTable[match(tables[[k]]$Characteristic, headerCol), ((k-1)*6)+(1:6)] <- as.matrix(tables[[k]][, 2:7]) + } + mainTable <- as.data.frame(mainTable) + mainTable <- cbind(data.frame(headerCol = headerCol), mainTable) + + createExcelTable <- function(mainTable, part) { + library(xlsx) + workBook <- xlsx::createWorkbook(type=""xlsx"") + sheet <- xlsx::createSheet(workBook, sheetName = ""Population characteristics"") + percentStyle <- xlsx::CellStyle(wb = workBook, dataFormat = xlsx::DataFormat(""#,##0.0"")) + diffStyle <- xlsx::CellStyle(wb = workBook, dataFormat = xlsx::DataFormat(""#,##0.00"")) + header0 <- rep("""", 1+6*length(databaseNames)) + header0[2-6+6*(1:length(databaseNames))] <- databaseNames + xlsx::addDataFrame(as.data.frame(t(header0)), + sheet = sheet, + startRow = 1, + startColumn = 1, + col.names = FALSE, + row.names = FALSE, + showNA = FALSE) + for (k in 1:length(databaseNames)) { + xlsx::addMergedRegion(sheet, + startRow = 1, + endRow = 1, + startColumn = (k-1)*6 + 2, + endColumn = (k-1)*6 + 7) + } + header1 <- c("""", rep(c(""Before matching"", """", """", ""After matching"", """", """"), length(databaseNames))) + xlsx::addDataFrame(as.data.frame(t(header1)), + sheet = sheet, + startRow = 2, + startColumn = 1, + col.names = FALSE, + row.names = FALSE, + showNA = FALSE) + for (k in 1:length(databaseNames)) { + addMergedRegion(sheet, + startRow = 2, + endRow = 2, + startColumn = (k-1)*6 + 2, + endColumn = (k-1)*6 + 4) + addMergedRegion(sheet, + startRow = 2, + endRow = 2, + startColumn = (k-1)*6 + 5, + endColumn = (k-1)*6 + 7) + } + header2 <- c("""", rep(c(""T"", ""c"", """"), 2*length(databaseNames))) + xlsx::addDataFrame(as.data.frame(t(header2)), + sheet = sheet, + startRow = 3, + startColumn = 1, + col.names = FALSE, + row.names = FALSE, + showNA = FALSE) + xlsx::addDataFrame(as.data.frame(t(header3)), + sheet = sheet, + startRow = 4, + startColumn = 1, + col.names = FALSE, + row.names = FALSE, + showNA = FALSE) + styles <- rep(list(percentStyle, percentStyle, diffStyle,percentStyle, percentStyle, diffStyle), length(databaseNames)) + names(styles) <- 1+(1:length(styles)) + xlsx::addDataFrame(mainTable, + sheet = sheet, + startRow = 5, + startColumn = 1, + col.names = FALSE, + row.names = FALSE, + showNA = FALSE, + colStyle = styles) + xlsx::setColumnWidth(sheet, 1, 45) + xlsx::setColumnWidth(sheet, 2:25, 6) + fileName <- paste0(""Chars "", primaryTcos$targetDrug[i], ""_"", primaryTcos$comparatorDrug[i],if (primaryTcos$establishedCvd[i] == ""required"") ""_cvd"" else ""_all"", ""_part"",part,"".xlsx"") + xlsx::saveWorkbook(workBook, file.path(reportFolder, fileName)) + } + + half <- ceiling(nrow(mainTable) / 2) + createExcelTable(mainTable[1:half, ], 1) + createExcelTable(mainTable[(half+1):nrow(mainTable), ], 2) + } + } +} + + +prepareTable1 <- function(balance) { + pathToCsv <- system.file(""settings"", ""Table1Specs.csv"", package = ""AhasHfBkleAmputation"") + specifications <- read.csv(pathToCsv, stringsAsFactors = FALSE) + + fixCase <- function(label) { + idx <- (toupper(label) == label) + if (any(idx)) { + label[idx] <- paste0(substr(label[idx], 1, 1), + tolower(substr(label[idx], 2, nchar(label[idx])))) + } + return(label) + } + + resultsTable <- data.frame() + for (i in 1:nrow(specifications)) { + if (specifications$analysisId[i] == """") { + resultsTable <- rbind(resultsTable, + data.frame(Characteristic = specifications$label[i], value = """")) + } else { + idx <- balance$analysisId == specifications$analysisId[i] + if (any(idx)) { + if (specifications$covariateIds[i] != """") { + covariateIds <- as.numeric(strsplit(specifications$covariateIds[i], "","")[[1]]) + idx <- balance$covariateId %in% covariateIds + } else { + covariateIds <- NULL + } + if (any(idx)) { + balanceSubset <- balance[idx, ] + if (is.null(covariateIds)) { + balanceSubset <- balanceSubset[order(balanceSubset$covariateId), ] + } else { + balanceSubset <- merge(balanceSubset, data.frame(covariateId = covariateIds, + rn = 1:length(covariateIds))) + balanceSubset <- balanceSubset[order(balanceSubset$rn, + balanceSubset$covariateId), ] + } + balanceSubset$covariateName <- fixCase(gsub(""^.*: "", + """", + balanceSubset$covariateName)) + if (specifications$covariateIds[i] == """" || length(covariateIds) > 1) { + resultsTable <- rbind(resultsTable, data.frame(Characteristic = specifications$label[i], + beforeMatchingMeanTreated = NA, + beforeMatchingMeanComparator = NA, + beforeMatchingStdDiff = NA, + afterMatchingMeanTreated = NA, + afterMatchingMeanComparator = NA, + afterMatchingStdDiff = NA, + stringsAsFactors = FALSE)) + resultsTable <- rbind(resultsTable, + data.frame(Characteristic = paste0("" "", balanceSubset$covariateName), + beforeMatchingMeanTreated = balanceSubset$beforeMatchingMeanTreated, + beforeMatchingMeanComparator = balanceSubset$beforeMatchingMeanComparator, + beforeMatchingStdDiff = balanceSubset$beforeMatchingStdDiff, + afterMatchingMeanTreated = balanceSubset$afterMatchingMeanTreated, + afterMatchingMeanComparator = balanceSubset$afterMatchingMeanComparator, + afterMatchingStdDiff = balanceSubset$afterMatchingStdDiff, + stringsAsFactors = FALSE)) + } else { + resultsTable <- rbind(resultsTable, data.frame(Characteristic = specifications$label[i], + beforeMatchingMeanTreated = balanceSubset$beforeMatchingMeanTreated, + beforeMatchingMeanComparator = balanceSubset$beforeMatchingMeanComparator, + beforeMatchingStdDiff = balanceSubset$beforeMatchingStdDiff, + afterMatchingMeanTreated = balanceSubset$afterMatchingMeanTreated, + afterMatchingMeanComparator = balanceSubset$afterMatchingMeanComparator, + afterMatchingStdDiff = balanceSubset$afterMatchingStdDiff, + stringsAsFactors = FALSE)) + } + } + } + } + } + resultsTable$beforeMatchingMeanTreated <- resultsTable$beforeMatchingMeanTreated * 100 + resultsTable$beforeMatchingMeanComparator <- resultsTable$beforeMatchingMeanComparator * 100 + resultsTable$afterMatchingMeanTreated <- resultsTable$afterMatchingMeanTreated * 100 + resultsTable$afterMatchingMeanComparator <- resultsTable$afterMatchingMeanComparator * 100 + return(resultsTable) +} + +selectKaplanMeierPlots <- function() { + + plotKm <- function(database, outputFolder, establishedCvd, analysisId, outcomeId) { + cmOutputFolder <- file.path(outputFolder, ""cmOutput"") + reference <- readRDS(file.path(cmOutputFolder, ""outcomeModelReference.rds"")) + pathToCsv <- system.file(""settings"", ""TcosOfInterest.csv"", package = ""AhasHfBkleAmputation"") + tcosOfInterest <- read.csv(pathToCsv, stringsAsFactors = FALSE) + row <- tcosOfInterest[tcosOfInterest$targetDrug ==""canagliflozin"" & + tcosOfInterest$comparatorDrug == ""any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA"" & + tcosOfInterest$establishedCvd == establishedCvd & + tcosOfInterest$priorExposure == ""no restrictions"" & + tcosOfInterest$censorAtSwitch == TRUE, ] + strataFile <- reference$strataFile[reference$targetId == row$targetId & + reference$comparatorId == row$comparatorId & + reference$analysisId == analysisId & + reference$outcomeId == outcomeId] + strataFile <- gsub(""^[a-z]:/"", ""r:/"", strataFile) + strata <- readRDS(strataFile) + plot <- CohortMethod::plotKaplanMeier(strata, + title = database, + treatmentLabel = ""canagliflozin"", + comparatorLabel = ""non-SGLT2i"") + return(plot) + } + + plot4Plots <- function(establishedCvd, analysisId, outcomeId) { + plot1 <- plotKm(database = databaseNames[1], + outputFolder = outputFolders[1], + establishedCvd = establishedCvd, + analysisId = analysisId, + outcomeId = outcomeId) + plot2 <-plotKm(database = databaseNames[2], + outputFolder = outputFolders[2], + establishedCvd = establishedCvd, + analysisId = analysisId, + outcomeId = outcomeId) + plot3 <-plotKm(database = databaseNames[3], + outputFolder = outputFolders[3], + establishedCvd = establishedCvd, + analysisId = analysisId, + outcomeId = outcomeId) + plot4 <-plotKm(database = databaseNames[4], + outputFolder = outputFolders[4], + establishedCvd = establishedCvd, + analysisId = analysisId, + outcomeId = outcomeId) + + g <- gridExtra::grid.arrange(plot1$grobs[[1]], + plot2$grobs[[1]], + plot1$grobs[[2]], + plot2$grobs[[2]], + plot3$grobs[[1]], + plot4$grobs[[1]], + plot3$grobs[[2]], + plot4$grobs[[2]], + heights = c(400,125, 400, 125), + nrow = 4, + ncol = 2) + fileName <- paste0(""KM_"", + if (analysisId == 2) ""_onTreatment"" else ""_itt"", + if (outcomeId == 5433) ""_BkleAmputation"" else ""_heartFailure"", + if (establishedCvd == ""required"") ""_cvd"" else ""_all"", + "".png"") + ggplot2::ggsave(plot = g, filename = file.path(reportFolder, fileName), width = 13, height = 9) + } + # analysisId 2 = on treatment first post-index event + # analysisId 4 = ITT first post-index event + # outcomeId 5432 = Heart Failure + # outcomeId 5433 = BKLE amputations + plot4Plots(establishedCvd = ""not required"", analysisId = 2, outcomeId = 5432) + plot4Plots(establishedCvd = ""not required"", analysisId = 4, outcomeId = 5432) + plot4Plots(establishedCvd = ""required"", analysisId = 2, outcomeId = 5432) + plot4Plots(establishedCvd = ""required"", analysisId = 4, outcomeId = 5432) + plot4Plots(establishedCvd = ""not required"", analysisId = 2, outcomeId = 5433) + plot4Plots(establishedCvd = ""not required"", analysisId = 4, outcomeId = 5433) + plot4Plots(establishedCvd = ""required"", analysisId = 2, outcomeId = 5433) + plot4Plots(establishedCvd = ""required"", analysisId = 4, outcomeId = 5433) +} + + +createTimeAtRiskTable <- function(outputFolders, databaseNames, reportFolder) { + requireNamespace(""XLConnect"") + loadResultsHois <- function(outputFolder, fileName) { + shinyDataFolder <- file.path(outputFolder, ""results"", ""shinyData"") + file <- list.files(shinyDataFolder, pattern = ""resultsHois_.*.rds"", full.names = TRUE) + x <- readRDS(file) + if (is.null(x$i2)) + x$i2 <- NA + return(x) + } + results <- lapply(outputFolders, loadResultsHois) + results <- do.call(rbind, results) + results$comparison <- paste(results$targetDrug, results$comparatorDrug, sep = "" - "") + outcomeNames <- unique(results$outcomeName) + establishedCvds <- unique(results$establishedCvd) + comparisonsOfInterest <- c(""canagliflozin - any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA"", + ""canagliflozin - any DPP-4 inhibitor, GLP-1 agonist, or other select AHA"", + ""canagliflozin - empagliflozin or dapagliflozin"", + ""empagliflozin or dapagliflozin - any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA"") + for (outcomeName in outcomeNames) { + # outcomeName <- outcomeNames[1] + for (establishedCvd in establishedCvds) { + #establishedCvd <- establishedCvds[1] + fileName <- file.path(reportFolder, paste0(""TAR "", outcomeName, if (establishedCvd == ""required"") ""_cvd"" else ""_all"", "".xlsx"")) + unlink(fileName) + wb <- XLConnect::loadWorkbook(fileName, create = TRUE) + XLConnect::createSheet(wb, name = ""Time-at-risk"") + + header0 <- rep("""", 14) + header0[3] <- ""On treatment"" + header0[17] <- ""Intent-to-treat"" + XLConnect::writeWorksheet(wb, + sheet = ""Time-at-risk"", + data = as.data.frame(t(header0)), + startRow = 1, + startCol = 1, + rownames = FALSE, + header = FALSE) + XLConnect::mergeCells(wb, sheet = ""Time-at-risk"", reference = ""C1:P1"") + XLConnect::mergeCells(wb, sheet = ""Time-at-risk"", reference = ""Q1:AD1"") + header1 <- c("""", """", ""Target"", """", """", """", """", """", """", ""Comparator"", """", """", """", """", """", """", ""Target"", """", """", """", """", """", """", ""Comparator"", """", """", """", """", """", """") + XLConnect::writeWorksheet(wb, + sheet = ""Time-at-risk"", + data = as.data.frame(t(header1)), + startRow = 2, + startCol = 1, + rownames = FALSE, + header = FALSE) + XLConnect::mergeCells(wb, sheet = ""Time-at-risk"", reference = ""C2:I2"") + XLConnect::mergeCells(wb, sheet = ""Time-at-risk"", reference = ""J2:P2"") + XLConnect::mergeCells(wb, sheet = ""Time-at-risk"", reference = ""Q2:W2"") + XLConnect::mergeCells(wb, sheet = ""Time-at-risk"", reference = ""X2:AD2"") + header2 <- c(""Question"", + ""Source"", + ""Mean"", + ""SD"", + ""Min"", + ""P25"", + ""Med"", + ""P75"", + ""Max"", + ""Mean"", + ""SD"", + ""Min"", + ""P25"", + ""Med"", + ""P75"", + ""Max"", + ""Mean"", + ""SD"", + ""Min"", + ""P25"", + ""Med"", + ""P75"", + ""Max"", + ""Mean"", + ""SD"", + ""Min"", + ""P25"", + ""Med"", + ""P75"", + ""Max"") + XLConnect::writeWorksheet(wb, + sheet = ""Time-at-risk"", + data = as.data.frame(t(header2)), + startRow = 3, + startCol = 1, + rownames = FALSE, + header = FALSE) + idx <- results$outcomeName == outcomeName & + results$comparison %in% comparisonsOfInterest & + results$psStrategy == ""Matching"" & + results$priorExposure == ""no restrictions"" & + results$evenType == ""First Post Index Event"" & + results$establishedCvd == establishedCvd + + results$dbOrder <- match(results$database, c(""CCAE"", ""MDCD"",""MDCR"", ""Optum"", ""Meta-analysis"")) + results$comparisonOrder <- match(results$comparison, comparisonsOfInterest) + onTreatment <- results[idx & results$timeAtRisk == ""On Treatment"", ] + itt <- results[idx & results$timeAtRisk == ""Intent to Treat"", ] + onTreatment <- onTreatment[order(onTreatment$establishedCvd, + onTreatment$comparisonOrder, + onTreatment$dbOrder), ] + itt <- itt[order(itt$establishedCvd, + itt$comparisonOrder, + itt$dbOrder), ] + if (!all.equal(onTreatment$establishedCvd, itt$establishedCvd) || + !all.equal(onTreatment$comparison, itt$comparison) || + !all.equal(onTreatment$database, itt$database)) { + stop(""Problem with sorting of data"") + } + formatDays <- function(days) { + formatC(days, big.mark = "","", format=""d"") + } + formatMeanSd <- function(days) { + formatC(days, digits = 1, format = ""f"") + } + formatEstablishCvd <- function(x) { + result <- rep(""With established CV disease"", length(x)) + result[x == ""not required""] <- ""All"" + return(result) + } + formatQuestion <- function(x) { + result <- rep(""canagliflozin vs. other SGLT2i"", length(x)) + result[x == ""canagliflozin - any DPP-4 inhibitor, GLP-1 agonist, or other select AHA""] <- ""canagliflozin vs. select non-SGLT2i"" + result[x == ""empagliflozin or dapagliflozin - any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA""] <- ""other SGLT2i vs. all non-SGLT2"" + result[x == ""canagliflozin - any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA""] <- ""canagliflozin vs. all non-SGLT2i"" + return(result) + } + + mainTable <- data.frame(question = formatQuestion(onTreatment$comparison), + source = onTreatment$database, + meanTOnTreatment = onTreatment$tarTargetMean, + sdTOnTreatment = onTreatment$tarTargetSd, + minTOnTreatment = onTreatment$tarTargetMin, + p25TOnTreatment = onTreatment$tarTargetP25, + medianTOnTreatment = onTreatment$tarTargetMedian, + p75TOnTreatment = onTreatment$tarTargetP75, + maxTOnTreatment = onTreatment$tarTargetMax, + meanCOnTreatment = onTreatment$tarComparatorMean, + sdCOnTreatment = onTreatment$tarComparatorSd, + minCOnTreatment = onTreatment$tarComparatorMin, + p25COnTreatment = onTreatment$tarComparatorP25, + medianCOnTreatment = onTreatment$tarComparatorMedian, + p75COnTreatment = onTreatment$tarComparatorP75, + maxCOnTreatment = onTreatment$tarComparatorMax, + meanTItt = itt$tarTargetMean, + sdTItt = itt$tarTargetSd, + minTItt = itt$tarTargetMin, + p25TItt = itt$tarTargetP25, + medianTItt = itt$tarTargetMedian, + p75TItt = itt$tarTargetP75, + maxTItt = itt$tarTargetMax, + meanCItt = itt$tarComparatorMean, + sdCItt = itt$tarComparatorSd, + minCItt = itt$tarComparatorMin, + p25CItt = itt$tarComparatorP25, + medianCItt = itt$tarComparatorMedian, + p75CItt = itt$tarComparatorP75, + maxCItt = itt$tarComparatorMax) + XLConnect::writeWorksheet(wb, + data = mainTable, + sheet = ""Time-at-risk"", + startRow = 4, + startCol = 1, + header = FALSE, + rownames = FALSE) + pStyle <- XLConnect::createCellStyle(wb) + XLConnect::setDataFormat(pStyle, format = ""#,##0.0"") + countStyle <- XLConnect::createCellStyle(wb) + XLConnect::setDataFormat(countStyle, format = ""#,##0"") + XLConnect::setCellStyle(wb, sheet = ""Time-at-risk"", row = 4:19, col = rep(3, 19), cellstyle = pStyle) + XLConnect::setCellStyle(wb, sheet = ""Time-at-risk"", row = 4:19, col = rep(4, 19), cellstyle = pStyle) + XLConnect::setCellStyle(wb, sheet = ""Time-at-risk"", row = 4:19, col = rep(5, 19), cellstyle = countStyle) + XLConnect::setCellStyle(wb, sheet = ""Time-at-risk"", row = 4:19, col = rep(6, 19), cellstyle = countStyle) + XLConnect::setCellStyle(wb, sheet = ""Time-at-risk"", row = 4:19, col = rep(7, 19), cellstyle = countStyle) + XLConnect::setCellStyle(wb, sheet = ""Time-at-risk"", row = 4:19, col = rep(8, 19), cellstyle = countStyle) + XLConnect::setCellStyle(wb, sheet = ""Time-at-risk"", row = 4:19, col = rep(9, 19), cellstyle = countStyle) + XLConnect::setCellStyle(wb, sheet = ""Time-at-risk"", row = 4:19, col = rep(10, 19), cellstyle = pStyle) + XLConnect::setCellStyle(wb, sheet = ""Time-at-risk"", row = 4:19, col = rep(11, 19), cellstyle = pStyle) + XLConnect::setCellStyle(wb, sheet = ""Time-at-risk"", row = 4:19, col = rep(12, 19), cellstyle = countStyle) + XLConnect::setCellStyle(wb, sheet = ""Time-at-risk"", row = 4:19, col = rep(13, 19), cellstyle = countStyle) + XLConnect::setCellStyle(wb, sheet = ""Time-at-risk"", row = 4:19, col = rep(14, 19), cellstyle = countStyle) + XLConnect::setCellStyle(wb, sheet = ""Time-at-risk"", row = 4:19, col = rep(15, 19), cellstyle = countStyle) + XLConnect::setCellStyle(wb, sheet = ""Time-at-risk"", row = 4:19, col = rep(16, 19), cellstyle = countStyle) + XLConnect::setCellStyle(wb, sheet = ""Time-at-risk"", row = 4:19, col = rep(17, 19), cellstyle = pStyle) + XLConnect::setCellStyle(wb, sheet = ""Time-at-risk"", row = 4:19, col = rep(18, 19), cellstyle = pStyle) + XLConnect::setCellStyle(wb, sheet = ""Time-at-risk"", row = 4:19, col = rep(19, 19), cellstyle = countStyle) + XLConnect::setCellStyle(wb, sheet = ""Time-at-risk"", row = 4:19, col = rep(20, 19), cellstyle = countStyle) + XLConnect::setCellStyle(wb, sheet = ""Time-at-risk"", row = 4:19, col = rep(21, 19), cellstyle = countStyle) + XLConnect::setCellStyle(wb, sheet = ""Time-at-risk"", row = 4:19, col = rep(22, 19), cellstyle = countStyle) + XLConnect::setCellStyle(wb, sheet = ""Time-at-risk"", row = 4:19, col = rep(23, 19), cellstyle = countStyle) + XLConnect::setCellStyle(wb, sheet = ""Time-at-risk"", row = 4:19, col = rep(24, 19), cellstyle = pStyle) + XLConnect::setCellStyle(wb, sheet = ""Time-at-risk"", row = 4:19, col = rep(25, 19), cellstyle = pStyle) + XLConnect::setCellStyle(wb, sheet = ""Time-at-risk"", row = 4:19, col = rep(26, 19), cellstyle = countStyle) + XLConnect::setCellStyle(wb, sheet = ""Time-at-risk"", row = 4:19, col = rep(27, 19), cellstyle = countStyle) + XLConnect::setCellStyle(wb, sheet = ""Time-at-risk"", row = 4:19, col = rep(28, 19), cellstyle = countStyle) + XLConnect::setCellStyle(wb, sheet = ""Time-at-risk"", row = 4:19, col = rep(29, 19), cellstyle = countStyle) + XLConnect::setCellStyle(wb, sheet = ""Time-at-risk"", row = 4:19, col = rep(30, 19), cellstyle = countStyle) + XLConnect::mergeCells(wb, sheet = ""Time-at-risk"", reference = ""A4:A7"") + XLConnect::mergeCells(wb, sheet = ""Time-at-risk"", reference = ""A8:A11"") + XLConnect::mergeCells(wb, sheet = ""Time-at-risk"", reference = ""A12:A15"") + XLConnect::mergeCells(wb, sheet = ""Time-at-risk"", reference = ""A16:A19"") + XLConnect::setColumnWidth(wb, sheet = ""Time-at-risk"", column = 1, width = -1) + XLConnect::setColumnWidth(wb, sheet = ""Time-at-risk"", column = 2, width = -1) + XLConnect::saveWorkbook(wb) + } + } +} + +outputAllEstimatesToSingleTable <- function(outputFolders, databaseNames, maOutputFolder, reportFolder) { + loadResultsHois <- function(outputFolder, fileName) { + shinyDataFolder <- file.path(outputFolder, ""results"", ""shinyData"") + files <- list.files(shinyDataFolder, pattern = ""resultsHois_.*.rds"", full.names = TRUE) + result <- data.frame() + for (file in files) { + x <- readRDS(file) + if (is.null(x$i2)) + x$i2 <- NA + result <- rbind(result, x) + } + return(result) + } + results <- lapply(c(outputFolders, maOutputFolder), loadResultsHois) + results <- do.call(rbind, results) + results$rr[is.na(results$seLogRr)] <- NA + + formatDrug <- function(x) { + result <- x + result[x == ""empagliflozin or dapagliflozin""] <- ""other SGLT2i"" + result[x == ""any DPP-4 inhibitor, GLP-1 agonist, or other select AHA""] <- ""select non-SGLT2i"" + result[x == ""any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA""] <- ""all non-SGLT2i"" + return(result) + } + results$targetDrug <- formatDrug(results$targetDrug) + results$comparatorDrug <- formatDrug(results$comparatorDrug) + table <- results[, c(""targetDrug"", + ""comparatorDrug"", + ""outcomeName"", + ""establishedCvd"", + ""priorExposure"", + ""timeAtRisk"", + ""evenType"", + ""psStrategy"", + ""database"", + ""rr"", + ""ci95lb"", + ""ci95ub"", + ""p"", + ""calP"")] + + colnames(table) <- c(""Target"", ""Comparator"", ""Outcome"", + ""Established cardiovascular disease"", + ""Prior exposure"", + ""Time at risk"", + ""Event type"", + ""Propensity score strategy"", + ""Database"", + ""Hazard ratio"", + ""Lower bound of the 95 confidence interval"", + ""Upper bound of the 95 confidence interval"", + ""P-value (uncalibrated)"", + ""Calibrated p-value"") + fileName <- file.path(reportFolder, ""AllEffectSizeEstimates.xlsx"") + unlink(fileName) + wb <- XLConnect::loadWorkbook(fileName, create = TRUE) + XLConnect::createSheet(wb, name = ""Effect size estimates"") + XLConnect::writeWorksheet(wb, + data = table, + sheet = ""Effect size estimates"", + startRow = 1, + startCol = 1, + header = TRUE, + rownames = FALSE) + style <- XLConnect::createCellStyle(wb) + XLConnect::setDataFormat(style, format = ""#,##0.00"") + XLConnect::setCellStyle(wb, sheet = ""Effect size estimates"", row = 1+1:nrow(results), col = 10, cellstyle = style) + XLConnect::setCellStyle(wb, sheet = ""Effect size estimates"", row = 1+1:nrow(results), col = 11, cellstyle = style) + XLConnect::setCellStyle(wb, sheet = ""Effect size estimates"", row = 1+1:nrow(results), col = 12, cellstyle = style) + XLConnect::setCellStyle(wb, sheet = ""Effect size estimates"", row = 1+1:nrow(results), col = 13, cellstyle = style) + XLConnect::setCellStyle(wb, sheet = ""Effect size estimates"", row = 1+1:nrow(results), col = 14, cellstyle = style) + XLConnect::saveWorkbook(wb) +} + + +createEstimateScatterPlots <- function(outputFolders, databaseNames, maOutputFolder, reportFolder) { + loadResultsHois <- function(outputFolder, fileName) { + shinyDataFolder <- file.path(outputFolder, ""results"", ""shinyData"") + file <- list.files(shinyDataFolder, pattern = ""resultsHois_.*.rds"", full.names = TRUE) + x <- lapply(file, readRDS) + x <- do.call(rbind, x) + if (is.null(x$i2)) + x$i2 <- NA + return(x) + } + results <- lapply(c(outputFolders, maOutputFolder), loadResultsHois) + results <- do.call(rbind, results) + results$comparison <- paste(results$targetDrug, results$comparatorDrug, sep = "" - "") + + loadResultsNcs <- function(outputFolder, fileName) { + shinyDataFolder <- file.path(outputFolder, ""results"", ""shinyData"") + file <- list.files(shinyDataFolder, pattern = ""resultsNcs_.*.rds"", full.names = TRUE) + x <- lapply(file, readRDS) + x <- do.call(rbind, x) + if (is.null(x$i2)) + x$i2 <- NA + return(x) + } + resultsNcs <- lapply(c(outputFolders, maOutputFolder), loadResultsNcs) + resultsNcs <- do.call(rbind, resultsNcs) + resultsNcs <- merge(resultsNcs, unique(results[, c(""targetId"", ""comparatorId"", ""comparison"")])) + resultsNcs$outcomeName <- ""Negative control"" + + + allResults <- rbind(results[, c(""comparison"", ""outcomeName"", ""logRr"", ""seLogRr"", ""database"")], + resultsNcs[, c(""comparison"", ""outcomeName"", ""logRr"", ""seLogRr"", ""database"")]) + + comparisonsOfInterest <- c(""canagliflozin - any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA"", + ""canagliflozin - any DPP-4 inhibitor, GLP-1 agonist, or other select AHA"", + ""canagliflozin - empagliflozin or dapagliflozin"", + ""empagliflozin or dapagliflozin - any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA"") + subset <- allResults[allResults$comparison %in% comparisonsOfInterest, ] + formatQuestion <- function(x) { + result <- rep(""canagliflozin vs.\n other SGLT2i"", length(x)) + result[x == ""canagliflozin - any DPP-4 inhibitor, GLP-1 agonist, or other select AHA""] <- ""canagliflozin vs.\n select non-SGLT2i"" + result[x == ""empagliflozin or dapagliflozin - any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA""] <- ""other SGLT2i vs\n. all non-SGLT2"" + result[x == ""canagliflozin - any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA""] <- ""canagliflozin vs.\n all non-SGLT2i"" + return(result) + } + subset$comparison <- formatQuestion(subset$comparison) + + subset$dummy <- 1 + temp1 <- aggregate(dummy ~ comparison + outcomeName, data = subset, sum) + temp1$nLabel <- paste0(formatC(temp1$dummy, big.mark = "","", format = ""d""), "" estimates"") + temp1$dummy <- NULL + subset$Significant <- abs(subset$logRr) > qnorm(0.975)*subset$seLogRr + temp2 <- aggregate(Significant~ comparison + outcomeName, data = subset, mean) + temp2$meanLabel <- paste0(formatC(100 * (1-temp2$Significant), digits = 1, format = ""f""), ""% of CIs include 1"") + temp2$Significant <- NULL + dd <- merge(temp1, temp2) + + + library(ggplot2) + breaks <- c(0.1, 0.25, 0.5, 1, 2, 4, 6, 8, 10) + theme <- element_text(colour = ""#000000"", size = 12) + themeRA <- element_text(colour = ""#000000"", size = 12, hjust = 1) + themeLA <- element_text(colour = ""#000000"", size = 12, hjust = 0) + plot <- ggplot(subset, aes(x=logRr, y=seLogRr), environment=environment())+ + geom_vline(xintercept=log(breaks), colour =""#AAAAAA"", lty=1, size=0.5) + + geom_abline(slope = 1/qnorm(0.025), colour=rgb(0.8,0,0), linetype=""dashed"", size=1,alpha=0.5) + + geom_abline(slope = 1/qnorm(0.975), colour=rgb(0.8,0,0), linetype=""dashed"", size=1,alpha=0.5) + + geom_point(size=1, color = rgb(0,0,0), shape = 16, aes(alpha = outcomeName)) + + geom_hline(yintercept=0) + + geom_label(x = log(0.11), y = 0.99, alpha = 1, hjust = ""left"", aes(label = nLabel), size = 5, data = dd) + + geom_label(x = log(0.11), y = 0.88, alpha = 1, hjust = ""left"", aes(label = meanLabel), size = 5, data = dd) + + scale_x_continuous(""Hazard ratio"",limits = log(c(0.1,10)), breaks=log(breaks),labels=breaks) + + scale_y_continuous(""Standard Error"",limits = c(0,1)) + + facet_grid(comparison~outcomeName) + + scale_alpha_manual(values = c(0.4, 0.4, 0.1)) + + theme( + panel.grid.minor = element_blank(), + panel.background= element_blank(), + panel.grid.major= element_blank(), + axis.ticks = element_blank(), + axis.text.y = themeRA, + axis.text.x = theme, + legend.key= element_blank(), + strip.text.x = theme, + strip.text.y = theme, + strip.background = element_blank(), + legend.position = ""none"" + ) + fileName <- file.path(reportFolder, ""EstimateScatterPlot.png"") + ggsave(plot = plot, fileName, width = 14, height = 10, dpi = 500) + + # Primary analysis only ---------------------------- + createPlot <- function(data, fileName) { + plot <- ggplot(data, aes(x=logRr, y=seLogRr), environment=environment())+ + geom_vline(xintercept=log(breaks), colour =""#AAAAAA"", lty=1, size=0.5) + + geom_abline(slope = 1/qnorm(0.025), colour=rgb(0.8,0,0), linetype=""dashed"", size=1,alpha=0.5) + + geom_abline(slope = 1/qnorm(0.975), colour=rgb(0.8,0,0), linetype=""dashed"", size=1,alpha=0.5) + + geom_point(size=2, color = rgb(0,0,0), shape = 16) + + geom_hline(yintercept=0) + + scale_x_continuous(""Hazard ratio"",limits = log(c(0.1,10)), breaks=log(breaks),labels=breaks) + + scale_y_continuous(""Standard Error"",limits = c(0,1)) + + facet_grid(.~outcomeName) + + theme( + panel.grid.minor = element_blank(), + panel.background= element_blank(), + panel.grid.major= element_blank(), + axis.ticks = element_blank(), + axis.text.y = themeRA, + axis.text.x = theme, + legend.key= element_blank(), + strip.text.x = theme, + strip.text.y = theme, + strip.background = element_blank(), + legend.position = ""none"" + ) + ggsave(plot = plot, fileName, width = 7, height = 4, dpi = 500) + } + primary <- results[results$comparison == ""canagliflozin - any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA"" & + results$establishedCvd == ""not required"" & + results$priorExposure == ""no restrictions"" & + !grepl(""no censor at switch"", results$timeAtRisk) & + !grepl(""Meta-analysis"", results$database) & + results$analysisId == 2, ] + + createPlot(primary[primary$outcomeId == 5432, ], file.path(reportFolder, ""EstimateScatterPlot_CanaVsNonSglt2_HeartFailure.png"")) + createPlot(primary[primary$outcomeId == 5433, ], file.path(reportFolder, ""EstimateScatterPlot_CanaVsNonSglt2_BkleAmpuation.png"")) + + primary <- results[results$comparison == ""canagliflozin - empagliflozin or dapagliflozin"" & + results$establishedCvd == ""not required"" & + results$priorExposure == ""no restrictions"" & + !grepl(""no censor at switch"", results$timeAtRisk) & + !grepl(""Meta-analysis"", results$database) & + results$analysisId == 2, ] + + createPlot(primary[primary$outcomeId == 5432, ], file.path(reportFolder, ""EstimateScatterPlot_CanaVsOtherSglt2_HeartFailure.png"")) + createPlot(primary[primary$outcomeId == 5433, ], file.path(reportFolder, ""EstimateScatterPlot_CanaVsOtherSglt2_BkleAmpuation.png"")) + + + + + plot <- ggplot(primary[primary$outcomeId == 5433, ], aes(x=logRr, y=seLogRr), environment=environment())+ + geom_vline(xintercept=log(breaks), colour =""#AAAAAA"", lty=1, size=0.5) + + geom_abline(slope = 1/qnorm(0.025), colour=rgb(0.8,0,0), linetype=""dashed"", size=1,alpha=0.5) + + geom_abline(slope = 1/qnorm(0.975), colour=rgb(0.8,0,0), linetype=""dashed"", size=1,alpha=0.5) + + geom_point(size=2, color = rgb(0,0,0), shape = 16) + + geom_hline(yintercept=0) + + scale_x_continuous(""Hazard ratio"",limits = log(c(0.1,10)), breaks=log(breaks),labels=breaks) + + scale_y_continuous(""Standard Error"",limits = c(0,1)) + + facet_grid(.~outcomeName) + + theme( + panel.grid.minor = element_blank(), + panel.background= element_blank(), + panel.grid.major= element_blank(), + axis.ticks = element_blank(), + axis.text.y = themeRA, + axis.text.x = theme, + legend.key= element_blank(), + strip.text.x = theme, + strip.text.y = theme, + strip.background = element_blank(), + legend.position = ""none"" + ) + fileName <- file.path(reportFolder, ""EstimateScatterPlot_BKLEAmputation.png"") + ggsave(plot = plot, fileName, width = 7, height = 4, dpi = 500) +} + +pot3DScatter <- function() { + loadResultsHois <- function(outputFolder, fileName) { + shinyDataFolder <- file.path(outputFolder, ""results"", ""shinyData"") + file <- list.files(shinyDataFolder, pattern = ""resultsHois_.*.rds"", full.names = TRUE) + x <- lapply(file, readRDS) + x <- do.call(rbind, x) + if (is.null(x$i2)) + x$i2 <- NA + return(x) + } + results <- lapply(c(outputFolders, maOutputFolder), loadResultsHois) + results <- do.call(rbind, results) + results$comparison <- paste(results$targetDrug, results$comparatorDrug, sep = "" - "") + comparisonsOfInterest <- c(""canagliflozin - any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA"", + ""canagliflozin - any DPP-4 inhibitor, GLP-1 agonist, or other select AHA"", + ""canagliflozin - empagliflozin or dapagliflozin"", + ""empagliflozin or dapagliflozin - any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA"") + subset <- results[results$comparison %in% comparisonsOfInterest, ] + + formatQuestion <- function(x) { + result <- rep(""canagliflozin vs. other SGLT2i"", length(x)) + result[x == ""canagliflozin - any DPP-4 inhibitor, GLP-1 agonist, or other select AHA""] <- ""canagliflozin vs. select non-SGLT2i"" + result[x == ""empagliflozin or dapagliflozin - any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA""] <- ""other SGLT2i vs. all non-SGLT2"" + result[x == ""canagliflozin - any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA""] <- ""canagliflozin vs. all non-SGLT2i"" + return(result) + } + subset$comparison <- formatQuestion(subset$comparison) + subset <- subset[!is.na(subset$seLogRr), ] + subset <- subset[subset$seLogRr < 1, ] + subset <- subset[abs(subset$logRr) < 3, ] + idx <- subset$comparison == ""canagliflozin vs. all non-SGLT2i"" + + d1 <- data.frame(logRr1 = subset$logRr[idx], + seLogRr1 = subset$seLogRr[idx], + outcomeName = subset$outcomeName[idx], + targetId = subset$targetId[idx], + analysisId = subset$analysisId[idx], + database = subset$database[idx]) + idx <- subset$comparison == ""canagliflozin vs. other SGLT2i"" + d2 <- data.frame(logRr2 = subset$logRr[idx], + seLogRr2 = subset$seLogRr[idx], + outcomeName = subset$outcomeName[idx], + targetId = subset$targetId[idx], + analysisId = subset$analysisId[idx], + database = subset$database[idx]) + d <- merge(d1, d2) + d <- d[!is.na(d$seLogRr1) & !is.na(d$seLogRr2), ] + + library(scatterplot3d) + + + plot(d$seLogRr1, d$seLogRr2) + cor(d$seLogRr1, d$seLogRr2) + plot(d$logRr1, d$logRr2) + cor(d$logRr1, d$logRr2) + idx <- d$outcomeName == ""Heart failure"" + s3d <- scatterplot3d(d$logRr1[idx], d$logRr2[idx], d$seLogRr1[idx], col.axis = ""blue"", + col.grid = ""lightblue"", main = ""Helix"", pch = 16, color = ""#66000066"", size = 2) + idx <- d$outcomeName == ""BKLE amputation"" + s3d$points3d(d$logRr1[idx], d$logRr2[idx], d$seLogRr1[idx], pch = 16, col = ""#00006666"", size = 2) + + d$o <- as.numeric(d$outcomeName == ""Heart failure"") + d$z <- (max(d$logRr2) - d$logRr2) / (max(d$logRr2) - min(d$logRr2)) + d$color <- hsv(0 + d$o*0.667, d$z^2, 0.5, alpha = 0.5) + scatterplot3d(d$logRr1, d$logRr2, d$seLogRr1, col.axis = ""blue"", + col.grid = ""lightblue"", main = ""Helix"", pch = 16, color = d$color, cex.symbols = 2) +} + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AhasHfBkleAmputation/extras/PackageMaintenance.R",".R","5678","115","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of AhasHfBkleAmputation +# +# 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. + +# Format and check code --------------------------------------------------- +OhdsiRTools::formatRFolder() +OhdsiRTools::checkUsagePackage(""AhasHfBkleAmputation"") +OhdsiRTools::updateCopyrightYearFolder() + +# Create manual ----------------------------------------------------------- +shell(""rm extras/AhasHfBkleAmputation.pdf"") +shell(""R CMD Rd2pdf ./ --output=extras/AhasHfBkleAmputation.pdf"") + +# Insert cohort definitions from ATLAS into package ----------------------- +OhdsiRTools::insertCohortDefinitionSetInPackage(fileName = ""CohortsToCreateWithCensoring.csv"", + baseUrl = Sys.getenv(""baseUrl""), + insertTableSql = TRUE, + insertCohortCreationR = TRUE, + generateStats = FALSE, + packageName = ""AhasHfBkleAmputation"") + +# Hack: get names and excluded concepts for comparisons from ATLAS ---------- +tcos <- read.csv(""inst/settings/TcosOfInterestWithCensoring.csv"", stringsAsFactors = FALSE) +cohorts <- read.csv(""inst/settings/CohortsToCreateWithCensoring.csv"", stringsAsFactors = FALSE) +tcos <- merge(tcos, data.frame(targetId = cohorts$cohortId, + targetName = cohorts$fullName)) +tcos <- merge(tcos, data.frame(comparatorId = cohorts$cohortId, + comparatorName = cohorts$fullName)) +getPrimaryConcepts <- function(fileName) { + json <- readChar(fileName, file.info(fileName)$size) + x <- RJSONIO::fromJSON(json) + id <- x$PrimaryCriteria$CriteriaList[[1]]$DrugExposure$CodesetId + for (i in 1:length(x$ConceptSets)) + if (x$ConceptSets[[i]]$id == id) { + conceptIds <- c() + for (item in x$ConceptSets[[i]]$expression$items) + conceptIds <- c(conceptIds, item$concept$CONCEPT_ID) + return(conceptIds) + } + stop(""No primary concept found"") +} +for (i in 1:nrow(tcos)) { + targetName <- paste0(""inst/cohorts/"", cohorts$name[cohorts$cohortId == tcos$targetId[i]], "".json"") + comparatorName <- paste0(""inst/cohorts/"", cohorts$name[cohorts$cohortId == tcos$comparatorId[i]], "".json"") + excludeIds <- c() + excludeIds <- c(excludeIds, getPrimaryConcepts(targetName)) + excludeIds <- c(excludeIds, getPrimaryConcepts(comparatorName)) + tcos$excludedCovariateConceptIds[i] <- paste(excludeIds, collapse = "";"") +} +write.csv(tcos, ""inst/settings/TcosOfInterestWithCensoring.csv"", row.names = FALSE) + +# Create exposure cohorts without censoring by modifying cohorts with censoring ---------------- +baseUrl <- Sys.getenv(""baseUrl"") +tcos <- read.csv(""inst/settings/TcosOfInterestWithCensoring.csv"", stringsAsFactors = FALSE) +cohorts <- read.csv(""inst/settings/CohortsToCreateWithCensoring.csv"", stringsAsFactors = FALSE) +exposureCohortIds <- unique(c(tcos$targetId, tcos$comparatorId)) +newCohorts <- list(cohorts) +for (exposureCohortId in exposureCohortIds) { + cohort <- cohorts[cohorts$cohortId == exposureCohortId, ] + writeLines(paste(""Dropping censoring criteria for"", cohort$fullName)) + cohortDef <- RJSONIO::fromJSON(file.path(""inst"", ""cohorts"", paste0(cohort$name, "".json""))) + + cohort$cohortId <- exposureCohortId + 10000 + cohort$atlasId <- NA + cohort$name <- paste0(cohort$name, ""NoCensor"") + cohort$fullName <- paste0(cohort$fullName, "", no censoring"") + newCohorts[[length(newCohorts) + 1]] <- cohort + + # Drop censoring criteria + cohortDef$CensoringCriteria <- NULL + fileConn <- file(file.path(""inst/cohorts"", paste(cohort$name, ""json"", sep = "".""))) + writeLines(RJSONIO::toJSON(cohortDef), fileConn) + close(fileConn) + jsonBody <- RJSONIO::toJSON(list(expression = cohortDef), digits = 23) + httpheader <- c(Accept = ""application/json; charset=UTF-8"", `Content-Type` = ""application/json"") + url <- paste(baseUrl, ""cohortdefinition"", ""sql"", sep = ""/"") + cohortSqlJson <- httr::POST(url, body = jsonBody, config = httr::add_headers(httpheader)) + cohortSqlJson <- httr::content(cohortSqlJson) + sql <- cohortSqlJson$templateSql + fileConn <- file(file.path(""inst/sql/sql_server"", paste(cohort$name, ""sql"", sep = "".""))) + writeLines(sql, fileConn) + close(fileConn) +} +cohorts <- do.call(rbind, newCohorts) +write.csv(cohorts, ""inst/settings/CohortsToCreate.csv"", row.names = FALSE) +newTcos <- tcos +newTcos$targetId <- 10000 + newTcos$targetId +newTcos$comparatorId <- 10000 + newTcos$comparatorId +newTcos$targetName <- paste0(newTcos$targetName, "", no censoring"") +newTcos$comparatorName <- paste0(newTcos$comparatorName, "", no censoring"") +newTcos$censorAtSwitch <- FALSE +tcos$censorAtSwitch <- TRUE +tcos <- rbind(tcos, newTcos) +write.csv(tcos, ""inst/settings/TcosOfInterest.csv"", row.names = FALSE) + +# Create analysis details ------------------------------------------------- +source(""R/CreateStudyAnalysisDetails.R"") +createAnalysesDetails(""inst/settings/"") + +# Store environment in which the study was executed ----------------------- +OhdsiRTools::insertEnvironmentSnapshotInPackage(""AhasHfBkleAmputation"") + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AhasHfBkleAmputation/extras/EvaluateTimeAtRiskWithoutCensorAtSwitch.R",".R","6286","130","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of AhasHfBkleAmputation +# +# 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. + +cohortTable2 <- paste0(cohortTable, ""_noCensor"") +noCensorFolder <- file.path(outputFolder, ""noCensor"") + +if (!file.exists(noCensorFolder)) + dir.create(noCensorFolder) + +pathToCsv <- system.file(""settings"", ""TcosOfInterest.csv"", package = ""AhasHfBkleAmputation"") +tcosOfInterest <- read.csv(pathToCsv, stringsAsFactors = FALSE) +cohortIds <- unique(c(tcosOfInterest$targetId, tcosOfInterest$comparatorId)) + +pathToCsv <- system.file(""settings"", ""CohortsToCreate.csv"", package = ""AhasHfBkleAmputation"") +cohortsToCreate <- read.csv(pathToCsv, stringsAsFactors = FALSE) +cohortsToCreate <- cohortsToCreate[cohortsToCreate$cohortId %in% cohortIds, ] + +# Create new cohort table with modified cohorts ----------------------------------------------- +connection <- DatabaseConnector::connect(connectionDetails) +sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""CreateCohortTable.sql"", + packageName = ""AhasHfBkleAmputation"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + cohort_database_schema = cohortDatabaseSchema, + cohort_table = cohortTable2) +DatabaseConnector::executeSql(connection, sql, progressBar = FALSE, reportOverallTime = FALSE) + +# baseUrl = Sys.getenv(""baseUrl"") +# definitionId <- cohortsToCreate$atlasId[1] +# cohortId <- cohortsToCreate$cohortId[1] +createModifiedCohortDefinition <- function(definitionId, + cohortId, + baseUrl, + connection, + cdmDatabaseSchema, + oracleTempSchema, + cohortDatabaseSchema, + cohortTable2) { + ### Fetch JSON object ### + url <- paste(baseUrl, ""cohortdefinition"", definitionId, sep = ""/"") + json <- httr::GET(url) + json <- httr::content(json) + name <- json$name + parsedExpression <- RJSONIO::fromJSON(json$expression) + + # Drop censoring criteria + parsedExpression$CensoringCriteria <- NULL + + ### Fetch SQL by posting JSON object ### + jsonBody <- RJSONIO::toJSON(list(expression = parsedExpression), digits = 23) + httpheader <- c(Accept = ""application/json; charset=UTF-8"", `Content-Type` = ""application/json"") + url <- paste(baseUrl, ""cohortdefinition"", ""sql"", sep = ""/"") + cohortSqlJson <- httr::POST(url, body = jsonBody, config = httr::add_headers(httpheader)) + cohortSqlJson <- httr::content(cohortSqlJson) + sql <- cohortSqlJson$templateSql + sql <- SqlRender::renderSql(sql = sql, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = cohortDatabaseSchema, + target_cohort_table = cohortTable2, + target_cohort_id = cohortId)$sql + sql <- SqlRender::translateSql(sql, + targetDialect = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema)$sql + DatabaseConnector::executeSql(connection, sql) +} + +for (i in 1:nrow(cohortsToCreate)) { + writeLines(paste(""Creating modified cohort"", cohortsToCreate$name[i])) + createModifiedCohortDefinition(definitionId = cohortsToCreate$atlasId[i], + cohortId = cohortsToCreate$cohortId[i], + baseUrl = Sys.getenv(""baseUrl""), + connection = connection, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable2 = cohortTable2) +} +DatabaseConnector::disconnect(connection) + +# Get cohort statistics ----------------------------------------------- +connection <- DatabaseConnector::connect(connectionDetails) +templateSql <- ""SELECT DATEDIFF(DAY, cohort_start_date, cohort_end_date) AS days FROM @cohort_database_schema.@cohort_table WHERE cohort_definition_id = @cohort_id"" +results <- data.frame(cohortId = rep(cohortsToCreate$atlasId, 2), + cohortName = rep(cohortsToCreate$fullName, 2), + type = rep(c(""Modified"", ""Original""), each = nrow(cohortsToCreate))) + +for (i in 1:nrow(results)) { + if (results$type[i] == ""Original"") { + table <- cohortTable + } else { + table <- cohortTable2 + } + sql <- SqlRender::renderSql(sql = templateSql, + cohort_database_schema = cohortDatabaseSchema, + cohort_table = table, + cohort_id = results$cohortId[i])$sql + sql <- SqlRender::translateSql(sql, + targetDialect = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema)$sql + days <- DatabaseConnector::querySql(connection, sql) + days <- days$DAYS + q <- quantile(days, c(0, 0.1, 0.25, 0.5, 0.75, 0.9, 1)) + results$count[i] <- length(days) + results$mean[i] <- mean(days) + results$sd[i] <- sd(days) + results$min[i] <- q[1] + results$p10[i] <- q[2] + results$p25[i] <- q[3] + results$median[i] <- q[4] + results$p50[i] <- q[5] + results$p90[i] <- q[6] + results$max[i] <- q[7] +} +DatabaseConnector::disconnect(connection) + +write.csv(results, file.path(noCensorFolder, ""tarDist.csv""), row.names = FALSE) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AhasHfBkleAmputation/extras/InstallPackages.R",".R","368","11","devtools::install_github(""ohdsi/SqlRender"") +devtools::install_github(""ohdsi/DatabaseConnector"") +devtools::install_github(""ohdsi/EmpiricalCalibration"") +devtools::install_github(""ohdsi/OhdsiRTools"") +devtools::install_github(""ohdsi/FeatureExtraction"") +devtools::install_github(""ohdsi/CohortMethod"", ref = ""develop"") +devtools::install_github(""ohdsi/EvidenceSynthesis"") + + + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AhasHfBkleAmputation/extras/CodeToRun.R",".R","3905","93","library(AhasHfBkleAmputation) +options(fftempdir = ""r:/FFtemp"") + +maxCores <- 30 +studyFolder <- ""r:/AhasHfBkleAmputation"" +dbms <- ""pdw"" +user <- NULL +pw <- NULL +server <- Sys.getenv(""PDW_SERVER"") +port <- Sys.getenv(""PDW_PORT"") +oracleTempSchema <- NULL +connectionDetails <- DatabaseConnector::createConnectionDetails(dbms = dbms, + server = server, + user = user, + password = pw, + port = port) + +# CCAE settings ---------------------------------------------------------------- +cdmDatabaseSchema <- ""cdm_truven_ccae_v656.dbo"" +cohortDatabaseSchema <- ""scratch.dbo"" +cohortTable <- ""epi501_ccae"" +databaseName <- ""CCAE"" +outputFolder <- file.path(studyFolder, ""ccae"") + +# MDCD settings ---------------------------------------------------------------- +cdmDatabaseSchema <- ""CDM_Truven_MDCD_V635.dbo"" +cohortDatabaseSchema <- ""scratch.dbo"" +cohortTable <- ""epi501_mdcd"" +databaseName <- ""MDCD"" +outputFolder <- file.path(studyFolder, ""mdcd"") + +# MDCR settings ---------------------------------------------------------------- +cdmDatabaseSchema <- ""cdm_truven_mdcr_v657.dbo"" +cohortDatabaseSchema <- ""scratch.dbo"" +cohortTable <- ""epi501_mdcr"" +databaseName <- ""MDCR"" +outputFolder <- file.path(studyFolder, ""mdcr"") + +# Optum settings ---------------------------------------------------------------- +cdmDatabaseSchema <- ""cdm_optum_extended_dod_v654.dbo"" +cohortDatabaseSchema <- ""scratch.dbo"" +cohortTable <- ""epi501_optum"" +databaseName <- ""Optum"" +outputFolder <- file.path(studyFolder, ""optum"") + + +mailSettings <- list(from = Sys.getenv(""mailAddress""), + to = c(Sys.getenv(""mailAddress"")), + smtp = list(host.name = ""smtp.gmail.com"", port = 465, + user.name = Sys.getenv(""mailAddress""), + passwd = Sys.getenv(""mailPassword""), ssl = TRUE), + authenticate = TRUE, + send = TRUE) + +result <- OhdsiRTools::runAndNotify({ + execute(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder, + databaseName = databaseName, + createCohorts = FALSE, + runAnalyses = FALSE, + getPriorExposureData = TRUE, + runDiagnostics = FALSE, + prepareResults = TRUE, + maxCores = maxCores) +}, mailSettings = mailSettings, label = ""AhasHfBkleAmputation"") + + +doMetaAnalysis(outputFolders = c(file.path(studyFolder, ""ccae""), + file.path(studyFolder, ""mdcd""), + file.path(studyFolder, ""mdcr""), + file.path(studyFolder, ""optum"")), + maOutputFolder = file.path(studyFolder, ""metaAnalysis""), + maxCores = maxCores) + +createTableAndFiguresForReport(outputFolders = c(file.path(studyFolder, ""ccae""), + file.path(studyFolder, ""mdcd""), + file.path(studyFolder, ""mdcr""), + file.path(studyFolder, ""optum"")), + databaseNames = c(""CCAE"", ""MDCD"", ""MDCR"", ""Optum""), + maOutputFolder = file.path(studyFolder, ""metaAnalysis""), + reportFolder = file.path(studyFolder, ""report"")) + + + +outputFolders = c(file.path(studyFolder, ""ccae""), + file.path(studyFolder, ""mdcr""), + file.path(studyFolder, ""optum"")) +databaseNames = c(""CCAE"", ""MDCR"", ""Optum"") +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AhasHfBkleAmputation/extras/CopyCensoredToUncensoredDataObjects.R",".R","2617","50","# This code generates CohortMethod data objects for cohorts without censoring by modifying objects for cohorts with censoring + +cmOutputFolder <- file.path(outputFolder, ""cmOutput"") + +connection <- DatabaseConnector::connect(connectionDetails) +tcos <- read.csv(""inst/settings/TcosOfInterest.csv"", stringsAsFactors = FALSE) +tcosWithCensoring <- tcos[tcos$censorAtSwitch, ] +for (i in 1:nrow(tcosWithCensoring)) { + targetId <- tcosWithCensoring$targetId[i] + comparatorId <- tcosWithCensoring$comparatorId[i] + newTargetId <- 10000 + targetId + newComparatorId <- 10000 + comparatorId + + # Copy cohortMethodData object ------------------------------------------------------------------- + sourceFileName <- file.path(cmOutputFolder, sprintf(""CmData_l1_t%s_c%s"", targetId, comparatorId)) + cmData <- CohortMethod::loadCohortMethodData(sourceFileName) + sql <- ""SELECT subject_id, + cohort_start_date, + DATEDIFF(DAY, cohort_start_date, cohort_end_date) AS days_to_cohort_end, + CASE WHEN cohort_definition_id = @target_id THEN 1 ELSE 0 END AS treatment + FROM @cohort_database_schema.@cohort_table + WHERE cohort_definition_id IN (@target_id, @comparator_id)"" + sql <- SqlRender::renderSql(sql = sql, + cohort_database_schema = cohortDatabaseSchema, + cohort_table = cohortTable, + target_id = newTargetId, + comparator_id = newComparatorId)$sql + sql <- SqlRender::translateSql(sql = sql, targetDialect = connectionDetails$dbms, oracleTempSchema = oracleTempSchema)$sql + newCohorts <- DatabaseConnector::querySql(connection, sql) + colnames(newCohorts) <- SqlRender::snakeCaseToCamelCase(colnames(newCohorts)) + cmData$cohorts$daysToCohortEnd <- NULL + cmData$cohorts <- merge(cmData$cohorts, newCohorts, all.x = TRUE) + if (any(is.na(cmData$cohorts$daysToCohortEnd))) + stop(""Cohort mismatch"") + targetFileName <- file.path(cmOutputFolder, sprintf(""CmData_l1_t%s_c%s"", newTargetId, newComparatorId)) + CohortMethod::saveCohortMethodData(cmData, targetFileName) + writeLines(paste(""Created object"", targetFileName)) + + # Copy shared PS object -------------------------------------------------------------------------- + sourceFileName <- file.path(cmOutputFolder, sprintf(""Ps_l1_p1_t%s_c%s.rds"", targetId, comparatorId)) + ps <- readRDS(sourceFileName) + targetFileName <- file.path(cmOutputFolder, sprintf(""Ps_l1_p1_t%s_c%s.rds"", newTargetId, newComparatorId)) + saveRDS(ps, targetFileName) + writeLines(paste(""Created object"", targetFileName)) +} + +DatabaseConnector::disconnect(connection) + + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AhasHfBkleAmputation/extras/EvidenceExplorer/global.R",".R","2937","62","blind <- FALSE + +fileNames <- list.files(path = ""data"", pattern = ""resultsHois_.*.rds"", full.names = TRUE) +resultsHois <- lapply(fileNames, readRDS) +allColumns <- unique(unlist(lapply(resultsHois, colnames))) +addMissingColumns <- function(results) { + presentCols <- colnames(results) + missingCols <- allColumns[!(allColumns %in% presentCols)] + for (missingCol in missingCols) { + results[, missingCol] <- rep(NA, nrow(results)) + } + return(results) +} +resultsHois <- lapply(resultsHois, addMissingColumns) +resultsHois <- do.call(rbind, resultsHois) + +fileNames <- list.files(path = ""data"", pattern = ""resultsNcs_.*.rds"", full.names = TRUE) +resultsNcs <- lapply(fileNames, readRDS) +resultsNcs <- do.call(rbind, resultsNcs) + +fileNames <- list.files(path = ""data"", pattern = ""covarNames_.*.rds"", full.names = TRUE) +covarNames <- lapply(fileNames, readRDS) +covarNames <- do.call(rbind, covarNames) +covarNames <- unique(covarNames) + +formatDrug <- function(x) { + result <- x + result[x == ""empagliflozin or dapagliflozin""] <- ""other SGLT2i"" + result[x == ""any DPP-4 inhibitor, GLP-1 agonist, or other select AHA""] <- ""select non-SGLT2i"" + result[x == ""any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA""] <- ""all non-SGLT2i"" + return(result) +} +resultsHois$targetDrug <- formatDrug(resultsHois$targetDrug) +resultsHois$comparatorDrug <- formatDrug(resultsHois$comparatorDrug) +resultsHois$comparison <- paste(resultsHois$targetDrug, resultsHois$comparatorDrug, sep = "" vs. "") + +comparisons <- unique(resultsHois$comparison) +comparisons <- comparisons[order(comparisons)] +outcomes <- unique(resultsHois$outcomeName) +establishCvds <- unique(resultsHois$establishedCvd) +priorExposures <- unique(resultsHois$priorExposure) +timeAtRisks <- unique(resultsHois$timeAtRisk) +timeAtRisks <- timeAtRisks[order(timeAtRisks)] +evenTypes <- unique(resultsHois$evenType) +psStrategies <- unique(resultsHois$psStrategy) +dbs <- unique(resultsHois$database) + +heterogeneous <- resultsHois[resultsHois$database == ""Meta-analysis (DL)"" & !is.na(resultsHois$i2) & resultsHois$i2 > 0.4, c(""targetId"", ""comparatorId"", ""outcomeId"", ""analysisId"")] +heterogeneous$heterogeneous <- ""yes"" +resultsHois <- merge(resultsHois, heterogeneous, all.x = TRUE) +resultsHois$heterogeneous[is.na(resultsHois$heterogeneous)] <- """" + +dbInfoHtml <- readChar(""DataSources.html"", file.info(""DataSources.html"")$size) +comparisonsInfoHtml <- readChar(""Comparisons.html"", file.info(""Comparisons.html"")$size) +outcomesInfoHtml <- readChar(""Outcomes.html"", file.info(""Outcomes.html"")$size) +cvdInfoHtml <- readChar(""Cvd.html"", file.info(""Cvd.html"")$size) +priorExposureInfoHtml <- readChar(""PriorExposure.html"", file.info(""PriorExposure.html"")$size) +tarInfoHtml <- readChar(""Tar.html"", file.info(""Tar.html"")$size) +eventInfoHtml <- readChar(""Event.html"", file.info(""Event.html"")$size) +psInfoHtml <- readChar(""Ps.html"", file.info(""Ps.html"")$size) + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AhasHfBkleAmputation/extras/EvidenceExplorer/server.R",".R","24361","591","library(shiny) +library(DT) +library(ggplot2) +source(""functions.R"") +source(""Table1.R"") + +mainColumns <- c(""establishedCvd"", + ""priorExposure"", + ""timeAtRisk"", + ""evenType"", + ""psStrategy"", + ""database"", + ""heterogeneous"", + ""rr"", + ""ci95lb"", + ""ci95ub"", + ""p"", + ""calP"") + +mainColumnNames <- c(""Est. CVD"", + ""Prior Exposure"", + ""Time at risk"", + ""Event"", + ""PS strategy"", + ""Data source"", + "" 0.4)?\"">Ht."", + ""HR"", + ""CI95LB"", + ""CI95UB"", + ""P"", + ""Cal. P"") + +powerColumns <- c(""treated"", + ""comparator"", + ""treatedDays"", + ""comparatorDays"", + ""eventsTreated"", + ""eventsComparator"", + ""irTreated"", + ""irComparator"", + ""mdrr"") + +powerColumnNames <- c(""Target subjects"", + ""Comparator subjects"", + ""Target days"", + ""Comparator days"", + ""Target events"", + ""Comparator events"", + ""Target IR (per 1,000 PY)"", + ""Comparator IR (per 1,000 PY)"", + ""MDRR"") + +shinyServer(function(input, output) { + + tableSubset <- reactive({ + idx <- resultsHois$comparison == input$comparison & + resultsHois$outcomeName == input$outcome & + resultsHois$establishedCvd %in% input$establishedCVd & + resultsHois$priorExposure %in% input$priorExposure & + resultsHois$timeAtRisk %in% input$timeAtRisk & + resultsHois$evenType %in% input$evenType & + resultsHois$psStrategy %in% input$psStrategy & + resultsHois$database %in% input$db + resultsHois[idx, ] + }) + + selectedRow <- reactive({ + idx <- input$mainTable_rows_selected + if (is.null(idx)) { + return(NULL) + } else { + return(tableSubset()[idx, ]) + } + }) + + forestPlotSubset <- reactive({ + row <- selectedRow() + if (is.null(row)) { + return(NULL) + } else { + subset <- resultsHois[resultsHois$comparison == row$comparison & + resultsHois$outcomeId == row$outcomeId, ] + subset$dbOrder <- match(subset$database, c(""CCAE"", ""MDCD"",""MDCR"", ""Optum"", ""Meta-analysis (HKSJ)"", ""Meta-analysis (DL)"")) + subset$timeAtRiskOrder <- match(subset$timeAtRisk, c(""On Treatment"", + ""On Treatment (no censor at switch)"", + ""Lag"", + ""Lag (no censor at switch)"", + ""Intent to Treat"", + ""Modified ITT"")) + + subset <- subset[order(subset$dbOrder, + subset$timeAtRiskOrder, + subset$establishedCvd, + subset$evenType, + subset$psStrategy, + subset$priorExposure), ] + subset$rr[is.na(subset$seLogRr)] <- NA + formatTimeAtRisk <- function(x) { + result <- x + result[x == ""Intent to Treat""] <- ""Intent-to-treat"" + result[x == ""On Treatment""] <- ""On treatment"" + result[x == ""On Treatment (no censor at switch)""] <- ""On treatment (no censor at switch)"" + result[x == ""Lag""] <- ""On treatment lagged"" + result[x == ""Lag (no censor at switch)""] <- ""On treatment lagged (no censor at switch)"" + return(result) + } + subset$timeAtRisk <- formatTimeAtRisk(subset$timeAtRisk) + subset$database <- factor(subset$database, levels = c(""CCAE"", ""MDCD"",""MDCR"", ""Optum"", ""Meta-analysis (HKSJ)"", ""Meta-analysis (DL)"")) + subset$timeAtRisk <- factor(subset$timeAtRisk, levels = c(""On treatment"", ""On treatment (no censor at switch)"", ""On treatment lagged"", ""On treatment lagged (no censor at switch)"", ""Intent-to-treat"", ""Modified ITT"")) + subset$displayOrder <- nrow(subset):1 + return(subset) + } + }) + + output$rowIsSelected <- reactive({ + return(!is.null(selectedRow())) + }) + outputOptions(output, ""rowIsSelected"", suspendWhenHidden = FALSE) + + output$isMetaAnalysis <- reactive({ + row <- selectedRow() + isMetaAnalysis <- !is.null(row) && (row$database == ""Meta-analysis (HKSJ)"" | row$database == ""Meta-analysis (DL)"") + if (isMetaAnalysis) { + hideTab(""tabsetPanel"", ""Population characteristics"") + hideTab(""tabsetPanel"", ""Propensity scores"") + hideTab(""tabsetPanel"", ""Covariate balance"") + hideTab(""tabsetPanel"", ""Kaplan-Meier"") + } else { + showTab(""tabsetPanel"", ""Population characteristics"") + showTab(""tabsetPanel"", ""Propensity scores"") + showTab(""tabsetPanel"", ""Covariate balance"") + showTab(""tabsetPanel"", ""Kaplan-Meier"") } + return(isMetaAnalysis) + }) + outputOptions(output, ""isMetaAnalysis"", suspendWhenHidden = FALSE) + + balance <- reactive({ + row <- selectedRow() + if (is.null(row) || row$database == ""Meta-analysis (HKSJ)"" || row$database == ""Meta-analysis (DL)"") { + return(NULL) + } else { + fileName <- paste0(""bal_a"",row$analysisId,""_t"",row$targetId,""_c"",row$comparatorId,""_o"",row$outcomeId,""_"",row$database,"".rds"") + data <- readRDS(file.path(""data"", fileName)) + data$absBeforeMatchingStdDiff <- abs(data$beforeMatchingStdDiff) + data$absAfterMatchingStdDiff <- abs(data$afterMatchingStdDiff) + data <- merge(data, covarNames) + return(data) + } + }) + + output$mainTable <- renderDataTable({ + table <- tableSubset()[, mainColumns] + if (nrow(table) == 0) + return(NULL) + table$rr[table$rr > 100] <- NA + table$rr <- formatC(table$rr, digits = 2, format = ""f"") + table$ci95lb <- formatC(table$ci95lb, digits = 2, format = ""f"") + table$ci95ub <- formatC(table$ci95ub, digits = 2, format = ""f"") + table$p <- formatC(table$p, digits = 2, format = ""f"") + table$calP <- formatC(table$calP, digits = 2, format = ""f"") + colnames(table) <- mainColumnNames + options = list(pageLength = 15, + searching = FALSE, + lengthChange = TRUE, + ordering = TRUE, + paging = TRUE) + selection = list(mode = ""single"", target = ""row"") + table <- datatable(table, + options = options, + selection = selection, + rownames = FALSE, + escape = FALSE, + class = ""stripe nowrap compact"") + return(table) + }) + + output$powerTableCaption <- renderUI({ + row <- selectedRow() + if (!is.null(row)) { + text <- ""Table 1a. Number of subjects, follow-up time (in days), number of outcome + events, and event incidence rate (IR) per 1,000 patient years (PY) in the target (%s) and + comparator (%s) group after %s, as well as the minimum detectable relative risk (MDRR). + Note that the IR does not account for any stratification."" + return(HTML(sprintf(text, row$targetDrug, row$comparatorDrug, tolower(row$psStrategy)))) + } else { + return(NULL) + } + }) + + output$powerTable <- renderTable({ + table <- selectedRow() + if (!is.null(table)) { + table$irTreated <- formatC(1000 * table$eventsTreated / (table$treatedDays / 365.25), digits = 2, format = ""f"") + table$irComparator <- formatC(1000 * table$eventsComparator / (table$comparatorDays / 365.25), digits = 2, format = ""f"") + + table$treated <- formatC(table$treated, big.mark = "","", format = ""d"") + table$comparator <- formatC(table$comparator, big.mark = "","", format = ""d"") + table$treatedDays <- formatC(table$treatedDays, big.mark = "","", format = ""d"") + table$comparatorDays <- formatC(table$comparatorDays, big.mark = "","", format = ""d"") + table$eventsTreated <- formatC(table$eventsTreated, big.mark = "","", format = ""d"") + table$eventsComparator <- formatC(table$eventsComparator, big.mark = "","", format = ""d"") + table$mdrr <- formatC(table$mdrr, digits = 2, format = ""f"") + if (table$database == ""Meta-analysis (HKSJ)"" || table$database == ""Meta-analysis (DL)"") { + table <- table[, c(powerColumns, ""i2"")] + colnames(table) <- c(powerColumnNames, ""I2"") + } else { + table <- table[, powerColumns] + colnames(table) <- powerColumnNames + } + return(table) + } else { + return(table) + } + }) + + output$timeAtRiskTableCaption <- renderUI({ + row <- selectedRow() + if (!is.null(row)) { + text <- ""Table 1b. Time (days) at risk distribution expressed as mean, standard deviation (SD), + minimum (min), 25th percentile (P25), median, 75th percentile (P75), and maximum (max) in the target + (%s) and comparator (%s) cohort after %s."" + return(HTML(sprintf(text, row$targetDrug, row$comparatorDrug, tolower(row$psStrategy)))) + } else { + return(NULL) + } + }) + + output$timeAtRiskTable <- renderTable({ + row <- selectedRow() + if (!is.null(table)) { + + table <- data.frame(Cohort = c(""Target"", ""Comparator""), + Mean = formatC(c(row$tarTargetMean, row$tarComparatorMean), digits = 1, format = ""f""), + SD = formatC(c(row$tarTargetSd, row$tarComparatorSd), digits = 1, format = ""f""), + Min = formatC(c(row$tarTargetMin, row$tarComparatorMin), big.mark = "","", format = ""d""), + P10 = formatC(c(row$tarTargetP10, row$tarComparatorP10), big.mark = "","", format = ""d""), + P25 = formatC(c(row$tarTargetP25, row$tarComparatorP25), big.mark = "","", format = ""d""), + Median = formatC(c(row$tarTargetMedian, row$tarComparatorMedian), big.mark = "","", format = ""d""), + P75 = formatC(c(row$tarTargetP75, row$tarComparatorP75), big.mark = "","", format = ""d""), + P90 = formatC(c(row$tarTargetP90, row$tarComparatorP90), big.mark = "","", format = ""d""), + Max = formatC(c(row$tarTargetMax, row$tarComparatorMax), big.mark = "","", format = ""d"")) + + return(table) + } else { + return(table) + } + }) + + output$table1Caption <- renderUI({ + bal <- balance() + if (!is.null(bal)) { + row <- selectedRow() + text <- ""Table 2. Select characteristics before and after %s, showing the (weighted) + percentage of subjects with the characteristics in the target (%s) and comparator (%s) group, as + well as the standardized difference of the means."" + return(HTML(sprintf(text, tolower(row$psStrategy), row$targetDrug, row$comparatorDrug))) + } else { + return(NULL) + } + }) + + output$table1Table <- renderDataTable({ + bal <- balance() + if (!is.null(bal)) { + row <- selectedRow() + fileName <- paste0(""ahaBal_a"",row$analysisId,""_t"",row$targetId,""_c"",row$comparatorId,""_o"",row$outcomeId,""_"",row$database,"".rds"") + priorAhaBalance <- readRDS(file.path(""data"", fileName)) + bal$absBeforeMatchingStdDiff <- NULL + bal$absAfterMatchingStdDiff <- NULL + priorAhaBalance <- priorAhaBalance[, colnames(bal)] + bal <- rbind(bal, priorAhaBalance) + table1 <- prepareTable1(bal, + beforeTargetPopSize = row$treatedBefore, + beforeComparatorPopSize = row$comparatorBefore, + afterTargetPopSize = row$treated, + afterComparatorPopSize = row$comparator, + beforeLabel = paste(""Before"", tolower(row$psStrategy)), + afterLabel = paste(""After"", tolower(row$psStrategy))) + container <- htmltools::withTags(table( + class = 'display', + thead( + tr( + th(rowspan = 3, ""Characteristic""), + th(colspan = 3, class = ""dt-center"", paste(""Before"", tolower(row$psStrategy))), + th(colspan = 3, class = ""dt-center"", paste(""After"", tolower(row$psStrategy))) + ), + tr( + lapply(table1[1, 2:ncol(table1)], th) + ), + tr( + lapply(table1[2, 2:ncol(table1)], th) + ) + ) + )) + options <- list(columnDefs = list(list(className = 'dt-right', targets = 1:6)), + searching = FALSE, + ordering = FALSE, + paging = FALSE, + bInfo = FALSE) + table1 <- datatable(table1[3:nrow(table1), ], + options = options, + rownames = FALSE, + escape = FALSE, + container = container, + class = ""stripe nowrap compact"") + return(table1) + } else { + return(NULL) + } + }) + + output$psPlot <- renderPlot({ + row <- selectedRow() + if (!is.null(row) && row$database != ""Meta-analysis (HKSJ)"" && row$database != ""Meta-analysis (DL)"") { + fileName <- paste0(""ps_a"",row$analysisId,""_t"",row$targetId,""_c"",row$comparatorId,""_"",row$database,"".rds"") + data <- readRDS(file.path(""data"", fileName)) + data$GROUP <- row$targetDrug + data$GROUP[data$treatment == 0] <- row$comparatorDrug + data$GROUP <- factor(data$GROUP, levels = c(row$targetDrug, + row$comparatorDrug)) + plot <- ggplot2::ggplot(data, ggplot2::aes(x = preferenceScore, y = y, color = GROUP, group = GROUP, fill = GROUP)) + + ggplot2::geom_area(position = ""identity"") + + ggplot2::scale_fill_manual(values = c(rgb(0.8, 0, 0, alpha = 0.5), rgb(0, 0, 0.8, alpha = 0.5))) + + ggplot2::scale_color_manual(values = c(rgb(0.8, 0, 0, alpha = 0.5), rgb(0, 0, 0.8, alpha = 0.5))) + + ggplot2::scale_x_continuous(""Preference score"", limits = c(0, 1)) + + ggplot2::scale_y_continuous(""Density"") + + ggplot2::theme(legend.title = ggplot2::element_blank(), + legend.position = ""top"", + legend.direction = ""horizontal"", + text = ggplot2::element_text(size = 15)) + return(plot) + } else { + return(NULL) + } + }) + + output$balancePlotCaption <- renderUI({ + bal <- balance() + if (!is.null(bal)) { + row <- selectedRow() + text <- ""Figure 2. Covariate balance before and after %s. Each dot represents + the standardizes difference of means for a single covariate before and after %s on the propensity + score. Move the mouse arrow over a dot for more details."" + return(HTML(sprintf(text, tolower(row$psStrategy), tolower(row$psStrategy)))) + } else { + return(NULL) + } + }) + + output$balancePlot <- renderPlot({ + bal <- balance() + if (!is.null(bal)) { + row <- selectedRow() + plotBalance(bal, + beforeLabel = paste(""Std. diff. before"", tolower(row$psStrategy)), + afterLabel = paste(""Std. diff. after"", tolower(row$psStrategy))) + } else { + return(NULL) + } + }) + + output$hoverInfoBalanceScatter <- renderUI({ + # Hover-over adapted from https://gitlab.com/snippets/16220 + bal <- balance() + if (is.null(bal)) + return(NULL) + row <- selectedRow() + hover <- input$plotHoverBalanceScatter + point <- nearPoints(bal, hover, threshold = 5, maxpoints = 1, addDist = TRUE) + if (nrow(point) == 0) return(NULL) + + # calculate point position INSIDE the image as percent of total dimensions + # from left (horizontal) and from top (vertical) + left_pct <- (hover$x - hover$domain$left) / (hover$domain$right - hover$domain$left) + top_pct <- (hover$domain$top - hover$y) / (hover$domain$top - hover$domain$bottom) + + # calculate distance from left and bottom side of the picture in pixels + left_px <- hover$range$left + left_pct * (hover$range$right - hover$range$left) + top_px <- hover$range$top + top_pct * (hover$range$bottom - hover$range$top) + + # create style property fot tooltip + # background color is set so tooltip is a bit transparent + # z-index is set so we are sure are tooltip will be on top + style <- paste0(""position:absolute; z-index:100; background-color: rgba(245, 245, 245, 0.85); "", + ""left:"", left_px - 251, ""px; top:"", top_px - 150, ""px; width:500px;"") + + + # actual tooltip created as wellPanel + beforeMatchingStdDiff <- formatC(point$beforeMatchingStdDiff, digits = 2, format = ""f"") + afterMatchingStdDiff <- formatC(point$afterMatchingStdDiff, digits = 2, format = ""f"") + div( + style=""position: relative; width: 0; height: 0"", + wellPanel( + style = style, + p(HTML(paste0("" Covariate: "", point$covariateName, ""
"", + "" Std. diff before "",tolower(row$psStrategy),"": "", beforeMatchingStdDiff, ""
"", + "" Std. diff after "",tolower(row$psStrategy),"": "", afterMatchingStdDiff))) + ) + ) + }) + + output$negativeControlPlot <- renderPlot({ + row <- selectedRow() + if (!is.null(row)) { + ncs <- resultsNcs[resultsNcs$targetId == row$targetId & + resultsNcs$comparatorId == row$comparatorId & + resultsNcs$analysisId == row$analysisId & + resultsNcs$database == row$database, ] + fileName <- paste0(""null_a"",row$analysisId,""_t"",row$targetId,""_c"",row$comparatorId,""_"",row$database,"".rds"") + if (file.exists(file.path(""data"", fileName))) { + null <- readRDS(file.path(""data"", fileName)) + } else { + null <- NULL + } + plot <- EmpiricalCalibration::plotCalibrationEffect(logRrNegatives = ncs$logRr, + seLogRrNegatives = ncs$seLogRr, + logRrPositives = row$logRr, + seLogRrPositives = row$seLogRr, + null = null, + xLabel = ""Hazard ratio"", + showCis = !is.null(null)) + plot <- plot + ggplot2::theme(text = ggplot2::element_text(size = 15)) + + return(plot) + } else { + return(NULL) + } + }) + + output$kaplanMeierPlot <- renderPlot({ + row <- selectedRow() + if (!is.null(row)) { + fileName <- paste0(""km_a"",row$analysisId,""_t"",row$targetId,""_c"",row$comparatorId,""_o"",row$outcomeId,""_"",row$database,"".rds"") + if (file.exists(file.path(""data"", fileName))) { + plot <- readRDS(file.path(""data"", fileName)) + return(grid::grid.draw(plot)) + } + } + return(NULL) + }, res = 100) + + output$kmPlotCaption <- renderUI({ + bal <- balance() + if (!is.null(bal)) { + row <- selectedRow() + text <- ""Table 5. Kaplan Meier plot, showing survival as a function of time. This plot + is adjusted for the propensity score %s: The target curve (%s) shows the actual observed survival. The + comparator curve (%s) applies reweighting to approximate the counterfactual of what the target survival + would look like had the target cohort been exposed to the comparator instead. The shaded area denotes + the 95 percent confidence interval."" + return(HTML(sprintf(text, tolower(row$psStrategy), row$targetDrug, row$comparatorDrug))) + } else { + return(NULL) + } + }) + + output$forestPlot <- renderPlot({ + row <- selectedRow() + if (!is.null(row)) { + subset <- forestPlotSubset() + return(plotForest(subset, row)) + } + return(NULL) + }, height = 2000) + + output$hoverInfoForestPlot <- renderUI({ + # Hover-over adapted from https://gitlab.com/snippets/16220 + subset <- forestPlotSubset() + if (is.null(subset)) + return(NULL) + hover <- input$plotHoverForestPlot + point <- nearPoints(subset, hover, threshold = 5, maxpoints = 1, addDist = TRUE) + if (nrow(point) == 0) return(NULL) + # calculate point position INSIDE the image as percent of total dimensions + # from left (horizontal) and from top (vertical) + left_pct <- (hover$x - hover$domain$left) / (hover$domain$right - hover$domain$left) + top_pct <- (hover$domain$top - hover$y) / (hover$domain$top - hover$domain$bottom) + + # calculate distance from left and bottom side of the picture in pixels + left_px <- hover$range$left + left_pct * (hover$range$right - hover$range$left) + top_px <- hover$range$top + top_pct * (hover$range$bottom - hover$range$top) + + # create style property fot tooltip + # background color is set so tooltip is a bit transparent + # z-index is set so we are sure are tooltip will be on top + style <- paste0(""position:absolute; z-index:100; background-color: rgba(245, 245, 245, 0.85); "", + ""left:100px; top:"", top_px - 200, ""px; width:500px;"") + + + # actual tooltip created as wellPanel + hr <- sprintf(""%.2f (%.2f - %.2f)"", point$rr, point$ci95lb, point$ci95ub) + div( + style=""position: relative; width: 0; height: 0"", + wellPanel( + style = style, + p(HTML(paste0("" Established Cvd.: "", point$establishedCvd, ""
"", + "" Prior exposure: "", point$priorExposure, ""
"", + "" Time at risk: "", point$timeAtRisk, ""
"", + "" Event type: "", point$evenType, ""
"", + "" Propensity score (PS) strategy: "", point$psStrategy, ""
"", + "" Database: "", point$database, ""
"", + "" Harard ratio (95% CI): "", hr, ""
""))) + ) + ) + }) + + observeEvent(input$dbInfo, { + showModal(modalDialog( + title = ""Data sources"", + easyClose = TRUE, + footer = NULL, + size = ""l"", + HTML(dbInfoHtml) + )) + }) + + observeEvent(input$comparisonsInfo, { + showModal(modalDialog( + title = ""Comparisons"", + easyClose = TRUE, + footer = NULL, + size = ""l"", + HTML(comparisonsInfoHtml) + )) + }) + + observeEvent(input$outcomesInfo, { + showModal(modalDialog( + title = ""Outcomes"", + easyClose = TRUE, + footer = NULL, + size = ""l"", + HTML(outcomesInfoHtml) + )) + }) + + observeEvent(input$cvdInfo, { + showModal(modalDialog( + title = ""Established cardiovascular disease (CVD)"", + easyClose = TRUE, + footer = NULL, + size = ""l"", + HTML(cvdInfoHtml) + )) + }) + + observeEvent(input$priorExposureInfo, { + showModal(modalDialog( + title = ""Prior exposure"", + easyClose = TRUE, + footer = NULL, + size = ""l"", + HTML(priorExposureInfoHtml) + )) + }) + + observeEvent(input$tarInfo, { + showModal(modalDialog( + title = ""Time-at-risk"", + easyClose = TRUE, + footer = NULL, + size = ""l"", + HTML(tarInfoHtml) + )) + }) + + observeEvent(input$eventInfo, { + showModal(modalDialog( + title = ""Time-at-risk"", + easyClose = TRUE, + footer = NULL, + size = ""l"", + HTML(eventInfoHtml) + )) + }) + + observeEvent(input$psInfo, { + showModal(modalDialog( + title = ""Time-at-risk"", + easyClose = TRUE, + footer = NULL, + size = ""l"", + HTML(psInfoHtml) + )) + }) + + + + +}) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AhasHfBkleAmputation/extras/EvidenceExplorer/functions.R",".R","3455","54","plotBalance <- function(balance, + beforeLabel = ""Before matching"", + afterLabel = ""After matching"") { + limits <- c(min(c(balance$absBeforeMatchingStdDiff, balance$absAfterMatchingStdDiff), na.rm = TRUE), + max(c(balance$absBeforeMatchingStdDiff, balance$absAfterMatchingStdDiff), na.rm = TRUE)) + plot <- ggplot2::ggplot(balance, + ggplot2::aes(x = absBeforeMatchingStdDiff, y = absAfterMatchingStdDiff)) + + ggplot2::geom_point(color = rgb(0, 0, 0.8, alpha = 0.3), shape = 16, size = 2) + + ggplot2::geom_abline(slope = 1, intercept = 0, linetype = ""dashed"") + + ggplot2::geom_hline(yintercept = 0) + + ggplot2::geom_vline(xintercept = 0) + + ggplot2::scale_x_continuous(beforeLabel, limits = limits) + + ggplot2::scale_y_continuous(afterLabel, limits = limits) + + ggplot2::theme(text = ggplot2::element_text(size = 15)) + return(plot) +} + +plotForest <- function(subset, row) { + comparatorName <- row$comparatorDrug + breaks <- c(0.1, 0.25, 0.5, 1, 2, 4, 6, 8, 10) + labels <- c(0.1, paste(""0.25\nFavors"" , row$targetDrug), 0.5, 1, 2, paste(""4\nFavors"" , row$comparatorDrug), 6, 8, 10) + col <- c(rgb(0, 0, 0.8, alpha = 1), rgb(0.8, 0.4, 0, alpha = 1)) + colFill <- c(rgb(0, 0, 1, alpha = 0.5), rgb(1, 0.4, 0, alpha = 0.5)) + highlight <- subset[subset$targetId == row$targetId & + subset$comparatorId == row$comparatorId & + subset$outcomeId == row$outcomeId & + subset$analysisId == row$analysisId & + subset$database == row$database, ] + plot <- ggplot2::ggplot(subset, ggplot2::aes(x = rr, + y = displayOrder, + xmin = ci95lb, + xmax = ci95ub, + fill = timeAtRisk), environment = environment()) + + ggplot2::geom_vline(xintercept = breaks, colour = ""#AAAAAA"", lty = 1, size = 0.2) + + ggplot2::geom_vline(xintercept = 1, colour = ""#000000"", lty = 1, size = 0.5) + + ggplot2::geom_errorbarh(height = 0, alpha = 0.7, aes(colour = timeAtRisk)) + + ggplot2::geom_point(shape = 16, size = 1.2, alpha = 0.7, aes(colour = timeAtRisk)) + + ggplot2::geom_errorbarh(height = 0, alpha = 1, size = 1, color = rgb(0,0,0), data = highlight, show.legend = FALSE) + + ggplot2::geom_point(shape = 16, size = 2, color = rgb(0,0,0), alpha = 1, data = highlight, show.legend = FALSE) + + ggplot2::coord_cartesian(xlim = c(0.1, 10)) + + ggplot2::scale_x_continuous(""Hazard ratio"", trans = ""log10"", breaks = breaks, labels = labels) + + ggplot2::facet_grid(database ~ ., scales = ""free_y"", space = ""free"") + + ggplot2::labs(color = ""Time-at-risk"", fill = ""Time-at-risk"") + + ggplot2::theme(text = ggplot2::element_text(size = 15), + panel.grid.minor = ggplot2::element_blank(), + panel.background = ggplot2::element_rect(fill = ""#FAFAFA"",colour = NA), + panel.grid.major = ggplot2::element_line(colour = ""#EEEEEE""), + axis.ticks = ggplot2::element_blank(), + axis.title.y = ggplot2::element_blank(), + axis.title.x = ggplot2::element_blank(), + axis.text.y = ggplot2::element_blank(), + legend.position = ""top"") + return(plot) +}","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AhasHfBkleAmputation/extras/EvidenceExplorer/ui.R",".R","13146","102","library(shiny) +library(DT) + +shinyUI(fluidPage(style = 'width:1500px;', + titlePanel(HTML(paste(""

Comparative effectiveness of canagliflozin, SGLT2 inhibitors and non-SGLT2 inhibitors on the risk of hospitalization for heart failure and amputation in patients with type 2 diabetes mellitus: A real-world meta-analysis of 4 observational databases (OBSERVE-4D)

"", if(blind){""*Blinded*""}else{""""})), windowTitle = ""Comparison of Canagliflozin vs. Alternative Antihyperglycemic Treatments""), + tags$head(tags$style(type = ""text/css"", "" + #loadmessage { + position: fixed; + top: 0px; + left: 0px; + width: 100%; + padding: 5px 0px 5px 0px; + text-align: center; + font-weight: bold; + font-size: 100%; + color: #000000; + background-color: #ADD8E6; + z-index: 105; + } + "")), + conditionalPanel(condition=""$('html').hasClass('shiny-busy')"", + tags$div(""Procesing..."",id=""loadmessage"")), + + tabsetPanel(id = ""mainTabsetPanel"", + tabPanel(""About"", + HTML(""
""), + HTML(""

OBSERVE-4D is a retrospective real-world observational study to evaluate the risk of below-knee lower extremity (BKLE) amputation and hospitalization for heart failure (HHF) with canagliflozin versus other sodium glucose co-transporter 2 inhibitor (SGLT2i) and non-SGLT2i antihyperglycemic agents (AHAs).

""), + HTML(""

This web-based application provides an interactive platform to explore all analysis results generated as part of this study, as a supplement to the manuscript published in Diabetes, Metabolism, and Obesity (the full manuscript is available at: https://onlinelibrary.wiley.com/doi/full/10.1111/dom.13424).

""), + HTML(""
""), + HTML(""

Below is the abstract of the manuscript that summarizes the collective findings:

""), + HTML(""

Aims: Sodium glucose co-transporter 2 inhibitors (SGLT2i) are indicated for treatment of type 2 diabetes mellitus (T2DM); some SGLT2i have reported cardiovascular benefit, and some have reported risk of below-knee lower extremity (BKLE) amputation. This study examined the real-world comparative effectiveness within the SGLT2i class and compared with non-SGLT2i antihyperglycaemic agents.

""), + HTML(""

Materials and methods: Data from 4 large US administrative claims databases were used to characterize risk and provide population-level estimates of canagliflozin's effects on hospitalization for heart failure (HHF) and BKLE amputation vs other SGLT2i and non-SGLT2i in T2DM patients. Comparative analyses using a propensity score–adjusted new-user cohort design examined relative hazards of outcomes across all new users and a subpopulation with established cardiovascular disease.

""), + HTML(""

Results: Across the 4 databases (142 800 new users of canagliflozin, 110 897 new users of other SGLT2i, 460 885 new users of non-SGLT2i), the meta-analytic hazard ratio estimate for HHF with canagliflozin vs non-SGLT2i was 0.39 (95% CI, 0.26-0.60) in the on-treatment analysis. The estimate for BKLE amputation with canagliflozin vs non-SGLT2i was 0.75 (95% CI, 0.40-1.41) in the on-treatment analysis and 1.01 (95% CI, 0.93-1.10) in the intent-to-treat analysis. Effects in the subpopulation with established cardiovascular disease were similar for both outcomes. No consistent differences were observed between canagliflozin and other SGLT2i.

""), + HTML(""

Conclusions: In this large comprehensive analysis, canagliflozin and other SGLT2i demonstrated HHF benefits consistent with clinical trial data, but showed no increased risk of BKLE amputation vs non-SGLT2i. HHF and BKLE amputation results were similar in the subpopulation with established cardiovascular disease. This study helps further characterize the potential benefits and harms of SGLT2i in routine clinical practice to complement evidence from clinical trials and prior observational studies.

""), + HTML(""
""), + HTML(""

Below are links for study-related artifacts that have been made available as part of this study:

""), + HTML("""") + ), + tabPanel(""Explore results"", + fluidRow( + column(3, + selectInput(""comparison"", div(""Comparison:"", actionLink(""comparisonsInfo"", """", icon = icon(""info-circle""))), comparisons), + selectInput(""outcome"", div(""Outcome:"", actionLink(""outcomesInfo"", """", icon = icon(""info-circle""))), outcomes), + checkboxGroupInput(""establishedCVd"", div(""Established cardiovasc. disease (CVD):"", actionLink(""cvdInfo"", """", icon = icon(""info-circle""))), establishCvds, selected = ""not required""), + checkboxGroupInput(""priorExposure"", div(""Prior exposure:"", actionLink(""priorExposureInfo"", """", icon = icon(""info-circle""))), priorExposures, selected = ""no restrictions""), + checkboxGroupInput(""timeAtRisk"", div(""Time at risk:"", actionLink(""tarInfo"", """", icon = icon(""info-circle""))), timeAtRisks, selected = ""On Treatment""), + checkboxGroupInput(""evenType"", div(""Event type:"", actionLink(""eventInfo"", """", icon = icon(""info-circle""))), evenTypes, selected = ""First Post Index Event""), + checkboxGroupInput(""psStrategy"", div(""Propensity score (PS) strategy:"", actionLink(""psInfo"", """", icon = icon(""info-circle""))), psStrategies, selected = ""Matching""), + checkboxGroupInput(""db"", div(""Data source:"", actionLink(""dbInfo"", """", icon = icon(""info-circle""))), dbs, selected = dbs) + ), + column(9, + dataTableOutput(""mainTable""), + conditionalPanel(""output.rowIsSelected == true"", + tabsetPanel(id = ""tabsetPanel"", + tabPanel(""Power"", + uiOutput(""powerTableCaption""), + tableOutput(""powerTable""), + conditionalPanel(""output.isMetaAnalysis == false"", + uiOutput(""timeAtRiskTableCaption""), + tableOutput(""timeAtRiskTable""))), + tabPanel(""Population characteristics"", + uiOutput(""table1Caption""), + dataTableOutput(""table1Table"")), + tabPanel(""Propensity scores"", + plotOutput(""psPlot""), + div(strong(""Figure 1.""),""Preference score distribution. The preference score is a transformation of the propensity score + that adjusts for differences in the sizes of the two treatment groups. A higher overlap indicates subjects in the + two groups were more similar in terms of their predicted probability of receiving one treatment over the other."")), + tabPanel(""Covariate balance"", + uiOutput(""hoverInfoBalanceScatter""), + plotOutput(""balancePlot"", + hover = hoverOpts(""plotHoverBalanceScatter"", delay = 100, delayType = ""debounce"")), + uiOutput(""balancePlotCaption"")), + tabPanel(""Systematic error"", + plotOutput(""negativeControlPlot""), + div(strong(""Figure 3.""),""Negative control estimates. Each blue dot represents the estimated hazard + ratio and standard error (related to the width of the confidence interval) of each of the negative + control outcomes. The yellow diamond indicated the outcome of interest. Estimates below the dashed + line have uncalibrated p < .05. Estimates in the orange area have calibrated p < .05. The red band + indicated the 95% credible interval around the boundary of the orange area. "")), + tabPanel(""Parameter sensitivity"", + uiOutput(""hoverInfoForestPlot""), + plotOutput(""forestPlot"", height = 2000, hover = hoverOpts(""plotHoverForestPlot"", delay = 100, delayType = ""debounce"")), + div(strong(""Figure 4.""),""Forest plot of effect estimates from all sensitivity analyses across databases and time-at-risk periods. Black indicates the estimate selected by the user."")), + tabPanel(""Kaplan-Meier"", + plotOutput(""kaplanMeierPlot"", height = 550), + uiOutput(""kmPlotCaption"")) + ) + ) + + ) + ) + ) + ) +) +)","R" +"Pharmacogenetics","OHDSI/StudyProtocols","AhasHfBkleAmputation/extras/EvidenceExplorer/Table1.R",".R","8201","146","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of AhasHfBkleAmputation +# +# 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. + +prepareTable1 <- function(balance, + beforeTargetPopSize, + beforeComparatorPopSize, + afterTargetPopSize, + afterComparatorPopSize, + beforeLabel = ""Before matching"", + afterLabel = ""After matching"", + targetLabel = ""Target"", + comparatorLabel = ""Comparator"", + percentDigits = 1, + stdDiffDigits = 2) { + #pathToCsv <- system.file(""settings"", ""Table1Specs.csv"", package = packageName) + pathToCsv <- ""Table1Specs.csv"" + specifications <- read.csv(pathToCsv, stringsAsFactors = FALSE) + + fixCase <- function(label) { + idx <- (toupper(label) == label) + if (any(idx)) { + label[idx] <- paste0(substr(label[idx], 1, 1), + tolower(substr(label[idx], 2, nchar(label[idx])))) + } + return(label) + } + + formatPercent <- function(x) { + result <- format(round(100*x, percentDigits), digits = percentDigits+1, justify = ""right"") + # result <- formatC(x * 100, digits = percentDigits, format = ""f"") + result <- gsub(""NA"", """", result) + result <- gsub("" "", "" "", result) + return(result) + } + + formatStdDiff <- function(x) { + result <- format(round(x, stdDiffDigits), digits = stdDiffDigits+1, justify = ""right"") + result <- gsub(""NA"", """", result) + result <- gsub("" "", "" "", result) + return(result) + } + + resultsTable <- data.frame() + for (i in 1:nrow(specifications)) { + if (specifications$analysisId[i] == """") { + resultsTable <- rbind(resultsTable, + data.frame(Characteristic = specifications$label[i], value = """")) + } else { + idx <- balance$analysisId == specifications$analysisId[i] + if (any(idx)) { + if (specifications$covariateIds[i] != """") { + covariateIds <- as.numeric(strsplit(specifications$covariateIds[i], "","")[[1]]) + idx <- balance$covariateId %in% covariateIds + } else { + covariateIds <- NULL + } + if (any(idx)) { + balanceSubset <- balance[idx, ] + if (is.null(covariateIds)) { + balanceSubset <- balanceSubset[order(balanceSubset$covariateId), ] + } else { + balanceSubset <- merge(balanceSubset, data.frame(covariateId = covariateIds, + rn = 1:length(covariateIds))) + balanceSubset <- balanceSubset[order(balanceSubset$rn, + balanceSubset$covariateId), ] + } + balanceSubset$covariateName <- fixCase(gsub(""^.*: "", + """", + balanceSubset$covariateName)) + if (specifications$covariateIds[i] == """" || length(covariateIds) > 1) { + resultsTable <- rbind(resultsTable, data.frame(Characteristic = specifications$label[i], + beforeMatchingMeanTreated = NA, + beforeMatchingMeanComparator = NA, + beforeMatchingStdDiff = NA, + afterMatchingMeanTreated = NA, + afterMatchingMeanComparator = NA, + afterMatchingStdDiff = NA, + stringsAsFactors = FALSE)) + resultsTable <- rbind(resultsTable, + data.frame(Characteristic = paste0(""    "", balanceSubset$covariateName), + beforeMatchingMeanTreated = balanceSubset$beforeMatchingMeanTreated, + beforeMatchingMeanComparator = balanceSubset$beforeMatchingMeanComparator, + beforeMatchingStdDiff = balanceSubset$beforeMatchingStdDiff, + afterMatchingMeanTreated = balanceSubset$afterMatchingMeanTreated, + afterMatchingMeanComparator = balanceSubset$afterMatchingMeanComparator, + afterMatchingStdDiff = balanceSubset$afterMatchingStdDiff, + stringsAsFactors = FALSE)) + } else { + resultsTable <- rbind(resultsTable, data.frame(Characteristic = specifications$label[i], + beforeMatchingMeanTreated = balanceSubset$beforeMatchingMeanTreated, + beforeMatchingMeanComparator = balanceSubset$beforeMatchingMeanComparator, + beforeMatchingStdDiff = balanceSubset$beforeMatchingStdDiff, + afterMatchingMeanTreated = balanceSubset$afterMatchingMeanTreated, + afterMatchingMeanComparator = balanceSubset$afterMatchingMeanComparator, + afterMatchingStdDiff = balanceSubset$afterMatchingStdDiff, + stringsAsFactors = FALSE)) + } + } + } + } + } + resultsTable$beforeMatchingMeanTreated <- formatPercent(resultsTable$beforeMatchingMeanTreated) + resultsTable$beforeMatchingMeanComparator <- formatPercent(resultsTable$beforeMatchingMeanComparator) + resultsTable$beforeMatchingStdDiff <- formatStdDiff(resultsTable$beforeMatchingStdDiff) + resultsTable$afterMatchingMeanTreated <- formatPercent(resultsTable$afterMatchingMeanTreated) + resultsTable$afterMatchingMeanComparator <- formatPercent(resultsTable$afterMatchingMeanComparator) + resultsTable$afterMatchingStdDiff <- formatStdDiff(resultsTable$afterMatchingStdDiff) + + headerRow <- as.data.frame(t(rep("""", ncol(resultsTable)))) + colnames(headerRow) <- colnames(resultsTable) + headerRow$beforeMatchingMeanTreated <- targetLabel + headerRow$beforeMatchingMeanComparator <- comparatorLabel + headerRow$afterMatchingMeanTreated <- targetLabel + headerRow$afterMatchingMeanComparator <- comparatorLabel + + subHeaderRow <- as.data.frame(t(rep("""", ncol(resultsTable)))) + colnames(subHeaderRow) <- colnames(resultsTable) + subHeaderRow$Characteristic <- ""Characteristic"" + subHeaderRow$beforeMatchingMeanTreated <- paste0(""% (n = "",format(beforeTargetPopSize, big.mark = "",""), "")"") + subHeaderRow$beforeMatchingMeanComparator <- paste0(""% (n = "",format(beforeComparatorPopSize, big.mark = "",""), "")"") + subHeaderRow$beforeMatchingStdDiff <- ""Std. diff"" + subHeaderRow$afterMatchingMeanTreated <- paste0(""% (n = "",format(afterTargetPopSize, big.mark = "",""), "")"") + subHeaderRow$afterMatchingMeanComparator <- paste0(""% (n = "",format(afterComparatorPopSize, big.mark = "",""), "")"") + subHeaderRow$afterMatchingStdDiff <- ""Std. diff"" + + resultsTable <- rbind(headerRow, subHeaderRow, resultsTable) + + colnames(resultsTable) <- rep("""", ncol(resultsTable)) + # colnames(resultsTable) <- as.character(1:ncol(resultsTable)) + colnames(resultsTable)[2] <- beforeLabel + colnames(resultsTable)[5] <- afterLabel + return(resultsTable) +}","R" +"Pharmacogenetics","OHDSI/StudyProtocols","EvaluatingCaseControl/R/AtcCovariateBuilder.R",".R","5207","99","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of EvaluatingCaseControl +# +# 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. + +#' Create settings for covariates representing one or more ATC codes +#' +#' @param covariateDefs A data frame with three columns: covariateId, covariateName, atc. +#' +#' @param windowStart Days relative to the index date to start capturing the covariates. Negative numbers indicates +#' days prior to index. +#' @param windowEnd Days relative to the index date to end capturing the covariates. Negative numbers indicates +#' days prior to index. +#' +#' @export +createAtcCovariateSettings <- function(covariateDefs, windowStart = -365, windowEnd = -1) { + covariateSettings <- list(covariateDefs = covariateDefs, + windowStart = windowStart, + windowEnd = windowEnd) + attr(covariateSettings, ""fun"") <- ""EvaluatingCaseControl::getDbAtcCovariateData"" + class(covariateSettings) <- ""covariateSettings"" + return(covariateSettings) +} + +getDbAtcCovariateData <- function(connection, + oracleTempSchema = NULL, + cdmDatabaseSchema, + cohortTable = ""#cohort_person"", + cohortId = -1, + cdmVersion = ""5"", + rowIdField = ""subject_id"", + covariateSettings, + aggregated = FALSE) { + sql <- ""CREATE TABLE #covar_defs (concept_id INT, covariate_id INT)"" + sql <- SqlRender::translateSql(sql, targetDialect = attr(connection, ""dbms""))$sql + DatabaseConnector::executeSql(connection, sql, progressBar = FALSE, reportOverallTime = FALSE) + + for (i in 1:nrow(covariateSettings$covariateDefs)) { + sql <- SqlRender::loadRenderTranslateSql(""atcToConcepts.sql"", + packageName = ""EvaluatingCaseControl"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + covariate_id = covariateSettings$covariateDefs$covariateId[i], + atc = covariateSettings$covariateDefs$atc[i], + cdm_database_schema = cdmDatabaseSchema) + DatabaseConnector::executeSql(connection, sql, progressBar = FALSE, reportOverallTime = FALSE) + } + sql <- SqlRender::loadRenderTranslateSql(""getAtcCovariates.sql"", + packageName = ""EvaluatingCaseControl"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + window_start = covariateSettings$windowStart, + window_end = covariateSettings$windowEnd, + cdm_database_schema = cdmDatabaseSchema, + row_id_field = rowIdField, + cohort_table = cohortTable, + cohort_id = cohortId) + covariates <- DatabaseConnector::querySql.ffdf(connection, sql) + colnames(covariates) <- SqlRender::snakeCaseToCamelCase(colnames(covariates)) + sql <- ""TRUNCATE TABLE #covar_defs; DROP TABLE #covar_defs;"" + sql <- SqlRender::translateSql(sql, targetDialect = attr(connection, ""dbms""))$sql + executeSql(connection, sql, progressBar = FALSE, reportOverallTime = FALSE) + + covariateRef <- unique(covariateSettings$covariateDefs[, c(""covariateId"",""covariateName"")]) + covariateRef$covariateId <- as.numeric(covariateRef$covariateId) + covariateRef$covariateName <- as.factor(covariateRef$covariateName) + covariateRef$analysisId <- 1 + covariateRef$conceptId <- 0 + covariateRef <- ff::as.ffdf(covariateRef) + + analysisRef <- data.frame(analysisId = 1, + analysisName = ""ATC covariates"", + domainId = ""Drug"", + startDay = 0, + endDay = 0, + isBinary = ""Y"", + missingMeansZero = ""Y"") + analysisRef <- ff::as.ffdf(analysisRef) + + metaData <- list(call = match.call()) + result <- list(covariates = covariates, + covariateRef = covariateRef, + analysisRef = analysisRef, + metaData = metaData) + class(result) <- ""covariateData"" + return(result) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","EvaluatingCaseControl/R/Main.R",".R","5810","119","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of EvaluatingCaseControl +# +# 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. + +#' @title +#' Execute OHDSI Evaluating the Case-Control Design Study +#' +#' @description +#' This function executes the OHDSI Evaluating the Case-Control Design Study. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param cohortDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param cohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' @param createCohorts Instantiate the necessary cohorts in the cohortTable? +# #' @param synthesizePositiveControls Synthesize positive controls based on the negative controls? +#' @param runCaseControl Execute the case-control analysis? +#' @param runSccs Execute the SCCS analysis? +#' @param createFiguresAndTables Create the figures and tables for the paper? +#' @param maxCores How many parallel cores should be used? If more cores are made available +#' this can speed up the analyses. +#' +#' @examples +#' \dontrun{ +#' connectionDetails <- createConnectionDetails(dbms = ""postgresql"", +#' user = ""joe"", +#' password = ""secret"", +#' server = ""myserver"") +#' +#' execute(connectionDetails, +#' cdmDatabaseSchema = ""cdm_data"", +#' cohortDatabaseSchema = ""results"", +#' oracleTempSchema = NULL, +#' outputFolder = ""c:/temp/study_results"") +#' +#' } +#' +#' @export +execute <- function(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable, + oracleTempSchema, + outputFolder, + createCohorts = TRUE, + # synthesizePositiveControls = TRUE, + runCaseControl = TRUE, + runSccs = TRUE, + createFiguresAndTables = TRUE, + maxCores = 4) { + if (!file.exists(outputFolder)) + dir.create(outputFolder) + + ParallelLogger::addDefaultFileLogger(file.path(outputFolder, ""log.txt"")) + + if (createCohorts) { + ParallelLogger::logInfo(""Creating exposure and outcome cohorts"") + createCohorts(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + outputFolder = outputFolder) + } + # if (synthesizePositiveControls) { + # ParallelLogger::logInfo(""Synthesizing positive controls"") + # synthesizePositiveControls(connectionDetails = connectionDetails, + # cdmDatabaseSchema = cdmDatabaseSchema, + # cohortDatabaseSchema = cohortDatabaseSchema, + # cohortTable = cohortTable, + # oracleTempSchema = oracleTempSchema, + # outputFolder = outputFolder, + # maxCores = maxCores) + # ParallelLogger::logInfo("""") + # } + + if (runCaseControl) { + ParallelLogger::logInfo(""Running case control"") + runCaseControlDesigns(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + outputFolder = outputFolder, + maxCores = maxCores) + } + if (createFiguresAndTables) { + ParallelLogger::logInfo(""Creating figures and tables"") + createFiguresAndTables(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder) + } +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","EvaluatingCaseControl/R/Icd9CovariateBuilder.R",".R","5229","98","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of EvaluatingCaseControl +# +# 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. + +#' Create settings for covariates representing one or more ICD-9 codes +#' +#' @param covariateDefs A data frame with three columns: covariateId, covariateName, icd9 +#' +#' @param windowStart Days relative to the index date to start capturing the covariates. Negative numbers indicates +#' days prior to index. +#' @param windowEnd Days relative to the index date to end capturing the covariates. Negative numbers indicates +#' days prior to index. +#' +#' @export +createIcd9CovariateSettings <- function(covariateDefs, windowStart = -365, windowEnd = -1) { + covariateSettings <- list(covariateDefs = covariateDefs, + windowStart = windowStart, + windowEnd = windowEnd) + attr(covariateSettings, ""fun"") <- ""EvaluatingCaseControl::getDbIcd9CovariateData"" + class(covariateSettings) <- ""covariateSettings"" + return(covariateSettings) +} + +getDbIcd9CovariateData <- function(connection, + oracleTempSchema = NULL, + cdmDatabaseSchema, + cohortTable = ""#cohort_person"", + cohortId = -1, + cdmVersion = ""5"", + rowIdField = ""subject_id"", + covariateSettings, + aggregated = FALSE) { + sql <- ""CREATE TABLE #covar_defs (concept_id INT, covariate_id INT)"" + sql <- SqlRender::translateSql(sql, targetDialect = attr(connection, ""dbms""))$sql + DatabaseConnector::executeSql(connection, sql, progressBar = FALSE, reportOverallTime = FALSE) + + for (i in 1:nrow(covariateSettings$covariateDefs)) { + sql <- SqlRender::loadRenderTranslateSql(""icd9ToConcepts.sql"", + packageName = ""EvaluatingCaseControl"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + covariate_id = covariateSettings$covariateDefs$covariateId[i], + icd9 = covariateSettings$covariateDefs$icd9[i], + cdm_database_schema = cdmDatabaseSchema) + DatabaseConnector::executeSql(connection, sql, progressBar = FALSE, reportOverallTime = FALSE) + } + sql <- SqlRender::loadRenderTranslateSql(""getIcd9Covariates.sql"", + packageName = ""EvaluatingCaseControl"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + window_start = covariateSettings$windowStart, + window_end = covariateSettings$windowEnd, + cdm_database_schema = cdmDatabaseSchema, + row_id_field = rowIdField, + cohort_table = cohortTable, + cohort_id = cohortId) + covariates <- DatabaseConnector::querySql.ffdf(connection, sql) + colnames(covariates) <- SqlRender::snakeCaseToCamelCase(colnames(covariates)) + sql <- ""TRUNCATE TABLE #covar_defs; DROP TABLE #covar_defs;"" + sql <- SqlRender::translateSql(sql, targetDialect = attr(connection, ""dbms""))$sql + executeSql(connection, sql, progressBar = FALSE, reportOverallTime = FALSE) + covariateRef <- unique(covariateSettings$covariateDefs[, c(""covariateId"",""covariateName"")]) + covariateRef$covariateId <- as.numeric(covariateRef$covariateId) + covariateRef$covariateName <- as.factor(covariateRef$covariateName) + covariateRef$analysisId <- 1 + covariateRef$conceptId <- 0 + covariateRef <- ff::as.ffdf(covariateRef) + + analysisRef <- data.frame(analysisId = 1, + analysisName = ""ICD9 covariates"", + domainId = ""Condition"", + startDay = 0, + endDay = 0, + isBinary = ""Y"", + missingMeansZero = ""Y"") + analysisRef <- ff::as.ffdf(analysisRef) + + metaData <- list(call = match.call()) + result <- list(covariates = covariates, + covariateRef = covariateRef, + analysisRef = analysisRef, + metaData = metaData) + class(result) <- ""covariateData"" + return(result) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","EvaluatingCaseControl/R/CreateCohorts.R",".R","3568","69","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of EvaluatingCaseControl +# +# 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. + +.createCohorts <- function(connection, + cdmDatabaseSchema, + vocabularyDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable, + oracleTempSchema, + outputFolder) { + + # Create study cohort table structure: + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""CreateCohortTable.sql"", + packageName = ""EvaluatingCaseControl"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + cohort_database_schema = cohortDatabaseSchema, + cohort_table = cohortTable) + DatabaseConnector::executeSql(connection, sql, progressBar = FALSE, reportOverallTime = FALSE) + + + + # Instantiate cohorts: + pathToCsv <- system.file(""settings"", ""CohortsToCreate.csv"", package = ""EvaluatingCaseControl"") + cohortsToCreate <- read.csv(pathToCsv) + for (i in 1:nrow(cohortsToCreate)) { + writeLines(paste(""Creating cohort:"", cohortsToCreate$name[i])) + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = paste0(cohortsToCreate$name[i], "".sql""), + packageName = ""EvaluatingCaseControl"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + vocabulary_database_schema = vocabularyDatabaseSchema, + + target_database_schema = cohortDatabaseSchema, + target_cohort_table = cohortTable, + target_cohort_id = cohortsToCreate$cohortId[i]) + DatabaseConnector::executeSql(connection, sql) + } + + # Fetch cohort counts: + sql <- ""SELECT cohort_definition_id, COUNT(*) AS count FROM @cohort_database_schema.@cohort_table GROUP BY cohort_definition_id"" + sql <- SqlRender::renderSql(sql, + cohort_database_schema = cohortDatabaseSchema, + cohort_table = cohortTable)$sql + sql <- SqlRender::translateSql(sql, targetDialect = attr(connection, ""dbms""))$sql + counts <- DatabaseConnector::querySql(connection, sql) + names(counts) <- SqlRender::snakeCaseToCamelCase(names(counts)) + counts <- merge(counts, data.frame(cohortDefinitionId = cohortsToCreate$cohortId, + cohortName = cohortsToCreate$name)) + write.csv(counts, file.path(outputFolder, ""CohortCounts.csv"")) + + +} + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","EvaluatingCaseControl/R/SynthesizePositiveControls.R",".R","10305","163","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of EvaluatingCaseControl +# +# 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. + +#' Synthesize positive controls +#' +#' @details +#' This function will synthesize positve controls based on the negative controls. The simulated outcomes +#' will be added to the cohort table. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param cohortDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param cohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' @param maxCores How many parallel cores should be used? If more cores are made available +#' this can speed up the analyses. +#' +#' @export +synthesizePositiveControls <- function(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable = ""cohort"", + oracleTempSchema, + outputFolder, + maxCores = 1) { + synthesisFolder <- file.path(outputFolder, ""positiveControlSynthesisAp"") + synthesisSummaryFile <- file.path(outputFolder, ""SynthesisSummaryAp.csv"") + outcomeId <- 2 + riskWindowEnd <- 30 + outputIdOffset <- 10000 + allControlsFile <- file.path(outputFolder, ""AllControls.csv"") + + synthesize <- function(synthesisFolder, + synthesisSummaryFile, + outcomeId, + riskWindowEnd, + outputIdOffset, + allControlsFile) { + if (!file.exists(synthesisFolder)) + dir.create(synthesisFolder) + + + if (!file.exists(synthesisSummaryFile)) { + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""EvaluatingCaseControl"") + negativeControls <- read.csv(pathToCsv) + negativeControls <- negativeControls[negativeControls$outcomeId == outcomeId, ] + exposureOutcomePairs <- data.frame(exposureId = negativeControls$targetId, + outcomeId = negativeControls$outcomeId) + exposureOutcomePairs <- unique(exposureOutcomePairs) + prior = Cyclops::createPrior(""laplace"", exclude = 0, useCrossValidation = TRUE) + control = Cyclops::createControl(cvType = ""auto"", + startingVariance = 0.01, + noiseLevel = ""quiet"", + cvRepetitions = 1, + threads = min(c(10, maxCores))) + covariateSettings <- FeatureExtraction::createCovariateSettings(useDemographicsAgeGroup = TRUE, + useDemographicsGender = TRUE, + useDemographicsIndexYear = TRUE, + useDemographicsIndexMonth = TRUE, + useConditionGroupEraLongTerm = TRUE, + useDrugGroupEraLongTerm = TRUE, + useProcedureOccurrenceLongTerm = TRUE, + useMeasurementLongTerm = TRUE, + useObservationLongTerm = TRUE, + useCharlsonIndex = TRUE, + useDcsi = TRUE, + useChads2Vasc = TRUE, + longTermStartDays = 365, + endDays = 0) + result <- MethodEvaluation::injectSignals(connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + exposureDatabaseSchema = cohortDatabaseSchema, + exposureTable = cohortTable, + outcomeDatabaseSchema = cohortDatabaseSchema, + outcomeTable = cohortTable, + outputDatabaseSchema = cohortDatabaseSchema, + outputTable = cohortTable, + createOutputTable = FALSE, + outputIdOffset = outputIdOffset, + exposureOutcomePairs = exposureOutcomePairs, + firstExposureOnly = FALSE, + firstOutcomeOnly = TRUE, + removePeopleWithPriorOutcomes = TRUE, + modelType = ""survival"", + washoutPeriod = 365, + riskWindowStart = 0, + riskWindowEnd = riskWindowEnd, + addExposureDaysToEnd = TRUE, + effectSizes = c(1.5, 2, 4), + precision = 0.01, + prior = prior, + control = control, + maxSubjectsForModel = 250000, + minOutcomeCountForModel = 50, + minOutcomeCountForInjection = 25, + workFolder = synthesisFolder, + modelThreads = max(1, round(maxCores/8)), + generationThreads = min(6, maxCores), + covariateSettings = covariateSettings) + write.csv(result, synthesisSummaryFile, row.names = FALSE) + } + ParallelLogger::logTrace(""Merging positive with negative controls "") + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""EvaluatingCaseControl"") + negativeControls <- read.csv(pathToCsv) + negativeControls <- negativeControls[negativeControls$outcomeId == outcomeId, ] + + synthesisSummary <- read.csv(synthesisSummaryFile) + synthesisSummary$targetId <- synthesisSummary$exposureId + synthesisSummary <- merge(synthesisSummary, negativeControls) + synthesisSummary <- synthesisSummary[synthesisSummary$trueEffectSize != 0, ] + synthesisSummary$outcomeName <- paste0(synthesisSummary$outcomeName, "", RR="", synthesisSummary$targetEffectSize) + synthesisSummary$oldOutcomeId <- synthesisSummary$outcomeId + synthesisSummary$outcomeId <- synthesisSummary$newOutcomeId + negativeControls$targetEffectSize <- 1 + negativeControls$trueEffectSize <- 1 + negativeControls$trueEffectSizeFirstExposure <- 1 + negativeControls$oldOutcomeId <- negativeControls$outcomeId + allControls <- rbind(negativeControls, synthesisSummary[, names(negativeControls)]) + # allControls <- negativeControls + write.csv(allControls, allControlsFile, row.names = FALSE) + } + ParallelLogger::logInfo(""Synhtesizing positive controls for Chou replication"") + synthesize(synthesisFolder = file.path(outputFolder, ""positiveControlSynthesisAp""), + synthesisSummaryFile = file.path(outputFolder, ""SynthesisSummaryAp.csv""), + outcomeId = 2, + riskWindowEnd = 30, + outputIdOffset = 10000, + allControlsFile = file.path(outputFolder, ""AllControlsAp.csv"")) + + ParallelLogger::logInfo(""Synhtesizing positive controls for Crockett replication"") + synthesize(synthesisFolder = file.path(outputFolder, ""positiveControlSynthesisIbd""), + synthesisSummaryFile = file.path(outputFolder, ""SynthesisSummaryIbd.csv""), + outcomeId = 3, + riskWindowEnd = 365, + outputIdOffset = 11000, + allControlsFile = file.path(outputFolder, ""AllControlsIbd.csv"")) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","EvaluatingCaseControl/R/CohortMethod.R",".R","13956","229","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of EvaluatingCaseControl +# +# 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. + +runCohortMethodDesigns <- function(connectionDetails, + cdmDatabaseSchema, + oracleTempSchema, + cohortDatabaseSchema, + cohortTable, + outputFolder, + maxCores) { + # Chou replication -------------------------------------------------------- + cmApFolder <- file.path(outputFolder, ""cmAp"") + if (!file.exists(cmApFolder)) + dir.create(cmApFolder) + + analysisListFile <- system.file(""settings"", ""cmAnalysisListAp.json"", package = ""EvaluatingCaseControl"") + analysisList <- CohortMethod::loadCmAnalysisList(analysisListFile) + tcoList <- createTcos(outputFolder = outputFolder, + exposureId = 4, + outcomeId = 2) + cmResult <- CohortMethod::runCmAnalyses(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + exposureDatabaseSchema = cohortDatabaseSchema, + exposureTable = cohortTable, + outcomeDatabaseSchema = cohortDatabaseSchema, + outcomeTable = cohortTable, + cmAnalysisList = analysisList, + targetComparatorOutcomesList = tcoList, + outputFolder = cmApFolder, + refitPsForEveryOutcome = FALSE, + getDbCohortMethodDataThreads = min(3, maxCores), + createStudyPopThreads = min(3, maxCores), + createPsThreads = max(3, round(maxCores/10)), + psCvThreads = min(10, maxCores), + trimMatchStratifyThreads = min(10, maxCores), + fitOutcomeModelThreads = max(1, round(maxCores/4)), + outcomeCvThreads = min(4, maxCores)) + cmSummary <- CohortMethod::summarizeAnalyses(cmResult, cmApFolder) + cmSummaryFile <- file.path(outputFolder, ""cmSummaryAp.rds"") + saveRDS(cmSummary, cmSummaryFile) + + ncs <- cmSummary[cmSummary$targetId != 4, ] + EmpiricalCalibration::plotCalibrationEffect(ncs$logRr, ncs$seLogRr, showCis = TRUE) + + + # Crockett replication -------------------------------------------------------- + cmIbdFolder <- file.path(outputFolder, ""cmIbd"") + if (!file.exists(cmIbdFolder)) + dir.create(cmIbdFolder) + + analysisListFile <- system.file(""settings"", ""cmAnalysisListIbd.json"", package = ""EvaluatingCaseControl"") + analysisList <- CohortMethod::loadCmAnalysisList(analysisListFile) + tcoList <- createTcos(outputFolder = outputFolder, + exposureId = 5, + outcomeId = 3) + cmResult <- CohortMethod::runCmAnalyses(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + exposureDatabaseSchema = cohortDatabaseSchema, + exposureTable = cohortTable, + outcomeDatabaseSchema = cohortDatabaseSchema, + outcomeTable = cohortTable, + cmAnalysisList = analysisList, + targetComparatorOutcomesList = tcoList, + outputFolder = cmIbdFolder, + refitPsForEveryOutcome = FALSE, + getDbCohortMethodDataThreads = min(3, maxCores), + createStudyPopThreads = min(3, maxCores), + createPsThreads = max(3, round(maxCores/10)), + psCvThreads = min(10, maxCores), + trimMatchStratifyThreads = min(10, maxCores), + fitOutcomeModelThreads = max(1, round(maxCores/4)), + outcomeCvThreads = min(4, maxCores)) + cmSummary <- CohortMethod::summarizeAnalyses(cmResult, cmIbdFolder) + cmSummaryFile <- file.path(outputFolder, ""cmSummaryIbd.rds"") + saveRDS(cmSummary, cmSummaryFile) + + ncs <- cmSummary[cmSummary$targetId != 5, ] + EmpiricalCalibration::plotCalibrationEffect(ncs$logRr, ncs$seLogRr, showCis = TRUE) +} + +#' Create the analyses details +#' +#' @details +#' This function creates files specifying the analyses that will be performed. +#' +#' @param workFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' +#' @export +createCohortMethodAnalysesDetails <- function(workFolder) { + + # Chou replication -------------------------------------------------------- + + covarSettings <- FeatureExtraction::createDefaultCovariateSettings(addDescendantsToExclude = TRUE) + + getDbCmDataArgs <- CohortMethod::createGetDbCohortMethodDataArgs(washoutPeriod = 365, + firstExposureOnly = TRUE, + removeDuplicateSubjects = TRUE, + studyStartDate = """", + studyEndDate = """", + covariateSettings = covarSettings, + maxCohortSize = 250000) + + createStudyPopArgs <- CohortMethod::createCreateStudyPopulationArgs(removeSubjectsWithPriorOutcome = TRUE, + minDaysAtRisk = 1, + riskWindowStart = 0, + addExposureDaysToStart = FALSE, + riskWindowEnd = 0, + addExposureDaysToEnd = TRUE) + + createPsArgs <- CohortMethod::createCreatePsArgs(control = Cyclops::createControl(cvType = ""auto"", + startingVariance = 0.01, + noiseLevel = ""quiet"", + tolerance = 2e-07, + cvRepetitions = 1), + stopOnError = FALSE) + + matchOnPsArgs <- CohortMethod::createMatchOnPsArgs(maxRatio = 100) + + fitOutcomeModelArgs <- CohortMethod::createFitOutcomeModelArgs(useCovariates = FALSE, + modelType = ""cox"", + stratified = TRUE) + + cmAnalysis <- CohortMethod::createCmAnalysis(analysisId = 1, + description = ""Matching plus simple outcome model"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = createStudyPopArgs, + createPs = TRUE, + createPsArgs = createPsArgs, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgs, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs) + + cmAnalysisList <- list(cmAnalysis) + CohortMethod::saveCmAnalysisList(cmAnalysisList, file.path(workFolder, ""cmAnalysisListAp.json"")) + + + # Crockett replication ---------------------------------------------------- + + covarSettings <- FeatureExtraction::createDefaultCovariateSettings() + + getDbCmDataArgs <- CohortMethod::createGetDbCohortMethodDataArgs(washoutPeriod = 365, + firstExposureOnly = TRUE, + removeDuplicateSubjects = TRUE, + studyStartDate = """", + studyEndDate = """", + covariateSettings = covarSettings, + maxCohortSize = 250000) + + createStudyPopArgs <- CohortMethod::createCreateStudyPopulationArgs(removeSubjectsWithPriorOutcome = TRUE, + minDaysAtRisk = 1, + riskWindowStart = 0, + addExposureDaysToStart = FALSE, + riskWindowEnd = 365, + addExposureDaysToEnd = FALSE) + + createPsArgs <- CohortMethod::createCreatePsArgs(control = Cyclops::createControl(cvType = ""auto"", + startingVariance = 0.01, + noiseLevel = ""quiet"", + tolerance = 2e-07, + cvRepetitions = 1), + stopOnError = FALSE) + + matchOnPsArgs <- CohortMethod::createMatchOnPsArgs(maxRatio = 100) + + fitOutcomeModelArgs <- CohortMethod::createFitOutcomeModelArgs(useCovariates = FALSE, + modelType = ""cox"", + stratified = TRUE) + + cmAnalysis <- CohortMethod::createCmAnalysis(analysisId = 1, + description = ""Matching plus simple outcome model"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = createStudyPopArgs, + createPs = TRUE, + createPsArgs = createPsArgs, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgs, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs) + + cmAnalysisList <- list(cmAnalysis) + CohortMethod::saveCmAnalysisList(cmAnalysisList, file.path(workFolder, ""cmAnalysisListIbd.json"")) +} + + +createTcos <- function(outputFolder, exposureId, outcomeId, nestingCohortId = NULL) { + allControlsFile = file.path(outputFolder, ""AllControlsAp.csv"") + if (file.exists(allControlsFile)) { + allControls <- read.csv(allControlsFile) + } else { + pathToCsv <- system.file(""settings"", ""NegativeControlsForCm.csv"", package = ""EvaluatingCaseControl"") + allControls <- read.csv(pathToCsv) + allControls <- allControls[allControls$outcomeId == outcomeId, ] + } + # nestedExposures <- read.csv(file.path(outputFolder, ""NestedExposures.csv"")) + tcoList <- list() + for (i in 1:nrow(allControls)) { + # targetId <- nestedExposures$nestedExposureId[nestedExposures$exposureId == allControls$targetId[i] & + # nestedExposures$nestingId == allControls$nestingId[i]] + # comparatorId <- nestedExposures$nestedExposureId[nestedExposures$exposureId == allControls$comparatorId[i] & + # nestedExposures$nestingId == allControls$nestingId[i]] + targetId <- allControls$targetId[i] + comparatorId <- allControls$comparatorId[i] + + tco <- CohortMethod::createTargetComparatorOutcomes(targetId = targetId, + comparatorId = comparatorId, + outcomeIds = allControls$outcomeId[i], + excludedCovariateConceptIds = c(allControls$targetId[i], allControls$comparatorId[i])) + tcoList[[length(tcoList) + 1]] <- tco + } + return(tcoList) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","EvaluatingCaseControl/R/CreateAllCohorts.R",".R","7912","139","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of EvaluatingCaseControl +# +# 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. + +#' Create the exposure and outcome cohorts +#' +#' @details +#' This function will create the exposure and outcome cohorts following the definitions included in +#' this package. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param cohortDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param cohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' +#' @export +createCohorts <- function(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable, + oracleTempSchema, + outputFolder) { + if (!file.exists(outputFolder)) { + dir.create(outputFolder, recursive = TRUE) + } + conn <- DatabaseConnector::connect(connectionDetails) + + .createCohorts(connection = conn, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder) + + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""EvaluatingCaseControl"") + negativeControls <- read.csv(pathToCsv) + ParallelLogger::logInfo(""- Creating exposure cohorts for negative controls"") + sql <- SqlRender::loadRenderTranslateSql(""ExposureCohorts.sql"", + ""EvaluatingCaseControl"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = cohortDatabaseSchema, + target_cohort_table = cohortTable, + exposure_ids = unique(c(negativeControls$targetId, negativeControls$comparatorId))) + DatabaseConnector::executeSql(conn, sql) + ParallelLogger::logInfo(""- Creating nesting cohorts for negative controls"") + nestingIds <- unique(negativeControls$nestingId) + nestingIds <- nestingIds[!is.na(nestingIds)] + sql <- SqlRender::loadRenderTranslateSql(""NestingCohorts.sql"", + ""EvaluatingCaseControl"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = cohortDatabaseSchema, + target_cohort_table = cohortTable, + nesting_ids = nestingIds) + DatabaseConnector::executeSql(conn, sql) + + ParallelLogger::logInfo(""- Creating nested exposure cohorts for negative controls (for CohortMethod)"") + pathToCsv <- system.file(""settings"", ""NegativeControlsForCm.csv"", package = ""EvaluatingCaseControl"") + negativeControls <- read.csv(pathToCsv) + nestedExposures <- data.frame(exposureId = c(negativeControls$targetId, negativeControls$comparatorId), + nestingId = c(negativeControls$nestingId, negativeControls$nestingId)) + nestedExposures <- unique(nestedExposures) + nestedExposures$nestedExposureId <- 100 + (1:nrow(nestedExposures)) + write.csv(nestedExposures, file.path(outputFolder, ""NestedExposures.csv"")) + colnames(nestedExposures) <- SqlRender::camelCaseToSnakeCase(colnames(nestedExposures)) + DatabaseConnector::insertTable(conn, ""#nested_exposures"", nestedExposures, dropTableIfExists = TRUE, createTable = TRUE, tempTable = TRUE, oracleTempSchema = oracleTempSchema) + sql <- SqlRender::loadRenderTranslateSql(""NestedExposureCohorts.sql"", + ""EvaluatingCaseControl"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + target_database_schema = cohortDatabaseSchema, + target_cohort_table = cohortTable) + DatabaseConnector::executeSql(conn, sql) + + + sql <- ""TRUNCATE TABLE #nested_exposures; DROP TABLE #nested_exposures;"" + sql <- SqlRender::translateSql(sql, targetDialect = connectionDetails$dbms, oracleTempSchema = oracleTempSchema)$sql + DatabaseConnector::executeSql(conn, sql, progressBar = FALSE, reportOverallTime = FALSE) + + # Count cohorts: + sql <- ""SELECT cohort_definition_id, COUNT(*) AS cohort_count FROM @target_database_schema.@target_cohort_table GROUP BY cohort_definition_id"" + sql <- SqlRender::renderSql(sql, + target_database_schema = cohortDatabaseSchema, + target_cohort_table = cohortTable)$sql + sql <- SqlRender::translateSql(sql, targetDialect = connectionDetails$dbms)$sql + counts <- DatabaseConnector::querySql(conn, sql) + + write.csv(counts, file.path(outputFolder, ""CohortCounts.csv"")) + + DatabaseConnector::disconnect(conn) +} + + +addCohortNames <- function(data, IdColumnName = ""cohortDefinitionId"", nameColumnName = ""cohortName"") { + pathToCsv <- system.file(""settings"", ""CohortsToCreate.csv"", package = ""EvaluatingCaseControl"") + cohortsToCreate <- read.csv(pathToCsv) + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""EvaluatingCaseControl"") + negativeControls <- read.csv(pathToCsv) + + idToName <- data.frame(cohortId = c(cohortsToCreate$cohortId, negativeControls$conceptId), + cohortName = c(as.character(cohortsToCreate$name), as.character(negativeControls$name))) + names(idToName)[1] <- IdColumnName + names(idToName)[2] <- nameColumnName + data <- merge(data, idToName, all.x = TRUE) + # Change order of columns: + idCol <- which(colnames(data) == IdColumnName) + if (idCol < ncol(data) - 1) { + data <- data[, c(1:idCol, ncol(data) , (idCol+1):(ncol(data)-1))] + } + return(data) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","EvaluatingCaseControl/R/CreateFiguresAndTables.R",".R","51554","874","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of EvaluatingCaseControl +# +# 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. + +#' @title +#' Create figures and tables +#' +#' @description +#' Create figures and tables for the paper. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +createFiguresAndTables <- function(connectionDetails, + cdmDatabaseSchema, + oracleTempSchema, + outputFolder) { + connection <- DatabaseConnector::connect(connectionDetails) + + ParallelLogger::logInfo(""Fetching population characteristics for Crockett study"") + getCharacteristics(ccFile = file.path(outputFolder, ""ccIbd"", ""caseControls_cd1_cc1_o3.rds""), + connection = connection, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + resultsFolder = file.path(outputFolder, ""resultsIbd"")) + + ParallelLogger::logInfo(""Fetching population characteristics for Chou study"") + getCharacteristics(ccFile = file.path(outputFolder, ""ccAp"", ""caseControls_cd1_n1_cc1_o2.rds""), + connection = connection, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + resultsFolder = file.path(outputFolder, ""resultsAp"")) + + createVisitPlot(resultsFolder = file.path(outputFolder, ""resultsIbd"")) + createVisitPlot(resultsFolder = file.path(outputFolder, ""resultsAp"")) + createCharacteristicsTable(resultsFolder = file.path(outputFolder, ""resultsIbd"")) + createCharacteristicsTable(resultsFolder = file.path(outputFolder, ""resultsAp"")) + plotOddsRatios(ccSummaryFile = file.path(outputFolder, ""ccSummaryIbd.rds""), + exposureId = 5, + exposureName = ""Isotretinoin"", + resultsFolder = file.path(outputFolder, ""resultsIbd""), + pubOr = 4.36, + pubLb = 1.97, + pubUb = 9.66) + plotOddsRatios(ccSummaryFile = file.path(outputFolder, ""ccSummaryAp.rds""), + exposureId = 4, + exposureName = ""DPP-4"", + resultsFolder = file.path(outputFolder, ""resultsAp""), + pubOr = 1.04, + pubLb = 0.89, + pubUb = 1.21) + + calibrateCi(ccSummaryFile = file.path(outputFolder, ""ccSummaryIbd.rds""), + exposureId = 5, + allControlsFile = file.path(outputFolder, ""AllControlsIbd.csv""), + resultsFolder = file.path(outputFolder, ""resultsIbd"")) + calibrateCi(ccSummaryFile = file.path(outputFolder, ""ccSummaryAp.rds""), + exposureId = 4, + allControlsFile = file.path(outputFolder, ""AllControlsAp.csv""), + resultsFolder = file.path(outputFolder, ""resultsAp"")) + + createEstimatesAppendix(outputFolder = outputFolder) +} + +calibrateCi <- function(ccSummaryFile, exposureId, allControlsFile, resultsFolder) { + ccSummary <- readRDS(ccSummaryFile) + allControls <- read.csv(allControlsFile) + allControls <- allControls[, c(""targetId"", ""outcomeId"", ""targetEffectSize"")] + colnames(allControls) <- c(""exposureId"", ""outcomeId"", ""targetEffectSize"") + allControls <- merge(allControls, ccSummary) + negativeControls <- allControls[allControls$targetEffectSize == 1, ] + hoi <- ccSummary[ccSummary$exposureId == exposureId & ccSummary$outcomeId < 10000, ] + null <- EmpiricalCalibration::fitNull(logRr = negativeControls$logRr, + seLogRr = negativeControls$seLogRr) + hoiCal <- EmpiricalCalibration::calibrateP(null, + logRr = hoi$logRr, + seLogRr = hoi$seLogRr) + hoi$calP <- hoiCal + model <- EmpiricalCalibration::fitSystematicErrorModel(logRr = allControls$logRr, + seLogRr = allControls$seLogRr, + trueLogRr = log(allControls$targetEffectSize)) + + hoiCal <- EmpiricalCalibration::calibrateConfidenceInterval(logRr = hoi$logRr, + seLogRr = hoi$seLogRr, + model = model) + hoi$calRr <- exp(hoiCal$logRr) + hoi$calCi95lb <- exp(hoiCal$logLb95Rr) + hoi$calCi95ub <- exp(hoiCal$logUb95Rr) + fileName <- file.path(resultsFolder, ""EmpiricalCalibration.csv"") + write.csv(hoi, fileName, row.names = FALSE) + fileName <- file.path(resultsFolder, ""TrueAndObservedForest.png"") + EmpiricalCalibration::plotTrueAndObserved(logRr = allControls$logRr, + seLogRr = allControls$seLogRr, + trueLogRr = log(allControls$targetEffectSize), + fileName = fileName) +} + +plotOddsRatios <- function(ccSummaryFile, exposureId, exposureName, resultsFolder, pubOr, pubLb, pubUb) { + ccSummary <- readRDS(ccSummaryFile) + ccSummary <- ccSummary[ccSummary$outcomeId < 10000, ] # No positive controls + estimates <- data.frame(logRr = ccSummary$logRr, + seLogRr = ccSummary$seLogRr, + label = ""Negative control (our replication)"", + stringsAsFactors = FALSE) + estimates$label[ccSummary$exposureId == exposureId] <- paste(exposureName, ""(our replication)"") + estimates <- rbind(estimates, + data.frame(logRr = log(pubOr), + seLogRr = -(log(pubUb) - log(pubLb)) / (2*qnorm(0.025)), + label = paste(exposureName, ""(original study)""), + stringsAsFactors = FALSE)) + + alpha <- 0.05 + idx <- estimates$label == ""Negative control (our replication)"" + null <- EmpiricalCalibration::fitNull(estimates$logRr[idx], estimates$seLogRr[idx]) + x <- exp(seq(log(0.25), log(10), by = 0.01)) + y <- EmpiricalCalibration:::logRrtoSE(log(x), alpha, null[1], null[2]) + seTheoretical <- sapply(x, FUN = function(x) { + abs(log(x))/qnorm(1 - alpha/2) + }) + breaks <- c(0.25, 0.5, 1, 2, 4, 6, 8, 10) + theme <- ggplot2::element_text(colour = ""#000000"", size = 12) + themeRA <- ggplot2::element_text(colour = ""#000000"", size = 12, hjust = 1) + plot <- ggplot2::ggplot(data.frame(x, y, seTheoretical), ggplot2::aes(x = x, y = y), environment = environment()) + + ggplot2::geom_vline(xintercept = breaks, colour = ""#AAAAAA"", lty = 1, size = 0.5) + + ggplot2::geom_vline(xintercept = 1, size = 0.7) + + ggplot2::geom_area(fill = rgb(1, 0.5, 0, alpha = 0.5), color = rgb(1, 0.5, 0), size = 1, alpha = 0.5) + + ggplot2::geom_area(ggplot2::aes(y = seTheoretical), + fill = rgb(0, 0, 0), + colour = rgb(0, 0, 0, alpha = 0.1), + alpha = 0.1) + + ggplot2::geom_line(ggplot2::aes(y = seTheoretical), + colour = rgb(0, 0, 0), + linetype = ""dashed"", + size = 1, + alpha = 0.5) + + ggplot2::geom_point(ggplot2::aes(x, y, shape = label, color = label, fill = label, size = label), + data = data.frame(x = exp(estimates$logRr), y = estimates$seLogRr, label = estimates$label), + alpha = 0.7) + + ggplot2::scale_color_manual(values = c(rgb(0, 0, 0), rgb(0, 0, 0), rgb(0, 0, 0.8))) + + ggplot2::scale_fill_manual(values = c(rgb(0.8, 0, 0.8, alpha = 0.8), rgb(1, 1, 0, alpha = 0.8), rgb(0, 0, 0.8, alpha = 0.5))) + + ggplot2::scale_shape_manual(values = c(24, 23, 21)) + + ggplot2::scale_size_manual(values = c(3, 3, 2)) + + ggplot2::geom_hline(yintercept = 0) + + ggplot2::scale_x_continuous(""Odds ratio"", trans = ""log10"", limits = c(0.25, 10), breaks = breaks, labels = breaks) + + ggplot2::scale_y_continuous(""Standard Error"", limits = c(0, 1.5)) + + ggplot2::theme(panel.grid.minor = ggplot2::element_blank(), + panel.background = ggplot2::element_rect(fill = ""#FAFAFA"", colour = NA), + panel.grid.major = ggplot2::element_blank(), + axis.ticks = ggplot2::element_blank(), axis.text.y = themeRA, + axis.text.x = theme, legend.key = ggplot2::element_blank(), + strip.text.x = theme, strip.background = ggplot2::element_blank(), + legend.position = ""top"", + legend.title = ggplot2::element_blank()) + + fileName <- file.path(resultsFolder, ""estimates.png"") + ggplot2::ggsave(fileName, plot, width = 6.1, height = 4.5, dpi = 400) + + estimates$seLogRr[estimates$label == ""Negative control (our replication)""] <- 3 + plot <- ggplot2::ggplot(data.frame(x, y, seTheoretical), ggplot2::aes(x = x, y = y), environment = environment()) + + ggplot2::geom_vline(xintercept = breaks, colour = ""#AAAAAA"", lty = 1, size = 0.5) + + ggplot2::geom_vline(xintercept = 1, size = 0.7) + + # ggplot2::geom_area(fill = rgb(1, 0.5, 0, alpha = 0.5), color = rgb(1, 0.5, 0), size = 1, alpha = 0.5) + + ggplot2::geom_area(ggplot2::aes(y = seTheoretical), + fill = rgb(0, 0, 0), + colour = rgb(0, 0, 0, alpha = 0.1), + alpha = 0.1) + + ggplot2::geom_line(ggplot2::aes(y = seTheoretical), + colour = rgb(0, 0, 0), + linetype = ""dashed"", + size = 1, + alpha = 0.5) + + ggplot2::geom_point(ggplot2::aes(x, y, shape = label, color = label, fill = label, size = label), + data = data.frame(x = exp(estimates$logRr), y = estimates$seLogRr, label = estimates$label), + alpha = 0.7) + + ggplot2::scale_color_manual(values = c(rgb(0, 0, 0), rgb(0, 0, 0), rgb(0, 0, 0.8))) + + ggplot2::scale_fill_manual(values = c(rgb(0.8, 0, 0.8, alpha = 0.8), rgb(1, 1, 0, alpha = 0.8), rgb(0, 0, 0.8, alpha = 0.5))) + + ggplot2::scale_shape_manual(values = c(24, 23, 21)) + + ggplot2::scale_size_manual(values = c(3, 3, 2)) + + ggplot2::geom_hline(yintercept = 0) + + ggplot2::scale_x_continuous(""Odds ratio"", trans = ""log10"", limits = c(0.25, 10), breaks = breaks, labels = breaks) + + ggplot2::scale_y_continuous(""Standard Error"", limits = c(0, 1.5)) + + ggplot2::theme(panel.grid.minor = ggplot2::element_blank(), + panel.background = ggplot2::element_rect(fill = ""#FAFAFA"", colour = NA), + panel.grid.major = ggplot2::element_blank(), + axis.ticks = ggplot2::element_blank(), axis.text.y = themeRA, + axis.text.x = theme, legend.key = ggplot2::element_blank(), + strip.text.x = theme, strip.background = ggplot2::element_blank(), + legend.position = ""top"", + legend.title = ggplot2::element_blank()) + + fileName <- file.path(resultsFolder, ""estimatesOriginalOur.png"") + ggplot2::ggsave(fileName, plot, width = 6.1, height = 4.5, dpi = 400) + + estimates$seLogRr[estimates$label != paste(exposureName, ""(original study)"")] <- 3 + plot <- ggplot2::ggplot(data.frame(x, y, seTheoretical), ggplot2::aes(x = x, y = y), environment = environment()) + + ggplot2::geom_vline(xintercept = breaks, colour = ""#AAAAAA"", lty = 1, size = 0.5) + + ggplot2::geom_vline(xintercept = 1, size = 0.7) + + # ggplot2::geom_area(fill = rgb(1, 0.5, 0, alpha = 0.5), color = rgb(1, 0.5, 0), size = 1, alpha = 0.5) + + ggplot2::geom_area(ggplot2::aes(y = seTheoretical), + fill = rgb(0, 0, 0), + colour = rgb(0, 0, 0, alpha = 0.1), + alpha = 0.1) + + ggplot2::geom_line(ggplot2::aes(y = seTheoretical), + colour = rgb(0, 0, 0), + linetype = ""dashed"", + size = 1, + alpha = 0.5) + + ggplot2::geom_point(ggplot2::aes(x, y, shape = label, color = label, fill = label, size = label), + data = data.frame(x = exp(estimates$logRr), y = estimates$seLogRr, label = estimates$label), + alpha = 0.7) + + ggplot2::scale_color_manual(values = c(rgb(0, 0, 0), rgb(0, 0, 0), rgb(0, 0, 0.8))) + + ggplot2::scale_fill_manual(values = c(rgb(0.8, 0, 0.8, alpha = 0.8), rgb(1, 1, 0, alpha = 0.8), rgb(0, 0, 0.8, alpha = 0.5))) + + ggplot2::scale_shape_manual(values = c(24, 23, 21)) + + ggplot2::scale_size_manual(values = c(3, 3, 2)) + + ggplot2::geom_hline(yintercept = 0) + + ggplot2::scale_x_continuous(""Odds ratio"", trans = ""log10"", limits = c(0.25, 10), breaks = breaks, labels = breaks) + + ggplot2::scale_y_continuous(""Standard Error"", limits = c(0, 1.5)) + + ggplot2::theme(panel.grid.minor = ggplot2::element_blank(), + panel.background = ggplot2::element_rect(fill = ""#FAFAFA"", colour = NA), + panel.grid.major = ggplot2::element_blank(), + axis.ticks = ggplot2::element_blank(), axis.text.y = themeRA, + axis.text.x = theme, legend.key = ggplot2::element_blank(), + strip.text.x = theme, strip.background = ggplot2::element_blank(), + legend.position = ""top"", + legend.title = ggplot2::element_blank()) + + fileName <- file.path(resultsFolder, ""estimatesOriginal.png"") + ggplot2::ggsave(fileName, plot, width = 6.1, height = 4.5, dpi = 400) +} + +createCharacteristicsTable <- function(resultsFolder) { + covariateData1 <- FeatureExtraction::loadCovariateData(file.path(resultsFolder, ""covsCases"")) + covariateData2 <- FeatureExtraction::loadCovariateData(file.path(resultsFolder, ""covsControls"")) + table1 <- FeatureExtraction::createTable1(covariateData1 = covariateData1, covariateData2 = covariateData2) + write.csv(table1, file.path(resultsFolder, ""characteristics.csv""), row.names = FALSE) +} + +createCharacteristicsByExposureTable <- function(resultsFolder) { + covariateData1 <- FeatureExtraction::loadCovariateData(file.path(resultsFolder, ""covsExposed"")) + covariateData2 <- FeatureExtraction::loadCovariateData(file.path(resultsFolder, ""covsUnexposed"")) + table1 <- FeatureExtraction::createTable1(covariateData1 = covariateData1, covariateData2 = covariateData2) + write.csv(table1, file.path(resultsFolder, ""characteristicsByExposure.csv""), row.names = FALSE) +} + +createVisitPlot <- function(resultsFolder) { + visitCounts <- readRDS(file.path(resultsFolder, ""visitCounts.rds"")) + visitCounts$label <- ""Cases"" + visitCounts$label[!visitCounts$isCase] <- ""Controls"" + plot <- ggplot2::ggplot(visitCounts, ggplot2::aes(x = day, y = rate, group = label, color = label)) + + ggplot2::geom_vline(xintercept = 0, color = rgb(0, 0, 0), size = 0.5) + + ggplot2::geom_line(alpha = 0.7, size = 1) + + ggplot2::scale_color_manual(values = c(rgb(0.8, 0, 0), rgb(0, 0, 0.8))) + + ggplot2::labs(x = ""Days relative to index date"", y = ""Visits / persons"") + + ggplot2::theme(legend.title = ggplot2::element_blank(), + legend.position = ""top"") + ggplot2::ggsave(file.path(resultsFolder, ""priorVisitRates.png""), plot, width = 5, height = 4, dpi = 400) +} + + +getCharacteristics <- function(ccFile, connection, cdmDatabaseSchema, oracleTempSchema, resultsFolder) { + if (!file.exists(resultsFolder)) + dir.create(resultsFolder) + cc <- readRDS(ccFile) + # stratumIds <- unique(cc$stratumId) + # sampledStratumIds <- sample(stratumIds, 10000, replace = FALSE) + # cc <- cc[cc$stratumId %in% sampledStratumIds, ] + tableToUpload <- data.frame(subjectId = cc$personId, + cohortStartDate = cc$indexDate, + cohortDefinitionId = as.integer(cc$isCase)) + + colnames(tableToUpload) <- SqlRender::camelCaseToSnakeCase(colnames(tableToUpload)) + + connection <- DatabaseConnector::connect(connectionDetails) + DatabaseConnector::insertTable(connection = connection, + tableName = ""scratch.dbo.mschuemi_temp"", + data = tableToUpload, + dropTableIfExists = TRUE, + createTable = TRUE, + tempTable = FALSE, + oracleTempSchema = oracleTempSchema, + useMppBulkLoad = TRUE) + disconnect(connection) + executeSql(connection, ""DROP TABLE scratch.dbo.mschuemi_temp"") + querySql(connection, ""SELECT COUNT(*) FROM scratch.dbo.mschuemi_temp"") + + covariateSettings <- FeatureExtraction::createCovariateSettings(useConditionGroupEraLongTerm = TRUE, + useDrugGroupEraLongTerm = TRUE, + useProcedureOccurrenceLongTerm = TRUE, + useMeasurementLongTerm = TRUE, + useMeasurementRangeGroupLongTerm = TRUE, + useObservationLongTerm = TRUE, + endDays = -30, + longTermStartDays = -365) + covsCases <- FeatureExtraction::getDbCovariateData(connection = connection, + oracleTempSchema = oracleTempSchema, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortTable = ""#temp"", + cohortTableIsTemp = TRUE, + cohortId = 1, + covariateSettings = covariateSettings, + aggregated = TRUE) + FeatureExtraction::saveCovariateData(covsCases, file.path(resultsFolder, ""covsCases"")) + covsControls <- FeatureExtraction::getDbCovariateData(connection = connection, + oracleTempSchema = oracleTempSchema, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortTable = ""#temp"", + cohortTableIsTemp = TRUE, + cohortId = 0, + covariateSettings = covariateSettings, + aggregated = TRUE) + FeatureExtraction::saveCovariateData(covsControls, file.path(resultsFolder, ""covsControls"")) + + sql <- ""SELECT DATEDIFF(DAY, cohort_start_date, visit_start_date) AS day, + cohort_definition_id AS is_case, + COUNT(*) AS visit_count + FROM #temp + INNER JOIN @cdm_database_schema.visit_occurrence + ON subject_id = person_id + WHERE cohort_start_date > visit_start_date + AND DATEDIFF(DAY, cohort_start_date, visit_start_date) > -365 + GROUP BY DATEDIFF(DAY, cohort_start_date, visit_start_date), + cohort_definition_id;"" + sql <- SqlRender::renderSql(sql = sql, + cdm_database_schema = cdmDatabaseSchema)$sql + sql <- SqlRender::translateSql(sql = sql, + targetDialect = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema)$sql + visitCounts <- querySql(connection = connection, sql = sql) + colnames(visitCounts) <- SqlRender::snakeCaseToCamelCase(colnames(visitCounts)) + cc$personCount <- 1 + personCounts <- aggregate(personCount ~ isCase, cc, sum) + visitCounts <- merge(visitCounts, personCounts) + visitCounts$rate <- visitCounts$visitCount / visitCounts$personCount + saveRDS(visitCounts, file.path(resultsFolder, ""visitCounts.rds"")) + + sql <- ""TRUNCATE TABLE #temp; DROP TABLE #temp;"" + sql <- SqlRender::translateSql(sql = sql, + targetDialect = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema)$sql + DatabaseConnector::executeSql(connection = connection, + sql = sql, + progressBar = FALSE, + reportOverallTime = FALSE) +} + +getCharacteristicsByExposure <- function(ccFile, connection, cdmDatabaseSchema, oracleTempSchema, resultsFolder) { + ccdFile <- file.path(outputFolder, ""ccAp"", ""ccd_cd1_n1_cc1_o2_ed1_e4_ccd1.rds"") + ccFile <- file.path(outputFolder, ""ccAp"", ""caseControls_cd1_n1_cc1_o2.rds"") + resultsFolder = file.path(outputFolder, ""resultsAp"") + + ccdFile <- file.path(outputFolder, ""ccIbd"", ""ccd_cd1_cc1_o3_ed1_e5_ccd1.rds"") + ccFile <- file.path(outputFolder, ""ccIbd"", ""caseControls_cd1_cc1_o3.rds"") + resultsFolder = file.path(outputFolder, ""resultsIbd"") + + ccd <- readRDS(ccdFile) + cc <- readRDS(ccFile) + + # ccd <- ccd[!ccd$isCase, ] + # cc <- cc[!cc$isCase, ] + tableToUpload <- data.frame(subjectId = cc$personId, + cohortStartDate = cc$indexDate, + cohortDefinitionId = as.integer(ccd$exposed), + exposed = as.integer(ccd$exposed), + isCase = as.integer(cc$isCase)) + + colnames(tableToUpload) <- SqlRender::camelCaseToSnakeCase(colnames(tableToUpload)) + + # connection <- DatabaseConnector::connect(connectionDetails) + DatabaseConnector::insertTable(connection = connection, + tableName = ""scratch.dbo.mschuemi_temp"", + data = tableToUpload, + dropTableIfExists = TRUE, + createTable = TRUE, + tempTable = FALSE, + oracleTempSchema = oracleTempSchema, + useMppBulkLoad = TRUE) + # disconnect(connection) + # executeSql(connection, ""DROP TABLE scratch.dbo.mschuemi_temp"") + # querySql(connection, ""SELECT COUNT(*) FROM scratch.dbo.mschuemi_temp"") + + covariateSettings <- FeatureExtraction::createCovariateSettings(useConditionGroupEraLongTerm = TRUE, + useDrugGroupEraLongTerm = TRUE, + useProcedureOccurrenceLongTerm = TRUE, + useMeasurementLongTerm = TRUE, + useMeasurementRangeGroupLongTerm = TRUE, + useObservationLongTerm = TRUE, + endDays = -30, + longTermStartDays = -365) + covsExposed <- FeatureExtraction::getDbCovariateData(connection = connection, + oracleTempSchema = oracleTempSchema, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = ""scratch.dbo"", + cohortTable = ""mschuemi_temp"", + cohortTableIsTemp = FALSE, + cohortId = 1, + covariateSettings = covariateSettings, + aggregated = TRUE) + FeatureExtraction::saveCovariateData(covsExposed, file.path(resultsFolder, ""covsExposed"")) + covsUnexposed <- FeatureExtraction::getDbCovariateData(connection = connection, + oracleTempSchema = oracleTempSchema, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = ""scratch.dbo"", + cohortTable = ""mschuemi_temp"", + cohortTableIsTemp = FALSE, + cohortId = 0, + covariateSettings = covariateSettings, + aggregated = TRUE) + FeatureExtraction::saveCovariateData(covsUnexposed, file.path(resultsFolder, ""covsUnexposed"")) + + sql <- ""SELECT DATEDIFF(DAY, cohort_start_date, visit_start_date) AS day, + exposed, + is_case, + COUNT(*) AS visit_count + FROM scratch.dbo.mschuemi_temp + INNER JOIN @cdm_database_schema.visit_occurrence + ON subject_id = person_id + WHERE cohort_start_date > visit_start_date + AND DATEDIFF(DAY, cohort_start_date, visit_start_date) > -365 + GROUP BY DATEDIFF(DAY, cohort_start_date, visit_start_date), + exposed, + is_case;"" + sql <- SqlRender::renderSql(sql = sql, + cdm_database_schema = cdmDatabaseSchema)$sql + sql <- SqlRender::translateSql(sql = sql, + targetDialect = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema)$sql + visitCounts <- querySql(connection = connection, sql = sql) + colnames(visitCounts) <- SqlRender::snakeCaseToCamelCase(colnames(visitCounts)) + ccd$personCount <- 1 + personCounts <- aggregate(personCount ~ exposed + isCase, ccd, sum) + visitCounts <- merge(visitCounts, personCounts) + visitCounts$rate <- visitCounts$visitCount / visitCounts$personCount + saveRDS(visitCounts, file.path(resultsFolder, ""visitCountsByExposure.rds"")) + + executeSql(connection, ""DROP TABLE scratch.dbo.mschuemi_temp"") + # disconnect(connection) +} + + +createPsPlot <- function(ccFile, ccdFile, connection, cdmDatabaseSchema, oracleTempSchema, resultsFolder) { + resultsFolder <- file.path(outputFolder, ""resultsIbd"") + ccdFile <- ""r:/EvaluatingCaseControl_ccae/ccIbd/ccd_cd1_cc1_o3_ed1_e5_ccd1.rds"" + ccFile = file.path(outputFolder, ""ccIbd"", ""caseControls_cd1_cc1_o3.rds"") + + resultsFolder <- file.path(outputFolder, ""resultsAp"") + ccdFile <- ""r:/EvaluatingCaseControl_ccae/ccAp/ccd_cd1_n1_cc1_o2_ed1_e4_ccd1.rds"" + ccFile = file.path(outputFolder, ""ccAp"", ""caseControls_cd1_n1_cc1_o2.rds"") + cc <- readRDS(ccFile) + ccd <- readRDS(ccdFile) + cc$rowId <- 1:nrow(cc) + m <- merge(cc, ccd) + tableToUpload <- data.frame(rowId = cc$rowId, + subjectId = cc$personId, + cohortStartDate = cc$indexDate, + cohortDefinitionId = as.integer(cc$isCase)) + + colnames(tableToUpload) <- SqlRender::camelCaseToSnakeCase(colnames(tableToUpload)) + + connection <- DatabaseConnector::connect(connectionDetails) + # debug(DatabaseConnector:::.bulkLoadPdw) + DatabaseConnector::insertTable(connection = connection, + tableName = ""scratch.dbo.mschuemi_temp"", + data = tableToUpload, + dropTableIfExists = TRUE, + createTable = TRUE, + tempTable = FALSE, + oracleTempSchema = oracleTempSchema, + useMppBulkLoad = TRUE) + # disconnect(connection) + # executeSql(connection, ""DROP TABLE scratch.dbo.mschuemi_temp"") + # querySql(connection, ""SELECT COUNT(*) FROM scratch.dbo.mschuemi_temp"") + + covariateSettings <- FeatureExtraction::createCovariateSettings(useConditionGroupEraLongTerm = TRUE, + useDrugGroupEraLongTerm = TRUE, + useProcedureOccurrenceLongTerm = TRUE, + useMeasurementLongTerm = TRUE, + useMeasurementRangeGroupLongTerm = TRUE, + useObservationLongTerm = TRUE, + endDays = -30, + longTermStartDays = -365) + covs <- FeatureExtraction::getDbCovariateData(connection = connection, + oracleTempSchema = oracleTempSchema, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = ""scratch.dbo"", + cohortTable = ""mschuemi_temp"", + cohortTableIsTemp = FALSE, + rowIdField = ""row_id"", + covariateSettings = covariateSettings, + aggregated = FALSE) + DatabaseConnector::executeSql(connection, ""DROP TABLE scratch.dbo.mschuemi_temp"") + DatabaseConnector::disconnect(connection) + FeatureExtraction::saveCovariateData(covs, file.path(resultsFolder, ""covsNotAggregated"")) + + tidyCovs <- FeatureExtraction::tidyCovariateData(covs) + + # Model probability of exposure --------------------------------- + outcomes <- data.frame(rowId = m$rowId, + y = m$exposed) + prior <- Cyclops::createPrior(""laplace"", useCrossValidation = TRUE, exclude = c(0)) + control <- Cyclops::createControl(cvRepetitions = 1, + threads = 10, + fold = 5, + cvType = ""auto"") + cyclopsData <- Cyclops::convertToCyclopsData(ff::as.ffdf(outcomes), tidyCovs$covariates, modelType = ""lr"") + fit <- Cyclops::fitCyclopsModel(cyclopsData = cyclopsData, + prior = prior, + control = control) + p <- predict(fit) + p <- data.frame(rowId = as.numeric(names(p)), + propensityScore = as.vector(p)) + ps <- merge(outcomes, p) + ps$treatment <- ps$y + fileName <- file.path(resultsFolder, ""predictabilityExposure.png"") + CohortMethod::plotPs(ps, fileName = fileName, targetLabel = ""Exposed"", comparatorLabel = ""Unexposed"") + CohortMethod::computePsAuc(ps) + + # Model probability of case vs control --------------------------------- + outcomes <- data.frame(rowId = m$rowId, + y = as.integer(m$isCase)) + prior <- Cyclops::createPrior(""laplace"", useCrossValidation = TRUE, exclude = c(0)) + control <- Cyclops::createControl(cvRepetitions = 1, + threads = 10, + fold = 5, + cvType = ""auto"") + cyclopsData <- Cyclops::convertToCyclopsData(ff::as.ffdf(outcomes), tidyCovs$covariates, modelType = ""lr"") + fit <- Cyclops::fitCyclopsModel(cyclopsData = cyclopsData, + prior = prior, + control = control) + p <- predict(fit) + p <- data.frame(rowId = as.numeric(names(p)), + propensityScore = as.vector(p)) + ps <- merge(outcomes, p) + ps$treatment <- ps$y + fileName <- file.path(resultsFolder, ""predictabilityCaseControl.png"") + CohortMethod::plotPs(ps, fileName = fileName, targetLabel = ""Cases"", comparatorLabel = ""Controls"") + CohortMethod::computePsAuc(ps) +} + +createCombinedEstimatesTable <- function(outputFolder) { + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""EvaluatingCaseControl"") + negativeControls <- read.csv(pathToCsv, stringsAsFactors = FALSE) + + + ccSummary <- readRDS(file.path(outputFolder, ""ccSummaryIbd.rds"")) + ccSummary <- ccSummary[ccSummary$outcomeId < 10000, ] # No positive controls + + estimatesIbd <- merge(ccSummary, + data.frame(exposureId = negativeControls$targetId, + outcomeId = negativeControls$outcomeId, + nestingCohortId = negativeControls$nestingId, + exposureName = negativeControls$targetName, + nestingName = negativeControls$nestingName, + outcomeName = negativeControls$outcomeName, + stringsAsFactors = FALSE), + all.x = TRUE) + estimatesIbd$type <- ""Negative control"" + estimatesIbd$type[estimatesIbd$exposureId == 5] <- ""Exposure of interest"" + estimatesIbd$exposureName[estimatesIbd$exposureId == 5] <- ""Isotretinoin"" + estimatesIbd$nestingName[estimatesIbd$exposureId == 5] <- """" + estimatesIbd$outcomeName[estimatesIbd$exposureId == 5] <- ""Ulcerative colitis"" + null <- EmpiricalCalibration::fitNull(logRr = estimatesIbd$logRr[estimatesIbd$type == ""Negative control""], + seLogRr = estimatesIbd$seLogRr[estimatesIbd$type == ""Negative control""]) + estimatesIbd$calP <- EmpiricalCalibration::calibrateP(null = null, + logRr = estimatesIbd$logRr, + seLogRr = estimatesIbd$seLogRr) + + ccSummary <- readRDS(file.path(outputFolder, ""ccSummaryAp.rds"")) + ccSummary <- ccSummary[ccSummary$outcomeId < 10000, ] # No positive controls + + estimatesAp <- merge(ccSummary, + data.frame(exposureId = negativeControls$targetId, + outcomeId = negativeControls$outcomeId, + nestingCohortId = negativeControls$nestingId, + exposureName = negativeControls$targetName, + nestingName = negativeControls$nestingName, + outcomeName = negativeControls$outcomeName, + stringsAsFactors = FALSE), + all.x = TRUE) + estimatesAp$type <- ""Negative control"" + estimatesAp$type[estimatesAp$exposureId == 4] <- ""Exposure of interest"" + estimatesAp$exposureName[estimatesAp$exposureId == 4] <- ""DPP-4 inhibitors"" + estimatesAp$nestingName[estimatesAp$exposureId == 4] <- ""Type 2 Diabetes Mellitus"" + estimatesAp$outcomeName[estimatesAp$exposureId == 4] <- ""Acute pancreatitis"" + null <- EmpiricalCalibration::fitNull(logRr = estimatesAp$logRr[estimatesAp$type == ""Negative control""], + seLogRr = estimatesAp$seLogRr[estimatesAp$type == ""Negative control""]) + estimatesAp$calP <- EmpiricalCalibration::calibrateP(null = null, + logRr = estimatesAp$logRr, + seLogRr = estimatesAp$seLogRr) + + estimates <- rbind(estimatesIbd, estimatesAp) + write.csv(estimates, file.path(outputFolder, ""AllEstimates.csv""), row.names = FALSE) +} + + + + +createEstimatesAppendix <- function(outputFolder) { + estimates <- read.csv(file.path(outputFolder, ""AllEstimates.csv"")) + estimates <- estimates[, c(""outcomeName"", ""exposureName"", ""nestingName"", ""type"", ""cases"", ""controls"", ""exposedCases"", ""exposedControls"", ""rr"", ""ci95lb"", ""ci95ub"", ""p"", ""calP"")] + colnames(estimates) <- c(""Outcome"", ""Exposure"", ""Nesting cohort"", ""Type"", ""Cases"", ""Controls"", ""Exposed cases"", ""Exposed controls"", ""Odds Ratio"", ""CI95LB"", ""CI95UB"", ""P"", ""Calibrated P"") + write.csv(estimates, file.path(outputFolder, ""SupplementaryTableS1.csv""), row.names = FALSE) +} + + + +plotOddsRatiosCombined <- function(outputFolder) { + estimates <- read.csv(file.path(outputFolder, ""AllEstimates.csv""), stringsAsFactors = FALSE) + estimates <- estimates[, c(""type"", ""outcomeName"", ""logRr"", ""seLogRr"")] + estimates$type[estimates$type == ""Negative control""] <- ""Negative control (our replication)"" + estimates$type[estimates$type == ""Exposure of interest""] <- ""Exposure of interest (our replication)"" + estimates$study <- ""Crockett"" + estimates$study[estimates$outcomeName == ""Acute pancreatitis""] <- ""Chou"" + estimates$outcomeName <- NULL + estimates <- rbind(estimates, + data.frame(type = ""Exposure of interest (original study)"", + logRr = log(c(4.36, 1.04)), + seLogRr = c(-(log(9.66) - log(1.97)) / (2*qnorm(0.025)), -(log(1.21) - log(0.89)) / (2*qnorm(0.025))), + study = c(""Crockett"", ""Chou""), + stringsAsFactors = FALSE)) + estimates$x <- exp(estimates$logRr) + estimates$y <- estimates$seLogRr + estimates$study <- factor(estimates$study, levels = c(""Crockett"", ""Chou"")) + + getArea <- function(study, alpha = 0.05) { + idx <- estimates$type == ""Negative control (our replication)"" & estimates$study == study + null <- EmpiricalCalibration::fitNull(estimates$logRr[idx], estimates$seLogRr[idx]) + x <- exp(seq(log(0.25), log(10), by = 0.01)) + y <- EmpiricalCalibration:::logRrtoSE(log(x), alpha, null[1], null[2]) + seTheoretical <- sapply(x, FUN = function(x) { + abs(log(x))/qnorm(1 - 0.05/2) + }) + return(data.frame(study = study, x = x, y = y, seTheoretical = seTheoretical)) + } + area <- rbind(getArea(""Crockett""), getArea(""Chou"")) + + + + breaks <- c(0.25, 0.5, 1, 2, 4, 6, 8, 10) + theme <- ggplot2::element_text(colour = ""#000000"", size = 10) + themeRA <- ggplot2::element_text(colour = ""#000000"", size = 10, hjust = 1) + plot <- ggplot2::ggplot(estimates, ggplot2::aes(x = x, y = y), environment = environment()) + + ggplot2::geom_vline(xintercept = breaks, colour = ""#AAAAAA"", lty = 1, size = 0.5) + + ggplot2::geom_vline(xintercept = 1, size = 0.7) + + ggplot2::geom_area(fill = rgb(1, 0.5, 0, alpha = 0.5), color = rgb(1, 0.5, 0), size = 0.5, alpha = 0.5, data = area) + + ggplot2::geom_area(ggplot2::aes(y = seTheoretical), + fill = rgb(0, 0, 0), + colour = rgb(0, 0, 0, alpha = 0.1), + alpha = 0.1, + data = area) + + ggplot2::geom_line(ggplot2::aes(y = seTheoretical), + colour = rgb(0, 0, 0), + linetype = ""dashed"", + size = 1, + alpha = 0.5, + data = area) + + ggplot2::geom_point(ggplot2::aes(shape = type, color = type, fill = type, size = type), alpha = 0.6) + + ggplot2::geom_point(ggplot2::aes(shape = type, color = type, fill = type, size = type), alpha = 0.6, data = estimates[estimates$type != ""Negative control (our replication)"", ]) + + ggplot2::scale_color_manual(values = c(rgb(0, 0, 0), rgb(0, 0, 0), rgb(0, 0, 0.8))) + + ggplot2::scale_fill_manual(values = c(rgb(0.8, 0, 0.8, alpha = 0.8), rgb(1, 1, 0, alpha = 0.8), rgb(0, 0, 0.8, alpha = 0.5))) + + ggplot2::scale_shape_manual(values = c(24, 23, 21)) + + ggplot2::scale_size_manual(values = c(3, 3, 2)) + + ggplot2::geom_hline(yintercept = 0) + + ggplot2::scale_x_continuous(""Odds ratio"", trans = ""log10"", limits = c(0.25, 10), breaks = breaks, labels = breaks) + + ggplot2::scale_y_continuous(""Standard Error"", limits = c(0, 1.5)) + + ggplot2::facet_grid(.~study) + + ggplot2::theme(panel.grid.minor = ggplot2::element_blank(), + panel.background = ggplot2::element_rect(fill = ""#FAFAFA"", colour = NA), + panel.grid.major = ggplot2::element_blank(), + axis.ticks = ggplot2::element_blank(), + axis.text.y = themeRA, + axis.text.x = theme, + axis.title = theme, + legend.key = ggplot2::element_blank(), + strip.text.x = theme, + strip.background = ggplot2::element_blank(), + legend.position = ""top"", + legend.title = ggplot2::element_blank(), + legend.text = theme, + legend.direction = ""horizontal"") + + fileName <- file.path(outputFolder, ""estimatesCaseControl.png"") + ggplot2::ggsave(fileName, plot, width = 8, height = 3.5, dpi = 400) +} + +plotIrrsCombined <- function(outputFolder) { + sccsSummary <- readRDS(file.path(outputFolder, ""sccsSummaryAp.rds"")) + estimatesAp <- data.frame(logRr = sccsSummary$`logRr(Exposure of interest)`, + seLogRr = sccsSummary$`seLogRr(Exposure of interest)`, + irr = sccsSummary$`rr(Exposure of interest)`, + CI95LB = sccsSummary$`ci95lb(Exposure of interest)`, + CI95UB = sccsSummary$`ci95ub(Exposure of interest)`, + exposureId = sccsSummary$exposureId, + outcomeId = sccsSummary$outcomeId, + caseCount = sccsSummary$caseCount, + eventCount = sccsSummary$eventCount, + type = ""Negative control"", + study = ""Chou"", + stringsAsFactors = FALSE) + estimatesAp$type[sccsSummary$exposureId == 4] <- ""Exposure of interest"" + + sccsSummary <- readRDS(file.path(outputFolder, ""sccsSummaryIbd.rds"")) + estimatesIbd <- data.frame(logRr = sccsSummary$`logRr(Exposure of interest)`, + seLogRr = sccsSummary$`seLogRr(Exposure of interest)`, + irr = sccsSummary$`rr(Exposure of interest)`, + CI95LB = sccsSummary$`ci95lb(Exposure of interest)`, + CI95UB = sccsSummary$`ci95ub(Exposure of interest)`, + exposureId = sccsSummary$exposureId, + outcomeId = sccsSummary$outcomeId, + caseCount = sccsSummary$caseCount, + eventCount = sccsSummary$eventCount, + type = ""Negative control"", + study = ""Crockett"", + stringsAsFactors = FALSE) + estimatesIbd$type[sccsSummary$exposureId == 5] <- ""Exposure of interest"" + estimates <- rbind(estimatesAp, estimatesIbd) + + estimates$x <- exp(estimates$logRr) + estimates$y <- estimates$seLogRr + estimates$study <- factor(estimates$study, levels = c(""Crockett"", ""Chou"")) + + getArea <- function(study, alpha = 0.05) { + idx <- estimates$type == ""Negative control"" & estimates$study == study + null <- EmpiricalCalibration::fitNull(estimates$logRr[idx], estimates$seLogRr[idx]) + x <- exp(seq(log(0.25), log(10), by = 0.01)) + y <- EmpiricalCalibration:::logRrtoSE(log(x), alpha, null[1], null[2]) + seTheoretical <- sapply(x, FUN = function(x) { + abs(log(x))/qnorm(1 - 0.05/2) + }) + return(data.frame(study = study, x = x, y = y, seTheoretical = seTheoretical)) + } + area <- rbind(getArea(""Crockett""), getArea(""Chou"")) + + breaks <- c(0.25, 0.5, 1, 2, 4, 6, 8, 10) + theme <- ggplot2::element_text(colour = ""#000000"", size = 10) + themeRA <- ggplot2::element_text(colour = ""#000000"", size = 10, hjust = 1) + plot <- ggplot2::ggplot(estimates, ggplot2::aes(x = x, y = y), environment = environment()) + + ggplot2::geom_vline(xintercept = breaks, colour = ""#AAAAAA"", lty = 1, size = 0.5) + + ggplot2::geom_vline(xintercept = 1, size = 0.7) + + ggplot2::geom_area(fill = rgb(1, 0.5, 0, alpha = 0.5), color = rgb(1, 0.5, 0), size = 0.5, alpha = 0.5, data = area) + + ggplot2::geom_area(ggplot2::aes(y = seTheoretical), + fill = rgb(0, 0, 0), + colour = rgb(0, 0, 0, alpha = 0.1), + alpha = 0.1, + data = area) + + ggplot2::geom_line(ggplot2::aes(y = seTheoretical), + colour = rgb(0, 0, 0), + linetype = ""dashed"", + size = 1, + alpha = 0.5, + data = area) + + ggplot2::geom_point(ggplot2::aes(shape = type, color = type, fill = type, size = type), alpha = 0.6) + + ggplot2::geom_point(ggplot2::aes(shape = type, color = type, fill = type, size = type), alpha = 0.6, data = estimates[estimates$type != ""Negative control"", ]) + + ggplot2::scale_color_manual(values = c(rgb(0, 0, 0), rgb(0, 0, 0.8))) + + ggplot2::scale_fill_manual(values = c(rgb(1, 1, 0, alpha = 0.8), rgb(0, 0, 0.8, alpha = 0.5))) + + ggplot2::scale_shape_manual(values = c(23, 21)) + + ggplot2::scale_size_manual(values = c(3, 2)) + + ggplot2::geom_hline(yintercept = 0) + + ggplot2::scale_x_continuous(""Incidence rate ratio"", trans = ""log10"", limits = c(0.25, 10), breaks = breaks, labels = breaks) + + ggplot2::scale_y_continuous(""Standard Error"", limits = c(0, 1.5)) + + ggplot2::facet_grid(.~study) + + ggplot2::theme(panel.grid.minor = ggplot2::element_blank(), + panel.background = ggplot2::element_rect(fill = ""#FAFAFA"", colour = NA), + panel.grid.major = ggplot2::element_blank(), + axis.ticks = ggplot2::element_blank(), + axis.text.y = themeRA, + axis.text.x = theme, + axis.title = theme, + legend.key = ggplot2::element_blank(), + strip.text.x = theme, + strip.background = ggplot2::element_blank(), + legend.position = ""top"", + legend.title = ggplot2::element_blank(), + legend.text = theme, + legend.direction = ""horizontal"") + + fileName <- file.path(outputFolder, ""estimatesSccs.png"") + ggplot2::ggsave(fileName, plot, width = 8, height = 3.5, dpi = 400) + write.csv(estimates, file.path(outputFolder, ""AllSccsEstimates.csv""), row.names = FALSE) +} + +createSccsEstimatesAppendix <- function(outputFolder) { + estimates <- read.csv(file.path(outputFolder, ""AllSccsEstimates.csv"")) + estimatesCc <- read.csv(file.path(outputFolder, ""AllEstimates.csv"")) + estimates <- merge(estimates, estimatesCc[, c(""exposureId"", ""exposureName"", ""nestingCohortId"", ""nestingName"", ""outcomeId"", ""outcomeName"", ""type"")], all.x = TRUE) + estimates$p <- EmpiricalCalibration::computeTraditionalP(estimates$logRr, estimates$seLogRr) + estimates <- estimates[, c(""outcomeName"", ""exposureName"", ""nestingName"", ""type"", ""caseCount"", ""eventCount"", ""irr"", ""CI95LB"", ""CI95UB"", ""p"")] + colnames(estimates) <- c(""Outcome"", ""Exposure"", ""Nesting cohort"", ""Type"", ""Cases"", ""Events"", ""Incidence rate ratio"", ""CI95LB"", ""CI95UB"", ""P"") + write.csv(estimates, file.path(outputFolder, ""SupplementaryTableS2.csv""), row.names = FALSE) +} + + +createVisitPlotCombined <- function(outputFolder) { + visitCounts1 <- readRDS(file.path(outputFolder, ""resultsIbd"", ""visitCounts.rds"")) + visitCounts1$study <- ""Crockett"" + visitCounts2 <- readRDS(file.path(outputFolder, ""resultsAp"", ""visitCounts.rds"")) + visitCounts2$study <- ""Chou"" + visitCounts <- rbind(visitCounts1, visitCounts2) + visitCounts$label <- ""Cases"" + visitCounts$label[!visitCounts$isCase] <- ""Controls"" + visitCounts$study <- factor(visitCounts$study, levels = c(""Crockett"", ""Chou"")) + theme <- ggplot2::element_text(colour = ""#000000"", size = 10) + themeRA <- ggplot2::element_text(colour = ""#000000"", size = 10, hjust = 1) + plot <- ggplot2::ggplot(visitCounts, ggplot2::aes(x = day, y = rate, group = label, color = label)) + + ggplot2::geom_vline(xintercept = 0, color = rgb(0, 0, 0), size = 0.5) + + ggplot2::geom_line(alpha = 0.7, size = 1) + + ggplot2::scale_color_manual(values = c(rgb(0.8, 0, 0), rgb(0, 0, 0.8))) + + ggplot2::labs(x = ""Days relative to index date"", y = ""Visits / persons"") + + ggplot2::facet_grid(.~study) + + ggplot2::theme(axis.ticks = ggplot2::element_blank(), + axis.text.y = themeRA, + axis.text.x = theme, + axis.title = theme, + legend.key = ggplot2::element_blank(), + strip.text.x = theme, + strip.background = ggplot2::element_blank(), + legend.position = ""top"", + legend.title = ggplot2::element_blank(), + legend.text = theme, + legend.direction = ""horizontal"") + ggplot2::ggsave(file.path(outputFolder, ""priorVisitRates.jpg""), plot, width = 8, height = 4, dpi = 1000) +} + +createVisitPlotByExposureCombined <- function(outputFolder) { + visitCounts1 <- readRDS(file.path(outputFolder, ""resultsIbd"", ""visitCountsByExposure.rds"")) + visitCounts1$study <- ""Crockett"" + visitCounts2 <- readRDS(file.path(outputFolder, ""resultsAp"", ""visitCountsByExposure.rds"")) + visitCounts2$study <- ""Chou"" + visitCounts <- rbind(visitCounts1, visitCounts2) + visitCounts$exposure <- ""Unexposed"" + visitCounts$exposure[visitCounts$exposed == 1] <- ""Exposed"" + visitCounts$case <- ""Control"" + visitCounts$case[visitCounts$isCase == 1] <- ""Case"" + visitCounts$study <- factor(visitCounts$study, levels = c(""Crockett"", ""Chou"")) + theme <- ggplot2::element_text(colour = ""#000000"", size = 10) + themeRA <- ggplot2::element_text(colour = ""#000000"", size = 10, hjust = 1) + plot <- ggplot2::ggplot(visitCounts, ggplot2::aes(x = day, y = rate, group = exposure, color = exposure)) + + ggplot2::geom_vline(xintercept = 0, color = rgb(0, 0, 0), size = 0.5) + + ggplot2::geom_line(alpha = 0.7, size = 1) + + ggplot2::scale_color_manual(values = c(rgb(0.8, 0, 0), rgb(0, 0, 0.8))) + + ggplot2::labs(x = ""Days relative to index date"", y = ""Visits / persons"") + + ggplot2::facet_grid(study~case) + + ggplot2::theme(axis.ticks = ggplot2::element_blank(), + axis.text.y = themeRA, + axis.text.x = theme, + axis.title = theme, + legend.key = ggplot2::element_blank(), + strip.text.x = theme, + strip.background = ggplot2::element_blank(), + legend.position = ""top"", + legend.title = ggplot2::element_blank(), + legend.text = theme, + legend.direction = ""horizontal"") + ggplot2::ggsave(file.path(outputFolder, ""priorVisitRatesByExposure.jpg""), plot, width = 8, height = 4, dpi = 1000) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","EvaluatingCaseControl/R/Sccs.R",".R","14432","216","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of EvaluatingCaseControl +# +# 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. + +runSccs <- function(connectionDetails, + cdmDatabaseSchema, + oracleTempSchema, + cohortDatabaseSchema, + cohortTable, + outputFolder, + maxCores) { + # Chou replication -------------------------------------------------------- + sccsApFolder <- file.path(outputFolder, ""sccsAp"") + if (!file.exists(sccsApFolder)) + dir.create(sccsApFolder) + + analysisListFile <- system.file(""settings"", ""sccsAnalysisListAp.json"", package = ""EvaluatingCaseControl"") + analysisList <- SelfControlledCaseSeries::loadSccsAnalysisList(analysisListFile) + eoList <- createEos(outputFolder = outputFolder, + exposureId = 4, + outcomeId = 2) + sccsResult <- SelfControlledCaseSeries::runSccsAnalyses(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + exposureDatabaseSchema = cohortDatabaseSchema, + exposureTable = cohortTable, + outcomeDatabaseSchema = cohortDatabaseSchema, + outcomeTable = cohortTable, + sccsAnalysisList = analysisList, + exposureOutcomeList = eoList, + outputFolder = sccsApFolder, + getDbSccsDataThreads = 3, + createSccsEraDataThreads = min(3, maxCores), + fitSccsModelThreads = min(5, maxCores), + cvThreads = min(10, maxCores), + compressSccsEraDataFiles = TRUE) + sccsSummary <- SelfControlledCaseSeries::summarizeSccsAnalyses(sccsResult, sccsApFolder) + sccsSummaryFile <- file.path(outputFolder, ""sccsSummaryAp.rds"") + saveRDS(sccsSummary, sccsSummaryFile) + + sccsSummary <- readRDS(file.path(outputFolder, ""sccsSummaryAp.rds"")) + ncs <- sccsSummary[sccsSummary$exposureId != 4, ] + pcs <- sccsSummary[sccsSummary$exposureId == 4, ] + EmpiricalCalibration::plotCalibrationEffect(logRrNegatives = ncs$`logRr(Exposure of interest)`, + seLogRrNegatives = ncs$`seLogRr(Exposure of interest)`, + logRrPositives = pcs$`logRr(Exposure of interest)`, + seLogRrPositives = pcs$`seLogRr(Exposure of interest)`, + showCis = TRUE) + + # Crockett replication -------------------------------------------------------- + sccsIbdFolder <- file.path(outputFolder, ""sccsIbd"") + if (!file.exists(sccsIbdFolder)) + dir.create(sccsIbdFolder) + + analysisListFile <- system.file(""settings"", ""sccsAnalysisListIbd.json"", package = ""EvaluatingCaseControl"") + analysisList <- SelfControlledCaseSeries::loadSccsAnalysisList(analysisListFile) + eoList <- createEos(outputFolder = outputFolder, + exposureId = 5, + outcomeId = 3) + sccsResult <- SelfControlledCaseSeries::runSccsAnalyses(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + exposureDatabaseSchema = cohortDatabaseSchema, + exposureTable = cohortTable, + outcomeDatabaseSchema = cohortDatabaseSchema, + outcomeTable = cohortTable, + sccsAnalysisList = analysisList, + exposureOutcomeList = eoList, + outputFolder = sccsIbdFolder, + getDbSccsDataThreads = 3, + createSccsEraDataThreads = min(3, maxCores), + fitSccsModelThreads = min(5, maxCores), + cvThreads = min(10, maxCores), + compressSccsEraDataFiles = TRUE) + sccsSummary <- SelfControlledCaseSeries::summarizeSccsAnalyses(sccsResult, sccsIbdFolder) + sccsSummaryFile <- file.path(outputFolder, ""sccsSummaryIbd.rds"") + saveRDS(sccsSummary, sccsSummaryFile) + + sccsSummary <- readRDS(file.path(outputFolder, ""sccsSummaryIbd.rds"")) + ncs <- sccsSummary[sccsSummary$exposureId != 5, ] + pcs <- sccsSummary[sccsSummary$exposureId == 5, ] + EmpiricalCalibration::plotCalibrationEffect(logRrNegatives = ncs$`logRr(Exposure of interest)`, + seLogRrNegatives = ncs$`seLogRr(Exposure of interest)`, + logRrPositives = pcs$`logRr(Exposure of interest)`, + seLogRrPositives = pcs$`seLogRr(Exposure of interest)`, + showCis = TRUE) +} + +#' Create the analyses details +#' +#' @details +#' This function creates files specifying the analyses that will be performed. +#' +#' @param workFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' +#' @export +createSccsAnalysesDetails <- function(workFolder) { + + # Chou replication -------------------------------------------------------- + getDbSccsDataArgsAp <- SelfControlledCaseSeries::createGetDbSccsDataArgs(useCustomCovariates = FALSE, + deleteCovariatesSmallCount = 100, + studyStartDate = """", + studyEndDate = """", + exposureIds = c(), + maxCasesPerOutcome = 250000) + + covarExposureOfIntAp <- SelfControlledCaseSeries::createCovariateSettings(label = ""Exposure of interest"", + includeCovariateIds = ""exposureId"", + start = 1, + end = 30, + addExposedDaysToEnd = TRUE) + + covarPreExposureAp = SelfControlledCaseSeries::createCovariateSettings(label = ""Pre-exposure"", + includeCovariateIds = ""exposureId"", + start = -30, + end = -1) + + ageSettingsAp <- SelfControlledCaseSeries::createAgeSettings(includeAge = TRUE, ageKnots = 5, computeConfidenceIntervals = FALSE) + + seasonalitySettingsAp <- SelfControlledCaseSeries::createSeasonalitySettings(includeSeasonality = TRUE, seasonKnots = 5, computeConfidenceIntervals = FALSE) + + createSccsEraDataArgsAp <- SelfControlledCaseSeries::createCreateSccsEraDataArgs(naivePeriod = 365, + firstOutcomeOnly = FALSE, + covariateSettings = list(covarExposureOfIntAp, + covarPreExposureAp), + ageSettings = ageSettingsAp, + seasonalitySettings = seasonalitySettingsAp, + minCasesForAgeSeason = 10000) + + fitSccsModelArgsAp <- SelfControlledCaseSeries::createFitSccsModelArgs() + + sccsAnalysisAp <- SelfControlledCaseSeries::createSccsAnalysis(analysisId = 1, + description = ""Using pre-exposure window, age, and season"", + getDbSccsDataArgs = getDbSccsDataArgsAp, + createSccsEraDataArgs = createSccsEraDataArgsAp, + fitSccsModelArgs = fitSccsModelArgsAp) + + sccsAnalysisListAp <- list(sccsAnalysisAp) + SelfControlledCaseSeries::saveSccsAnalysisList(sccsAnalysisListAp, file.path(workFolder, ""sccsAnalysisListAp.json"")) + + # Crockett replication ---------------------------------------------------- + getDbSccsDataArgsIbd <- SelfControlledCaseSeries::createGetDbSccsDataArgs(useCustomCovariates = FALSE, + deleteCovariatesSmallCount = 100, + studyStartDate = """", + studyEndDate = """", + exposureIds = c(), + maxCasesPerOutcome = 250000) + + covarExposureOfIntIbd <- SelfControlledCaseSeries::createCovariateSettings(label = ""Exposure of interest"", + includeCovariateIds = ""exposureId"", + start = 1, + end = 365, + addExposedDaysToEnd = TRUE) + + covarPreExposureIbd = SelfControlledCaseSeries::createCovariateSettings(label = ""Pre-exposure"", + includeCovariateIds = ""exposureId"", + start = -30, + end = -1) + + ageSettingsIbd <- SelfControlledCaseSeries::createAgeSettings(includeAge = TRUE, ageKnots = 5, computeConfidenceIntervals = FALSE) + + seasonalitySettingsIbd <- SelfControlledCaseSeries::createSeasonalitySettings(includeSeasonality = TRUE, seasonKnots = 5, computeConfidenceIntervals = FALSE) + + createSccsEraDataArgsIbd <- SelfControlledCaseSeries::createCreateSccsEraDataArgs(naivePeriod = 365, + firstOutcomeOnly = FALSE, + covariateSettings = list(covarExposureOfIntIbd, + covarPreExposureIbd), + ageSettings = ageSettingsIbd, + seasonalitySettings = seasonalitySettingsIbd, + minCasesForAgeSeason = 10000) + + fitSccsModelArgsIbd <- SelfControlledCaseSeries::createFitSccsModelArgs() + + sccsAnalysisIbd <- SelfControlledCaseSeries::createSccsAnalysis(analysisId = 1, + description = ""Using pre-exposure window, age, and season"", + getDbSccsDataArgs = getDbSccsDataArgsIbd, + createSccsEraDataArgs = createSccsEraDataArgsIbd, + fitSccsModelArgs = fitSccsModelArgsIbd) + + sccsAnalysisListIbd <- list(sccsAnalysisIbd) + SelfControlledCaseSeries::saveSccsAnalysisList(sccsAnalysisListIbd, file.path(workFolder, ""sccsAnalysisListIbd.json"")) +} + +createEos <- function(outputFolder, exposureId, outcomeId) { + allControlsFile = file.path(outputFolder, ""AllControlsAp.csv"") + if (file.exists(allControlsFile)) { + allControls <- read.csv(allControlsFile) + } else { + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""EvaluatingCaseControl"") + allControls <- read.csv(pathToCsv) + allControls <- allControls[allControls$outcomeId == outcomeId, ] + } + eonList <- list(SelfControlledCaseSeries::createExposureOutcome(exposureId = exposureId, + outcomeId = outcomeId)) + for (i in 1:nrow(allControls)) { + eon <- SelfControlledCaseSeries::createExposureOutcome(exposureId = allControls$targetId[i], + outcomeId = allControls$outcomeId[i]) + + eonList[[length(eonList) + 1]] <- eon + } + return(eonList) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","EvaluatingCaseControl/R/SampleSize.R",".R","1389","36","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of EvaluatingCaseControl +# +# 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. + +computeSampleSize <- function(outputFolder) { + ParallelLogger::logInfo(""Computing sample size and power"") + ccdFile = file.path(outputFolder, ""ccIbd"", ""ccd_cd1_cc1_o3_ed1_e5_ccd1.rds"") + ccd <- readRDS(ccdFile) + row1 <- CaseControl::computeMdrr(ccd) + row1$Study <- ""Crockett et al."" + row1$Outcome <- ""Ulcerative colitis"" + row1$exposure <- ""Isotretinoin"" + + ccdFile = file.path(outputFolder, ""ccAp"", ""ccd_cd1_n1_cc1_o2_ed1_e4_ccd1.rds"") + ccd <- readRDS(ccdFile) + row2 <- CaseControl::computeMdrr(ccd) + row2$Study <- ""Chou et al."" + row2$Outcome <- ""Acute pancreatitis"" + row2$exposure <- ""DPP-4 inhibitors"" + + table <- rbind(row1, row2) + write.csv(table, file.path(outputFolder, ""SampleSize.csv""), row.names = FALSE) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","EvaluatingCaseControl/R/EvaluatingCaseControl.R",".R","881","26","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of EvaluatingCaseControl +# +# 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. + +#' EvaluatingCaseControl +#' +#' @docType package +#' @name EvaluatingCaseControl +#' @importFrom grDevices rgb +#' @importFrom stats aggregate qnorm +#' @importFrom utils read.csv write.csv +#' @import DatabaseConnector +NULL +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","EvaluatingCaseControl/R/CaseControl.R",".R","16193","278","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of EvaluatingCaseControl +# +# 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. + +runCaseControlDesigns <- function(connectionDetails, + cdmDatabaseSchema, + oracleTempSchema, + cohortDatabaseSchema, + cohortTable, + outputFolder, + maxCores) { + ParallelLogger::logInfo(""Running Chou replication"") + ccApFolder <- file.path(outputFolder, ""ccAp"") + if (!file.exists(ccApFolder)) + dir.create(ccApFolder) + + analysisListFile <- system.file(""settings"", ""ccAnalysisListAp.json"", package = ""EvaluatingCaseControl"") + analysisList <- CaseControl::loadCcAnalysisList(analysisListFile) + eonList <- createEons(outputFolder = outputFolder, + exposureId = 4, + outcomeId = 2, + nestingCohortId = 1) + ccResult <- CaseControl::runCcAnalyses(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + exposureDatabaseSchema = cohortDatabaseSchema, + exposureTable = cohortTable, + outcomeDatabaseSchema = cohortDatabaseSchema, + outcomeTable = cohortTable, + nestingCohortDatabaseSchema = cohortDatabaseSchema, + nestingCohortTable = cohortTable, + ccAnalysisList = analysisList, + exposureOutcomeNestingCohortList = eonList, + outputFolder = ccApFolder, + getDbCaseDataThreads = 1, + selectControlsThreads = min(3, maxCores), + getDbExposureDataThreads = 1, + createCaseControlDataThreads = min(5, maxCores), + fitCaseControlModelThreads = min(5, maxCores), + cvThreads = min(2,maxCores), + prefetchExposureData = FALSE) + ccSummary <- CaseControl::summarizeCcAnalyses(ccResult) + ccSummaryFile <- file.path(outputFolder, ""ccSummaryAp.rds"") + saveRDS(ccSummary, ccSummaryFile) + + ParallelLogger::logInfo(""Running Crockett replication"") + ccIbdFolder <- file.path(outputFolder, ""ccIbd"") + if (!file.exists(ccIbdFolder)) + dir.create(ccIbdFolder) + + analysisListFile <- system.file(""settings"", ""ccAnalysisListIbd.json"", package = ""EvaluatingCaseControl"") + analysisList <- CaseControl::loadCcAnalysisList(analysisListFile) + eonList <- createEons(allControlsFile = file.path(outputFolder, ""AllControlsIbd.csv""), + exposureId = 5, + outcomeId = 3) + ccResult <- CaseControl::runCcAnalyses(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + exposureDatabaseSchema = cohortDatabaseSchema, + exposureTable = cohortTable, + outcomeDatabaseSchema = cohortDatabaseSchema, + outcomeTable = cohortTable, + nestingCohortDatabaseSchema = cohortDatabaseSchema, + nestingCohortTable = cohortTable, + ccAnalysisList = analysisList, + exposureOutcomeNestingCohortList = eonList, + outputFolder = ccIbdFolder, + getDbCaseDataThreads = 1, + selectControlsThreads = min(3, maxCores), + getDbExposureDataThreads = 1, + createCaseControlDataThreads = min(5, maxCores), + fitCaseControlModelThreads = min(5, maxCores), + prefetchExposureData = TRUE) + + # Crockett used option not supported by package: controls have index date 1 year from observation start + # Achieve this by resetting index date and rerunning analysis. + ParallelLogger::logInfo(""Resetting conrol index date"") + #ccResult <- readRDS(file.path(ccIbdFolder, ""outcomeModelReference.rds"")) + caseData <- CaseControl::loadCaseData(ccResult$caseDataFolder[1]) + caseControlsFiles <- ccResult$caseControlsFile + for (caseControlsFile in unique(caseControlsFiles)) { + caseControls <- readRDS(caseControlsFile) + cases <- caseControls[caseControls$isCase, ] + controls <- caseControls[!caseControls$isCase, ] + controlsData <- caseData$nestingCohorts[ffbase::`%in%`(caseData$nestingCohorts$personId, controls$personId), c(""personId"", ""startDate"", ""endDate"")] + controls <- merge(controls, controlsData, all.x = TRUE) + controls <- controls[controls$indexDate >= controls$startDate & controls$indexDate <= controls$endDate, ] + controls$indexDate <- controls$startDate + 365 + controls$startDate <- NULL + controls$endDate <- NULL + caseControls <- rbind(cases, controls) + saveRDS(caseControls, caseControlsFile) + } + unlink(unique(ccResult$exposureDataFile), recursive = TRUE) + unlink(unique(ccResult$caseControlDataFile)) + unlink(unique(ccResult$modelFile)) + + ccResult <- CaseControl::runCcAnalyses(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + exposureDatabaseSchema = cohortDatabaseSchema, + exposureTable = cohortTable, + outcomeDatabaseSchema = cohortDatabaseSchema, + outcomeTable = cohortTable, + nestingCohortDatabaseSchema = cohortDatabaseSchema, + nestingCohortTable = cohortTable, + ccAnalysisList = analysisList, + exposureOutcomeNestingCohortList = eonList, + outputFolder = ccIbdFolder, + getDbCaseDataThreads = 1, + selectControlsThreads = min(3, maxCores), + getDbExposureDataThreads = 1, + createCaseControlDataThreads = min(5, maxCores), + fitCaseControlModelThreads = min(5, maxCores), + prefetchExposureData = TRUE) + ccSummary <- CaseControl::summarizeCcAnalyses(ccResult) + ccSummaryFile <- file.path(outputFolder, ""ccSummaryIbd.rds"") + saveRDS(ccSummary, ccSummaryFile) +} + +#' Create the analyses details +#' +#' @details +#' This function creates files specifying the analyses that will be performed. +#' +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' +#' @export +createCaseControlAnalysesDetails <- function(outputFolder) { + + # Chou replication -------------------------------------------------------- + cdAp <- CaseControl::createGetDbCaseDataArgs(useNestingCohort = TRUE, + useObservationEndAsNestingEndDate = TRUE, + getVisits = FALSE) + + ccAp <- CaseControl::createSelectControlsArgs(firstOutcomeOnly = TRUE, + washoutPeriod = 365, + controlsPerCase = 4, + matchOnAge = TRUE, + ageCaliper = 1, + matchOnGender = TRUE, + matchOnProvider = FALSE, + matchOnVisitDate = FALSE, + matchOnTimeInCohort = TRUE, + daysInCohortCaliper = 365, + removedUnmatchedCases = TRUE) + + pathToCsv <- system.file(""settings"", ""Icd9Covariates.csv"", package = ""EvaluatingCaseControl"") + icd9CovariateDefs <- read.csv(pathToCsv) + icd9CovariateSettings <- createIcd9CovariateSettings(icd9CovariateDefs) + + pathToCsv <- system.file(""settings"", ""AtcCovariates.csv"", package = ""EvaluatingCaseControl"") + atcCovariateDefs <- read.csv(pathToCsv) + atcCovariateSettings <- createAtcCovariateSettings(atcCovariateDefs) + + defaultCovariateSettings = FeatureExtraction::createCovariateSettings(useDcsi = TRUE, + endDays = -1) + + edAp <- CaseControl::createGetDbExposureDataArgs(covariateSettings = list(icd9CovariateSettings, + atcCovariateSettings, + defaultCovariateSettings)) + + ccdAp <- CaseControl::createCreateCaseControlDataArgs(firstExposureOnly = FALSE, + riskWindowStart = -30, + riskWindowEnd = 0) + + mAp <- CaseControl::createFitCaseControlModelArgs(useCovariates = TRUE, + prior = Cyclops::createPrior(""normal"", 10000)) + + ccAnalysisAp <- CaseControl::createCcAnalysis(analysisId = 1, + description = ""Chou replication for AP"", + getDbCaseDataArgs = cdAp, + selectControlsArgs = ccAp, + getDbExposureDataArgs = edAp, + createCaseControlDataArgs = ccdAp, + fitCaseControlModelArgs = mAp) + + ccAnalysisListAp <- list(ccAnalysisAp) + CaseControl::saveCcAnalysisList(ccAnalysisListAp, file.path(outputFolder, ""ccAnalysisListAp.json"")) + + # pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""EvaluatingCaseControl"") + # negativeControls <- read.csv(pathToCsv) + # negativeControls <- negativeControls[negativeControls$outcomeName == ""Acute pancreatitis"", ] + # eon <- CaseControl::createExposureOutcomeNestingCohort(exposureId = 4, outcomeId = 2, nestingCohortId = 1) + # eonsAp <- list(eon) + # for (i in 1:nrow(negativeControls)) { + # eon <- CaseControl::createExposureOutcomeNestingCohort(exposureId = negativeControls$targetId[i], + # outcomeId = 2, + # nestingCohortId = negativeControls$nestingId[i]) + # eonsAp[[length(eonsAp) + 1]] <- eon + # } + # CaseControl::saveExposureOutcomeNestingCohortList(eonsAp, file.path(outputFolder, ""ccExposureOutcomeNestingAp.json"")) + + + # Crockett replication ---------------------------------------------------- + + cdIbd <- CaseControl::createGetDbCaseDataArgs(getVisits = FALSE) + + ccIbd <- CaseControl::createSelectControlsArgs(firstOutcomeOnly = TRUE, + washoutPeriod = 365, + controlsPerCase = 3, + matchOnAge = TRUE, + ageCaliper = 2, + matchOnGender = TRUE, + matchOnProvider = FALSE, + matchOnVisitDate = FALSE, + matchOnTimeInCohort = TRUE, + daysInCohortCaliper = 90, + removedUnmatchedCases = TRUE) + + edIbd <- CaseControl::createGetDbExposureDataArgs() + + ccdIbd <- CaseControl::createCreateCaseControlDataArgs(firstExposureOnly = FALSE, + riskWindowStart = -365, + riskWindowEnd = 0) + + mIbd <- CaseControl::createFitCaseControlModelArgs() + + ccAnalysisIbd <- CaseControl::createCcAnalysis(analysisId = 2, + description = ""Crockett replication for IBD"", + getDbCaseDataArgs = cdIbd, + selectControlsArgs = ccIbd, + getDbExposureDataArgs = edIbd, + createCaseControlDataArgs = ccdIbd, + fitCaseControlModelArgs = mIbd) + + ccAnalysisListIbd <- list(ccAnalysisIbd) + CaseControl::saveCcAnalysisList(ccAnalysisListIbd, file.path(outputFolder, ""ccAnalysisListIbd.json"")) + + + # pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""EvaluatingCaseControl"") + # negativeControls <- read.csv(pathToCsv) + # negativeControls <- negativeControls[negativeControls$outcomeName == ""Ulcerative colitis"", ] + # eon <- CaseControl::createExposureOutcomeNestingCohort(exposureId = 5, outcomeId = 3) + # eonsIbd <- list(eon) + # for (i in 1:nrow(negativeControls)) { + # eon <- CaseControl::createExposureOutcomeNestingCohort(exposureId = negativeControls$targetId[i], + # outcomeId = 3) + # eonsIbd[[length(eonsIbd) + 1]] <- eon + # } + # CaseControl::saveExposureOutcomeNestingCohortList(eonsIbd, file.path(outputFolder, ""ccExposureOutcomeNestingIbd.json"")) +} + +createEons <- function(outputFolder, exposureId, outcomeId, nestingCohortId = NULL) { + allControlsFile = file.path(outputFolder, ""AllControlsAp.csv"") + if (file.exists(allControlsFile)) { + allControls <- read.csv(allControlsFile) + } else { + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""EvaluatingCaseControl"") + allControls <- read.csv(pathToCsv) + allControls <- allControls[allControls$outcomeId == outcomeId, ] + } + eonList <- list(CaseControl::createExposureOutcomeNestingCohort(exposureId = exposureId, + outcomeId = outcomeId, + nestingCohortId = nestingCohortId)) + for (i in 1:nrow(allControls)) { + eon <- CaseControl::createExposureOutcomeNestingCohort(exposureId = allControls$targetId[i], + outcomeId = allControls$outcomeId[i], + nestingCohortId = allControls$nestingId[i]) + + eonList[[length(eonList) + 1]] <- eon + } + return(eonList) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","EvaluatingCaseControl/extras/PackageMaintenance.R",".R","2523","57","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of EvaluatingCaseControl +# +# 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. + +# Format and check code ---- +OhdsiRTools::formatRFolder() +OhdsiRTools::checkUsagePackage(""EvaluatingCaseControl"") +OhdsiRTools::updateCopyrightYearFolder() + +# Create manual and vignette ---- +shell(""EvaluatingCaseControl.pdf"") +shell(""R CMD Rd2pdf ./ --output=extras/EvaluatingCaseControl.pdf"") + +# Insert cohort definitions into package ---- +OhdsiRTools::insertCohortDefinitionSetInPackage(fileName = ""CohortsToCreate.csv"", + baseUrl = Sys.getenv(""baseUrl""), + insertTableSql = TRUE, + insertCohortCreationR = TRUE, + generateStats = FALSE, + packageName = ""EvaluatingCaseControl"") + +# Create analysis details ---- +source(""R/CaseControl.R"") +createCaseControlAnalysesDetails(""inst/settings/"") +source(""R/CohortMethod.R"") +createCohortMethodAnalysesDetails(""inst/settings/"") +source(""R/Sccs.R"") +createSccsAnalysesDetails(""inst/settings/"") + +# Store environment in which the study was executed ---- +OhdsiRTools::insertEnvironmentSnapshotInPackage(""EvaluatingCaseControl"") + + + +# Get CohortMethod negative controls from MethodEvaluation package +# x <- readRDS(system.file(""ohdsiNegativeControls.rds"", package = ""MethodEvaluation"")) +# x <- x[x$outcomeName %in% c(""Inflammatory Bowel Disease"", ""Acute pancreatitis""), ] +# x$outcomeId[x$outcomeName == ""Inflammatory Bowel Disease""] <- 3 +# x$outcomeId[x$outcomeName == ""Acute pancreatitis""] <- 2 +# pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""EvaluatingCaseControl"") +# allControls <- read.csv(pathToCsv) +# min(x$targetId %in% allControls$targetId) +# min(x$comparatorId %in% allControls$targetId) +# write.csv(x, ""inst/settings/NegativeControlsForCm.csv"", row.names = FALSE) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","EvaluatingCaseControl/extras/PaperExecutionCode.R",".R","1979","54","# @file PaperExecutionCode.R +# +# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of EvaluatingCaseControl +# +# 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. + +library(EvaluatingCaseControl) +options(fftempdir = ""s:/fftemp"") + +pw <- NULL +dbms <- ""pdw"" +user <- NULL +server <- Sys.getenv(""PDW_SERVER"") +port <- Sys.getenv(""PDW_PORT"") +maxCores <- 30 + +connectionDetails <- DatabaseConnector::createConnectionDetails(dbms = dbms, + server = server, + user = user, + password = pw, + port = port) + + +# CCAE settings -------------------------------------------------- +cdmDatabaseSchema <- ""cdm_truven_ccae_v697.dbo"" +oracleTempSchema <- NULL +cohortDatabaseSchema <- ""scratch.dbo"" +cohortTable <- ""mschuemie_case_control_ap_ccae"" +outputFolder <- ""s:/EvaluatingCaseControl_ccae"" + +execute(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + outputFolder = outputFolder, + createCohorts = TRUE, + synthesizePositiveControls = TRUE, + runAnalyses = TRUE, + createFiguresAndTables = TRUE, + maxCores = maxCores) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","DrugsInPeds/R/FiguresAndTables.R",".R","20681","380","# Copyright 2016 Observational Health Data Sciences and Informatics +# +# This file is part of DrugsInPeds +# +# 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. + +createTable1 <- function() { + denominator <- read.csv(""DenominatorByAgeGroup.csv"", stringsAsFactors = FALSE) + numerator <- read.csv(""NumeratorByAgeGroup.csv"", stringsAsFactors = FALSE) + numeratorInpatient <- numerator[numerator$inpatient == 1,] + if (nrow(numeratorInpatient) == 0){ + numeratorInpatient <- data.frame(conceptId = rep(0, nrow(numerator)), + conceptName = rep(""drug"", nrow(numerator)), + prescriptionCount = rep(0, nrow(numerator)), + personCount = rep(0, nrow(numerator)), + ageGroup = numerator$ageGroup) + } + names(numeratorInpatient)[names(numeratorInpatient) == ""prescriptionCount""] <- ""PrescriptionsInpatient"" + numeratorNotInpatient <- numerator[numerator$inpatient == 0,] + if (nrow(numeratorNotInpatient) == 0){ + numeratorNotInpatient <- data.frame(conceptId = rep(0, nrow(numerator)), + conceptName = rep(""drug"", nrow(numerator)), + prescriptionCount = rep(0, nrow(numerator)), + personCount = rep(0, nrow(numerator)), + ageGroup = numerator$ageGroup) + } + names(numeratorNotInpatient)[names(numeratorNotInpatient) == ""prescriptionCount""] <- ""PrescriptionsNotInpatient"" + data <- merge(denominator, numeratorInpatient[,c(""ageGroup"",""PrescriptionsInpatient"")]) + data <- merge(data, numeratorNotInpatient[,c(""ageGroup"",""PrescriptionsNotInpatient"")]) + data <- data[order(data$ageGroup),] + table1 <- data.frame(Category = data$ageGroup, + NoOfChildren = data$persons, + NoOrPersonYears = round(data$days / 365.25), + PrescriptionsInpatient = data$PrescriptionsInpatient, + PrescriptionsNotInpatient = data$PrescriptionsNotInpatient, + stringsAsFactors = FALSE) + + + denominator <- read.csv(""DenominatorByGender.csv"", stringsAsFactors = FALSE) + numerator <- read.csv(""NumeratorByGender.csv"", stringsAsFactors = FALSE) + numeratorInpatient <- numerator[numerator$inpatient == 1,] + if (nrow(numeratorInpatient) == 0){ + numeratorInpatient <- data.frame(conceptId = rep(0, nrow(numerator)), + conceptName = rep(""drug"", nrow(numerator)), + prescriptionCount = rep(0, nrow(numerator)), + personCount = rep(0, nrow(numerator)), + genderConceptId = numerator$genderConceptId) + } + names(numeratorInpatient)[names(numeratorInpatient) == ""prescriptionCount""] <- ""PrescriptionsInpatient"" + numeratorNotInpatient <- numerator[numerator$inpatient == 0,] + if (nrow(numeratorNotInpatient) == 0){ + numeratorNotInpatient <- data.frame(conceptId = rep(0, nrow(numerator)), + conceptName = rep(""drug"", nrow(numerator)), + prescriptionCount = rep(0, nrow(numerator)), + personCount = rep(0, nrow(numerator)), + genderConceptId = numerator$genderConceptId) + } + names(numeratorNotInpatient)[names(numeratorNotInpatient) == ""prescriptionCount""] <- ""PrescriptionsNotInpatient"" + data <- merge(denominator, numeratorInpatient[,c(""genderConceptId"",""PrescriptionsInpatient"")]) + data <- merge(data, numeratorNotInpatient[,c(""genderConceptId"",""PrescriptionsNotInpatient"")]) + data$gender <- ""Male"" + data$gender[data$genderConceptId == 8532] <- ""Female"" + data <- data[order(data$gender),] + table1 <- rbind(table1, data.frame(Category = data$gender, + NoOfChildren = data$persons, + NoOrPersonYears = round(data$days / 365.25), + PrescriptionsInpatient = data$PrescriptionsInpatient, + PrescriptionsNotInpatient = data$PrescriptionsNotInpatient, + stringsAsFactors = FALSE)) + + denominator <- read.csv(""DenominatorByYear.csv"", stringsAsFactors = FALSE) + numerator <- read.csv(""NumeratorByYear.csv"", stringsAsFactors = FALSE) + numeratorInpatient <- numerator[numerator$inpatient == 1,] + if (nrow(numeratorInpatient) == 0){ + numeratorInpatient <- data.frame(conceptId = rep(0, nrow(numerator)), + conceptName = rep(""drug"", nrow(numerator)), + prescriptionCount = rep(0, nrow(numerator)), + personCount = rep(0, nrow(numerator)), + calendarYear = numerator$calendarYear) + } + names(numeratorInpatient)[names(numeratorInpatient) == ""prescriptionCount""] <- ""PrescriptionsInpatient"" + numeratorNotInpatient <- numerator[numerator$inpatient == 0,] + if (nrow(numeratorNotInpatient) == 0){ + numeratorNotInpatient <- data.frame(conceptId = rep(0, nrow(numerator)), + conceptName = rep(""drug"", nrow(numerator)), + prescriptionCount = rep(0, nrow(numerator)), + personCount = rep(0, nrow(numerator)), + calendarYear = numerator$calendarYear) + } + names(numeratorNotInpatient)[names(numeratorNotInpatient) == ""prescriptionCount""] <- ""PrescriptionsNotInpatient"" + data <- merge(denominator, numeratorInpatient[,c(""calendarYear"",""PrescriptionsInpatient"")]) + data <- merge(data, numeratorNotInpatient[,c(""calendarYear"",""PrescriptionsNotInpatient"")]) + data <- data[order(data$calendarYear),] + table1 <- rbind(table1, data.frame(Category = data$calendarYear, + NoOfChildren = data$persons, + NoOrPersonYears = round(data$days / 365.25), + PrescriptionsInpatient = data$PrescriptionsInpatient, + PrescriptionsNotInpatient = data$PrescriptionsNotInpatient, + stringsAsFactors = FALSE)) + + + denominator <- read.csv(""Denominator.csv"", stringsAsFactors = FALSE) + numerator <- read.csv(""Numerator.csv"", stringsAsFactors = FALSE) + data <- denominator + if (any(numerator$inpatient == 1)) { + data$PrescriptionsInpatient <- numerator$prescriptionCount[numerator$inpatient == 1] + } else { + data$PrescriptionsInpatient <- 0 + } + if (any(numerator$inpatient == 0)) { + data$PrescriptionsNotInpatient <- numerator$prescriptionCount[numerator$inpatient == 0] + } else { + data$PrescriptionsNotInpatient <- 0 + } + table1 <- rbind(table1, data.frame(Category = ""Total"", + NoOfChildren = data$persons, + NoOrPersonYears = round(data$days / 365.25), + PrescriptionsInpatient = data$PrescriptionsInpatient, + PrescriptionsNotInpatient = data$PrescriptionsNotInpatient, + stringsAsFactors = FALSE)) + write.csv(table1, ""Table1.csv"", row.names = FALSE) +} + +createTable2 <- function(conn, cdmDatabaseSchema, denominatorType) { + denominator <- read.csv(""Denominator.csv"", stringsAsFactors = FALSE) + numerator <- read.csv(""NumeratorByClass.csv"", stringsAsFactors = FALSE) + numeratorInpatient <- numerator[numerator$inpatient == 1,] + if (nrow(numeratorInpatient) != 0) { + data <- numeratorInpatient + data <- data[order(data$conceptName),] + if (denominatorType == ""persons"") { + table2a <- data.frame(Class = data$conceptName, + UserPrevalence = round(data$personCount/(denominator$persons / 1000), digits = 2), + PrescriptionPrevalence = round(data$prescriptionCount/(denominator$persons / 1000), digits = 2)) + } else { + table2a <- data.frame(Class = data$conceptName, + UserPrevalence = round(data$personCount/(denominator$days / 365.25 / 1000), digits = 2), + PrescriptionPrevalence = round(data$prescriptionCount/(denominator$days / 365.25 / 1000), digits = 2)) + } + write.csv(table2a, ""Table2a.csv"", row.names = FALSE) + } + numeratorNotInpatient <- numerator[numerator$inpatient == 0,] + if (nrow(numeratorNotInpatient) != 0) { + data <- numeratorNotInpatient + data <- data[order(data$conceptName),] + if (denominatorType == ""persons"") { + table2b <- data.frame(Class = data$conceptName, + UserPrevalence = round(data$personCount/(denominator$persons / 1000), digits = 2), + PrescriptionPrevalence = round(data$prescriptionCount/(denominator$days / 365.25 / 1000), digits = 2)) + } else { + table2b <- data.frame(Class = data$conceptName, + UserPrevalence = round(data$personCount/(denominator$persons / 1000), digits = 2), + PrescriptionPrevalence = round(data$prescriptionCount/(denominator$days / 365.25 / 1000), digits = 2)) + } + + write.csv(table2b, ""Table2b.csv"", row.names = FALSE) + } +} + +createTable3 <- function(denominatorType, drugsPerClass = 5) { + denominator <- read.csv(""Denominator.csv"", stringsAsFactors = FALSE) + numerator <- read.csv(""NumeratorByIngredient.csv"", stringsAsFactors = FALSE) + + pathToCsv <- system.file(""csv"", + ""CustomClassification.csv"", + package = ""DrugsInPeds"") + classes <- read.csv(pathToCsv, as.is = TRUE) + names(classes) <- SqlRender::snakeCaseToCamelCase(names(classes)) + classes <- classes[, c(""conceptId"",""classId"")] + numerator <- merge(numerator, classes) + + temp <- list() + for (inpatient in c(0,1)) { + for (classId in unique(classes$classId)){ + subset <- numerator[numerator$classId == classId & numerator$inpatient == inpatient,] + subset <- subset[order(-subset$personCount), ] + subset <- subset[1:min(drugsPerClass,nrow(subset)), ] + temp[[length(temp)+1]] <- subset + } + } + numerator <- do.call(rbind, temp) + numerator <- numerator[order(numerator$classId, -numerator$personCount),] + + data <- numerator[numerator$inpatient == 1,] + + if (denominatorType == ""persons"") { + table3a <- data.frame(Class = data$classId, + Drug = data$conceptName, + UserPrevalence = round(data$personCount/(denominator$persons / 1000), digits = 2)) + } else { + table3a <- data.frame(Class = data$classId, + Drug = data$conceptName, + UserPrevalence = round(data$personCount/(denominator$days / 365.25 / 1000), digits = 2)) + } + + data <- numerator[numerator$inpatient == 0,] + if (denominatorType == ""persons"") { + table3b <- data.frame(Class = data$classId, + Drug = data$conceptName, + UserPrevalence = round(data$personCount/(denominator$persons / 1000), digits = 2)) + } else { + table3b <- data.frame(Class = data$classId, + Drug = data$conceptName, + UserPrevalence = round(data$personCount/(denominator$days / 365.25 / 1000), digits = 2)) + } + + write.csv(table3a, ""Table3a.csv"", row.names = FALSE) + write.csv(table3b, ""Table3b.csv"", row.names = FALSE) +} + +createFigure1 <- function(denominatorType) { + denominator <- read.csv(""DenominatorByAgeGroup.csv"", stringsAsFactors = FALSE) + numerator <- read.csv(""NumeratorByAgeGroupByClass.csv"", stringsAsFactors = FALSE) + + numeratorInpatient <- numerator[numerator$inpatient == 1,] + if (nrow(numeratorInpatient) != 0){ + data <- merge(denominator, numeratorInpatient) + if (denominatorType == ""persons"") { + data$Prevalence <- data$personCount/(data$persons / 1000) + } else { + data$Prevalence <- data$personCount/(data$days / 365.25 / 1000) + } + data$ageGroup <- factor(data$ageGroup, levels = c(""<2 years"",""2-11 years"",""12-18 years"")) + ggplot2::ggplot(data, ggplot2::aes(x = ageGroup, y = Prevalence)) + + ggplot2::geom_bar(stat = ""identity"") + + ggplot2::facet_grid(.~ conceptName) + + ggplot2::theme(axis.text.x = ggplot2::element_text(angle=-90), + strip.text.x = ggplot2::element_text(angle=-90)) + ggplot2::ggsave(""Figure1a.png"", width = 9, height = 9, dpi= 200) + } + + numeratorNotInpatient <- numerator[numerator$inpatient == 0,] + if (nrow(numeratorNotInpatient) != 0){ + data <- merge(denominator, numeratorNotInpatient) + if (denominatorType == ""persons"") { + data$Prevalence <- data$personCount/(data$persons / 1000) + } else { + data$Prevalence <- data$personCount/(data$days / 365.25 / 1000) + } + data$ageGroup <- factor(data$ageGroup, levels = c(""<2 years"",""2-11 years"",""12-18 years"")) + ggplot2::ggplot(data, ggplot2::aes(x = ageGroup, y = Prevalence)) + + ggplot2::geom_bar(stat = ""identity"") + + ggplot2::facet_grid(.~ conceptName) + + ggplot2::theme(axis.text.x = ggplot2::element_text(angle=-90), + strip.text.x = ggplot2::element_text(angle=-90)) + ggplot2::ggsave(""Figure1b.png"", width = 9, height = 9, dpi= 200) + } +} + +createFigure2 <- function(denominatorType) { + denominator <- read.csv(""DenominatorByGender.csv"", stringsAsFactors = FALSE) + numerator <- read.csv(""NumeratorByGenderByClass.csv"", stringsAsFactors = FALSE) + + numeratorInpatient <- numerator[numerator$inpatient == 1,] + if (nrow(numeratorInpatient) != 0){ + data <- merge(denominator, numeratorInpatient) + if (denominatorType == ""persons"") { + data$Prevalence <- data$personCount/(data$persons / 1000) + } else { + data$Prevalence <- data$personCount/(data$days / 365.25 / 1000) + } + data$Gender <- ""Male"" + data$Gender[data$genderConceptId == 8532] <- ""Female"" + ggplot2::ggplot(data, ggplot2::aes(x = Gender, y = Prevalence)) + + ggplot2::geom_bar(stat = ""identity"") + + ggplot2::facet_grid(.~ conceptName) + + ggplot2::theme(axis.text.x = ggplot2::element_text(angle=-90), + strip.text.x = ggplot2::element_text(angle=-90)) + ggplot2::ggsave(""Figure2a.png"", width = 9, height = 9, dpi= 200) + } + numeratorNotInpatient <- numerator[numerator$inpatient == 0,] + if (nrow(numeratorNotInpatient) != 0){ + data <- merge(denominator, numeratorNotInpatient) + if (denominatorType == ""persons"") { + data$Prevalence <- data$personCount/(data$persons / 1000) + } else { + data$Prevalence <- data$personCount/(data$days / 365.25 / 1000) + } + data$Gender <- ""Male"" + data$Gender[data$genderConceptId == 8532] <- ""Female"" + ggplot2::ggplot(data, ggplot2::aes(x = Gender, y = Prevalence)) + + ggplot2::geom_bar(stat = ""identity"") + + ggplot2::facet_grid(.~ conceptName) + + ggplot2::theme(axis.text.x = ggplot2::element_text(angle=-90), + strip.text.x = ggplot2::element_text(angle=-90)) + ggplot2::ggsave(""Figure2b.png"", width = 9, height = 9, dpi= 200) + } +} + +createFigure3 <- function(denominatorType) { + denominator <- read.csv(""DenominatorByAgeGroupByYear.csv"", stringsAsFactors = FALSE) + numerator <- read.csv(""NumeratorByAgeGroupByYearByClass.csv"", stringsAsFactors = FALSE) + + numeratorInpatient <- numerator[numerator$inpatient == 1,] + if (nrow(numeratorInpatient) != 0){ + data <- merge(denominator, numeratorInpatient) + if (denominatorType == ""persons"") { + data$Prevalence <- data$personCount/(data$persons / 1000) + } else { + data$Prevalence <- data$personCount/(data$days / 365.25 / 1000) + } + data$ageGroup <- factor(data$ageGroup, levels = c(""<2 years"",""2-11 years"",""12-18 years"")) + ggplot2::ggplot(data, ggplot2::aes(x = calendarYear, y = Prevalence)) + + ggplot2::geom_line() + + ggplot2::facet_grid(conceptName ~ ageGroup, scales = ""free"") + + ggplot2::theme(axis.text.x = ggplot2::element_text(angle=-90), + strip.text.y = ggplot2::element_text(angle=0)) + ggplot2::ggsave(""Figure3a.png"", width = 10, height = 8, dpi= 200) + } + + numeratorNotInpatient <- numerator[numerator$inpatient == 0,] + if (nrow(numeratorNotInpatient) != 0){ + data <- merge(denominator, numeratorNotInpatient) + if (denominatorType == ""persons"") { + data$Prevalence <- data$personCount/(data$persons / 1000) + } else { + data$Prevalence <- data$personCount/(data$days / 365.25 / 1000) + } + data$ageGroup <- factor(data$ageGroup, levels = c(""<2 years"",""2-11 years"",""12-18 years"")) + ggplot2::ggplot(data, ggplot2::aes(x = calendarYear, y = Prevalence)) + + ggplot2::geom_line() + + ggplot2::facet_grid(conceptName ~ ageGroup, scales = ""free"") + + ggplot2::theme(axis.text.x = ggplot2::element_text(angle=-90), + strip.text.y = ggplot2::element_text(angle=0)) + ggplot2::ggsave(""Figure3b.png"", width = 10, height = 8, dpi= 200) + } +} + +#' @title Create figures and tables for the paper +#' +#' @details +#' This function creates the figures and tables specified in the protocol, based on the data files generated using the \code{\link{execute}} function. +#' +#' Note that this function requires access to a CDM database to query the vocabulary. +#' +#' @return +#' Creates CSV and PNG files in the specified folder. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the \code{\link[DatabaseConnector]{createConnectionDetails}} +#' function in the DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. Note that for SQL Server, this should include +#' both the database and schema name, for example 'cdm_data.dbo'. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write priviliges for storing temporary tables. +#' @param cdmVersion Version of the CDM. Can be ""4"" or ""5"" +#' @param folder (Optional) Name of local file to place results; make sure to use forward slashes (/) +#' +#' @export +createFiguresAndTables <- function(connectionDetails, + cdmDatabaseSchema, + oracleTempSchema = cdmDatabaseSchema, + cdmVersion, + folder){ + # Study parameters: + denominatorType <- ""persons"" # denominatorType can be ""persons"" or ""person time"" + + writeLines(""Creating tables and figures"") + setwd(folder) + conn <- DatabaseConnector::connect(connectionDetails) + createTable1() + createTable2(conn = conn, + cdmDatabaseSchema = cdmDatabaseSchema, + denominatorType = denominatorType) + createTable3(denominatorType = denominatorType) + createFigure1(denominatorType = denominatorType) + createFigure2(denominatorType = denominatorType) + createFigure3(denominatorType = denominatorType) + DBI::dbDisconnect(conn) + writeLines(""Done"") +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","DrugsInPeds/R/DrugsInPeds.R",".R","745","23","# Copyright 2016 Observational Health Data Sciences and Informatics +# +# This file is part of DrugsInPeds +# +# 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. + +#' DrugsInPeds +#' +#' @docType package +#' @name DrugsInPeds +#' @import DatabaseConnector +NULL +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","DrugsInPeds/R/StudySpecific.R",".R","19392","430","# Copyright 2016 Observational Health Data Sciences and Informatics +# +# This file is part of DrugsInPeds +# +# 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. + +loadHelperTables <- function(conn, oracleTempSchema){ + writeLines(""Loading helper tables"") + pathToCsv <- system.file(""csv"", + ""AgeGroups.csv"", + package = ""DrugsInPeds"") + ageGroups <- read.csv(pathToCsv, as.is = TRUE) + DatabaseConnector::insertTable(conn, table = ""#age_group"", data = ageGroups, dropTableIfExists = TRUE, createTable = TRUE, tempTable = TRUE, oracleTempSchema = oracleTempSchema) + + pathToCsv <- system.file(""csv"", + ""Years.csv"", + package = ""DrugsInPeds"") + years <- read.csv(pathToCsv, as.is = TRUE) + DatabaseConnector::insertTable(conn, table = ""#calendar_year"", data = years, dropTableIfExists = TRUE, createTable = TRUE, tempTable = TRUE, oracleTempSchema = oracleTempSchema) + + pathToCsv <- system.file(""csv"", + ""CustomClassification.csv"", + package = ""DrugsInPeds"") + classes <- read.csv(pathToCsv, as.is = TRUE) + DatabaseConnector::insertTable(conn, table = ""#drug_classes"", data = classes, dropTableIfExists = TRUE, createTable = TRUE, tempTable = TRUE, oracleTempSchema = oracleTempSchema) + + sql <- SqlRender::loadRenderTranslateSql(""CreateYearPeriods.sql"", + ""DrugsInPeds"", + attr(conn,""dbms""), + oracleTempSchema = oracleTempSchema) + DatabaseConnector::executeSql(conn, sql, progressBar = FALSE, reportOverallTime = FALSE) +} + +findPopulationWithData <- function(conn, + oracleTempSchema, + cdmDatabaseSchema, + studyStartDate, + studyEndDate, + minDaysPerPerson) { + writeLines(paste(""Finding persons with at least"", minDaysPerPerson, ""days of observation in the period"", studyStartDate, ""to"", studyEndDate)) + sql <- SqlRender::loadRenderTranslateSql(""FindPopulationWithData.sql"", + ""DrugsInPeds"", + attr(conn,""dbms""), + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + study_start_date = studyStartDate, + study_end_date = studyEndDate, + min_days_per_person = minDaysPerPerson) + DatabaseConnector::executeSql(conn, sql, progressBar = FALSE, reportOverallTime = FALSE) +} + +saveDenominator <- function(conn, + oracleTempSchema, + cdmDatabaseSchema, + studyStartDate, + studyEndDate, + splitByAgeGroup, + splitByYear, + splitByGender, + restrictToPersonsWithData, + useDerivedObservationPeriods, + fileName) { + line <- ""Getting denominator"" + if (splitByAgeGroup) { + line <- paste(line, ""by age group"") + } + if (splitByYear) { + line <- paste(line, ""by year"") + } + if (splitByGender) { + line <- paste(line, ""by gender"") + } + writeLines(line) + sql <- SqlRender::loadRenderTranslateSql(""GetDenominator.sql"", + ""DrugsInPeds"", + attr(conn,""dbms""), + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + study_start_date = studyStartDate, + study_end_date = studyEndDate, + split_by_age_group = splitByAgeGroup, + split_by_year = splitByYear, + split_by_gender = splitByGender, + restict_to_persons_with_data = restrictToPersonsWithData, + use_derived_observation_periods = useDerivedObservationPeriods) + denominator <- DatabaseConnector::querySql(conn, sql) + names(denominator) <- SqlRender::snakeCaseToCamelCase(names(denominator)) + write.csv(denominator, file = fileName, row.names = FALSE) +} + +saveNumerator <- function(conn, + oracleTempSchema, + cdmDatabaseSchema, + studyStartDate, + studyEndDate, + splitByAgeGroup, + splitByYear, + splitByGender, + splitByDrugLevel, + restrictToPersonsWithData, + cdmVersion, + fileName) { + line <- ""Getting numerator"" + if (splitByAgeGroup) { + line <- paste(line, ""by age group"") + } + if (splitByYear) { + line <- paste(line, ""by year"") + } + if (splitByGender) { + line <- paste(line, ""by gender"") + } + if (splitByDrugLevel != ""none""){ + line <- paste(line, ""at drug level"", splitByDrugLevel) + } + writeLines(line) + sql <- SqlRender::loadRenderTranslateSql(""BuildNumerator.sql"", + ""DrugsInPeds"", + attr(conn,""dbms""), + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + study_start_date = studyStartDate, + study_end_date = studyEndDate, + split_by_age_group = splitByAgeGroup, + split_by_year = splitByYear, + split_by_gender = splitByGender, + split_by_drug_level = splitByDrugLevel, + restict_to_persons_with_data = restrictToPersonsWithData, + cdm_version = cdmVersion) + DatabaseConnector::executeSql(conn, sql, progressBar = FALSE, reportOverallTime = FALSE) + + sql <- SqlRender::loadRenderTranslateSql(""GetNumerator.sql"", + ""DrugsInPeds"", + attr(conn,""dbms""), + oracleTempSchema = oracleTempSchema) + + numerator <- DatabaseConnector::querySql(conn, sql) + + sql <- SqlRender::loadRenderTranslateSql(""DropNumerator.sql"", + ""DrugsInPeds"", + attr(conn,""dbms""), + oracleTempSchema = oracleTempSchema) + + DatabaseConnector::executeSql(conn, sql, progressBar = FALSE, reportOverallTime = FALSE) + + names(numerator) <- SqlRender::snakeCaseToCamelCase(names(numerator)) + write.csv(numerator, file = fileName, row.names = FALSE) +} + +dropHelperTables <- function(conn, oracleTempSchema, restrictToPersonsWithData){ + writeLines(""Dropping helper tables"") + sql <- SqlRender::loadRenderTranslateSql(""DropHelperTables.sql"", + ""DrugsInPeds"", + attr(conn,""dbms""), + oracleTempSchema = oracleTempSchema, + restict_to_persons_with_data = restrictToPersonsWithData) + DatabaseConnector::executeSql(conn, sql, progressBar = FALSE, reportOverallTime = FALSE) +} + +compressAndEncrypt <- function(folder, file){ + pathToPublicKey <- system.file(""key"", + ""public.key"", + package = ""DrugsInPeds"") + OhdsiSharing::compressAndEncryptFolder(folder, file, pathToPublicKey) +} + +#' @title Execute OHDSI Drug Utilization in Children +#' +#' @details +#' This function executes the OHDSI Drug Utilization in Children Study. +#' +#' @return +#' Study results are placed in CSV format files in specified local folder. The CSV files are then compressed and encrypted into +#' a single file called StudyResults.zip.enc. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the \code{\link[DatabaseConnector]{createConnectionDetails}} +#' function in the DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. Note that for SQL Server, this should include +#' both the database and schema name, for example 'cdm_data.dbo'. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write priviliges for storing temporary tables. +#' @param cdmVersion Version of the CDM. Can be ""4"" or ""5"" +#' @param folder (Optional) Name of local file to place results; make sure to use forward slashes (/) +#' @param file Name of the file containing all study results. +#' +#' @examples \dontrun{ +#' connectionDetails <- createConnectionDetails(dbms = ""postgresql"", +#' user = ""joe"", +#' password = ""secret"", +#' server = ""myserver"") +#' +#' execute(connectionDetails, +#' cdmDatabaseSchema = ""cdm_data"", +#' cdmVersion = ""4"") +#' +#' } +#' +#' @export +execute <- function(connectionDetails, + cdmDatabaseSchema, + oracleTempSchema = cdmDatabaseSchema, + cdmVersion = 4, + folder = ""DrugsInPeds"", + file = ""StudyResults.zip.enc"") { + # Study parameters: + studyStartDate <- ""20090101"" + studyEndDate <- ""20131231"" + minDaysPerPerson <- 0 + useDerivedObservationPeriods <- TRUE # If TRUE, derive observation periods from the start of the first observation period to the end of the last + + if (!file.exists(folder)){ + dir.create(folder) + } + + conn <- DatabaseConnector::connect(connectionDetails) + if (is.null(conn)) { + stop(""Failed to connect to db server."") + } + start <- Sys.time() + + loadHelperTables(conn, oracleTempSchema) + + if (minDaysPerPerson != 0) { + findPopulationWithData(conn, + oracleTempSchema, + cdmDatabaseSchema, + studyStartDate, + studyEndDate, + minDaysPerPerson) + } + + saveDenominator(conn, + oracleTempSchema, + cdmDatabaseSchema, + studyStartDate, + studyEndDate, + splitByAgeGroup = FALSE, + splitByYear = FALSE, + splitByGender = FALSE, + restrictToPersonsWithData = minDaysPerPerson != 0, + useDerivedObservationPeriods = useDerivedObservationPeriods, + fileName = file.path(folder, ""Denominator.csv"")) + + saveDenominator(conn, + oracleTempSchema, + cdmDatabaseSchema, + studyStartDate, + studyEndDate, + splitByAgeGroup = TRUE, + splitByYear = FALSE, + splitByGender = FALSE, + restrictToPersonsWithData = minDaysPerPerson != 0, + useDerivedObservationPeriods = useDerivedObservationPeriods, + fileName = file.path(folder, ""DenominatorByAgeGroup.csv"")) + + saveDenominator(conn, + oracleTempSchema, + cdmDatabaseSchema, + studyStartDate, + studyEndDate, + splitByAgeGroup = FALSE, + splitByYear = TRUE, + splitByGender = FALSE, + restrictToPersonsWithData = minDaysPerPerson != 0, + useDerivedObservationPeriods = useDerivedObservationPeriods, + fileName = file.path(folder, ""DenominatorByYear.csv"")) + + saveDenominator(conn, + oracleTempSchema, + cdmDatabaseSchema, + studyStartDate, + studyEndDate, + splitByAgeGroup = FALSE, + splitByYear = FALSE, + splitByGender = TRUE, + restrictToPersonsWithData = minDaysPerPerson != 0, + useDerivedObservationPeriods = useDerivedObservationPeriods, + fileName = file.path(folder, ""DenominatorByGender.csv"")) + + saveDenominator(conn, + oracleTempSchema, + cdmDatabaseSchema, + ""20000101"", + ""20141231"", + splitByAgeGroup = TRUE, + splitByYear = TRUE, + splitByGender = FALSE, + restrictToPersonsWithData = minDaysPerPerson != 0, + useDerivedObservationPeriods = useDerivedObservationPeriods, + fileName = file.path(folder, ""DenominatorByAgeGroupByYear.csv"")) + + saveNumerator(conn, + oracleTempSchema, + cdmDatabaseSchema, + studyStartDate, + studyEndDate, + splitByAgeGroup = FALSE, + splitByYear = FALSE, + splitByGender = FALSE, + splitByDrugLevel = ""none"", + restrictToPersonsWithData = minDaysPerPerson != 0, + cdmVersion = cdmVersion, + fileName = file.path(folder, ""Numerator.csv"")) + + saveNumerator(conn, + oracleTempSchema, + cdmDatabaseSchema, + studyStartDate, + studyEndDate, + splitByAgeGroup = TRUE, + splitByYear = FALSE, + splitByGender = FALSE, + splitByDrugLevel = ""none"", + restrictToPersonsWithData = minDaysPerPerson != 0, + cdmVersion = cdmVersion, + fileName = file.path(folder, ""NumeratorByAgeGroup.csv"")) + + saveNumerator(conn, + oracleTempSchema, + cdmDatabaseSchema, + studyStartDate, + studyEndDate, + splitByAgeGroup = FALSE, + splitByYear = TRUE, + splitByGender = FALSE, + splitByDrugLevel = ""none"", + restrictToPersonsWithData = minDaysPerPerson != 0, + cdmVersion = cdmVersion, + fileName = file.path(folder, ""NumeratorByYear.csv"")) + + saveNumerator(conn, + oracleTempSchema, + cdmDatabaseSchema, + studyStartDate, + studyEndDate, + splitByAgeGroup = FALSE, + splitByYear = FALSE, + splitByGender = TRUE, + splitByDrugLevel = ""none"", + restrictToPersonsWithData = minDaysPerPerson != 0, + cdmVersion = cdmVersion, + fileName = file.path(folder, ""NumeratorByGender.csv"")) + + saveNumerator(conn, + oracleTempSchema, + cdmDatabaseSchema, + studyStartDate, + studyEndDate, + splitByAgeGroup = FALSE, + splitByYear = FALSE, + splitByGender = FALSE, + splitByDrugLevel = ""ingredient"", + restrictToPersonsWithData = minDaysPerPerson != 0, + cdmVersion = cdmVersion, + fileName = file.path(folder, ""NumeratorByIngredient.csv"")) + + saveNumerator(conn, + oracleTempSchema, + cdmDatabaseSchema, + studyStartDate, + studyEndDate, + splitByAgeGroup = FALSE, + splitByYear = FALSE, + splitByGender = FALSE, + splitByDrugLevel = ""class"", + restrictToPersonsWithData = minDaysPerPerson != 0, + cdmVersion = cdmVersion, + fileName = file.path(folder, ""NumeratorByClass.csv"")) + + saveNumerator(conn, + oracleTempSchema, + cdmDatabaseSchema, + studyStartDate, + studyEndDate, + splitByAgeGroup = TRUE, + splitByYear = FALSE, + splitByGender = FALSE, + splitByDrugLevel = ""class"", + restrictToPersonsWithData = minDaysPerPerson != 0, + cdmVersion = cdmVersion, + fileName = file.path(folder, ""NumeratorByAgeGroupByClass.csv"")) + + saveNumerator(conn, + oracleTempSchema, + cdmDatabaseSchema, + studyStartDate, + studyEndDate, + splitByAgeGroup = FALSE, + splitByYear = FALSE, + splitByGender = TRUE, + splitByDrugLevel = ""class"", + restrictToPersonsWithData = minDaysPerPerson != 0, + cdmVersion = cdmVersion, + fileName = file.path(folder, ""NumeratorByGenderByClass.csv"")) + + saveNumerator(conn, + oracleTempSchema, + cdmDatabaseSchema, + ""20000101"", + ""20141231"", + splitByAgeGroup = TRUE, + splitByYear = TRUE, + splitByGender = FALSE, + splitByDrugLevel = ""class"", + restrictToPersonsWithData = minDaysPerPerson != 0, + cdmVersion = cdmVersion, + fileName = file.path(folder, ""NumeratorByAgeGroupByYearByClass.csv"")) + + dropHelperTables(conn = conn, + oracleTempSchema = oracleTempSchema, + restrictToPersonsWithData = minDaysPerPerson != 0) + + DBI::dbDisconnect(conn) + + compressAndEncrypt(folder, file.path(folder, file)) + + # Report time + delta <- Sys.time() - start + writeLines(paste(""Analysis took"", signif(delta, 3), attr(delta, ""units""))) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","DrugsInPeds/extras/PackageMaintenance.R",".R","1742","46","# @file PackageMaintenance +# +# Copyright 2016 Observational Health Data Sciences and Informatics +# +# This file is part of DrugsInPeds +# +# 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. + +# Format and check code: +OhdsiRTools::formatRFolder() +OhdsiRTools::checkUsagePackage(""DrugsInPeds"") +OhdsiRTools::updateCopyrightYearFolder() + + +# Create manual : +shell(""rm extras/DrugsInPeds.pdf"") +shell(""R CMD Rd2pdf ./ --output=extras/DrugsInPeds.pdf"") + + +# Create custom drug classification: +connectionDetails <- DatabaseConnector::createConnectionDetails(dbms = ""sql server"", + server = ""RNDUSRDHIT06.jnj.com"") +conn <- DatabaseConnector::connect(connectionDetails) +DatabaseConnector::executeSql(conn, ""USE [OMOP_Vocabulary_20160311]"") +sql <- SqlRender::readSql(""extras/BuildCustomDrugClassification.sql"") +DatabaseConnector::executeSql(conn, sql) +classification <- DatabaseConnector::querySql(conn, ""SELECT * FROM #my_drug_classification ORDER BY class_id, concept_name"") +write.csv(classification, ""inst/csv/CustomClassification.csv"", row.names = FALSE) +RJDBC::dbDisconnect(conn) + +# Store environment in which the study was executed +OhdsiRTools::insertEnvironmentSnapshotInPackage(""DrugsInPeds"") + + + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","DrugsInPeds/extras/FigureMockups.R",".R","3495","58","# Copyright 2016 Observational Health Data Sciences and Informatics +# +# This file is part of DrugsInPeds +# +# 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. + +createMockupsForProtocol <- function(){ + library(ggplot2) + + #data <- expand.grid(c(""CDARS"",""JMDC"",""NHIRD"", ""AUSOM"",""CCAE""), c(""<2"",""2-11"",""12-18""), c(""A"",""B"",""C"",""D"",""G"",""H"",""J"",""L"",""M"",""N"",""P"")) + data <- expand.grid(c(""CDARS"",""JMDC"",""NHIRD"", ""AUSOM"",""CCAE""), c(""<2"",""2-11"",""12-18""), c(""Adrenergics"", ""Analgesics (inc. NSAIDs)"", ""Antibiotics"", ""Antidiabetic drugs"", ""Antiepileptics"", ""Antihistamines"", ""Antiinfectives (excluding antibiotics)"", ""Antineoplastic and immunomodulating agents"", ""Antithrombotic agents"", ""Central nervous system stimulants"", ""Contraceptives"", ""Corticosteroid"", ""Diuretics"", ""Mucolytics"", ""Psychotherapeutic agents"")) + colnames(data) <- c(""Database"",""Age"",""Class"") + data$Prevalence <- runif(nrow(data),0,100) + + ggplot(data, aes(x = Age, y = Prevalence, group = Database, fill = Database)) + + geom_bar(stat = ""identity"") + + facet_grid(.~ Class) + + theme(axis.text.x = element_text(angle=-90), + strip.text.x = element_text(angle=-90)) + + ggsave(""extras/mockup1.png"", width = 9, height = 5, dpi= 200) + + data <- expand.grid(c(""CDARS"",""JMDC"",""NHIRD"", ""AUSOM"",""CCAE""), c(""Male"",""Female""), c(""Adrenergics"", ""Analgesics (inc. NSAIDs)"", ""Antibiotics"", ""Antidiabetic drugs"", ""Antiepileptics"", ""Antihistamines"", ""Antiinfectives (excluding antibiotics)"", ""Antineoplastic and immunomodulating agents"", ""Antithrombotic agents"", ""Central nervous system stimulants"", ""Contraceptives"", ""Corticosteroid"", ""Diuretics"", ""Mucolytics"", ""Psychotherapeutic agents"")) + colnames(data) <- c(""Database"",""Gender"",""Class"") + data$Prevalence <- runif(nrow(data),0,100) + + ggplot(data, aes(x = Gender, y = Prevalence, group = Database, fill = Database)) + + geom_bar(stat = ""identity"") + + facet_grid(.~ Class) + + theme(axis.text.x = element_text(angle=-90), + strip.text.x = element_text(angle=-90)) + + ggsave(""extras/mockup2.png"", width = 9, height = 5, dpi= 200) + + + data <- expand.grid(c(""CDARS"",""JMDC"",""NHIRD"", ""AUSOM"",""CCAE""), c(""<2"",""2-11"",""12-18""), c(""Adrenergics"", ""Analgesics (inc. NSAIDs)"", ""Antibiotics"", ""Antidiabetic drugs"", ""Antiepileptics"", ""Antihistamines"", ""Antiinfectives (excluding antibiotics)"", ""Antineoplastic and immunomodulating agents"", ""Antithrombotic agents"", ""Central nervous system stimulants"", ""Contraceptives"", ""Corticosteroid"", ""Diuretics"", ""Mucolytics"", ""Psychotherapeutic agents""), 2008:2014) + colnames(data) <- c(""Database"",""Age"",""Class"", ""Year"") + data$Prevalence <- runif(nrow(data),0,100) + + ggplot(data, aes(x = Year, y = Prevalence, group = Database, color = Database)) + + geom_line() + + facet_grid(Class ~ Age) + + theme(axis.text.x = element_text(angle=-90), + strip.text.y = element_text(angle=0)) + + ggsave(""extras/mockup3.png"", width = 7, height = 8, dpi= 200) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","DrugsInPeds/extras/TestCode.R",".R","2386","70","library(DrugsInPeds) + +setwd('s:/temp') + +password <- NULL +user <- NULL +oracleTempSchema <- NULL + +dbms <- ""postgresql"" +server <- ""localhost/ohdsi"" +cdmDatabaseSchema <- ""cdm4_sim"" +port <- NULL +cdmVersion <- ""4"" +user <- ""postgres"" +password <- Sys.getenv(""pwPostgres"") + +dbms <- ""sql server"" +server <- ""RNDUSRDHIT07.jnj.com"" +cdmDatabaseSchema <- ""cdm4_sim.dbo"" +port <- NULL +cdmVersion <- ""4"" + +dbms <- ""sql server"" +server <- ""RNDUSRDHIT06.jnj.com"" +cdmDatabaseSchema <- ""cdm_jmdc.dbo"" +port <- NULL +cdmVersion <- ""4"" + +dbms <- ""pdw"" +server <- ""JRDUSAPSCTL01"" +cdmDatabaseSchema <- ""cdm_jmdc_v512.dbo"" +port <- 17001 +cdmVersion <- ""5"" + + +connectionDetails <- DatabaseConnector::createConnectionDetails(dbms = dbms, + server = server, + user = user, + password = password, + port = port) + +execute(connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + cdmVersion = cdmVersion, + folder = ""s:/temp/DrugsInPeds"") + +createFiguresAndTables(connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + cdmVersion = cdmVersion, + folder = ""s:/temp/DrugsInPeds"") +#OhdsiSharing::generateKeyPair(""s:/temp/public.key"",""s:/temp/private.key"") + +#OhdsiSharing::decryptAndDecompressFolder(""s:/temp/DrugsInPeds/StudyResults.zip.enc"",""s:/temp/test"",""s:/temp/private.key"") + + + +# Find drugs in multiple classes ------------------------------------------ +pathToCsv <- system.file(""csv"", + ""CustomClassification.csv"", + package = ""DrugsInPeds"") +classification <- read.csv(pathToCsv, as.is = TRUE) +classification$CONCEPT_NAME <- tolower(classification$CONCEPT_NAME) +classification <- unique(classification[, c(""CONCEPT_NAME"", ""CLASS_ID"")]) +classCounts <- aggregate(CLASS_ID ~ CONCEPT_NAME, data = classification, length) +classCounts <- classCounts[classCounts$CLASS_ID > 1, ] +duplicates <- classification[classification$CONCEPT_NAME %in% classCounts$CONCEPT_NAME, ] +write.csv(duplicates, ""s:/temp/duplicateDrugs.csv"", row.names = FALSE) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","DrugsInPeds/extras/CentralizedProcessing.R",".R","13828","315","# Copyright 2016 Observational Health Data Sciences and Informatics +# +# This file is part of DrugsInPeds +# +# 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. + +denominatorType <- ""persons"" # denominatorType can be ""persons"" or ""person time"" + +library(DrugsInPeds) +dbms <- ""sql server"" +server <- ""RNDUSRDHIT06.jnj.com"" +cdmDatabaseSchema <- ""cdm_jmdc.dbo"" +port <- NULL +cdmVersion <- ""4"" +password <- NULL +user <- NULL +oracleTempSchema <- NULL +connectionDetails <- DatabaseConnector::createConnectionDetails(dbms = dbms, + server = server, + user = user, + password = password, + port = port) +folder <- ""C:/home/Research/DrugsInPeds/results"" +privateKey <- file.path(folder, ""private.key"") + +dbs <- data.frame(name = c(""AUSOM"",""CDARS"",""JMDC"", ""NHIRD"", ""PBS""), inpatient = c(TRUE, TRUE, TRUE, TRUE, FALSE), ambulatory = c(FALSE, FALSE, TRUE, TRUE, TRUE), stringsAsFactors = FALSE) +# dbs <- data.frame(name = c(""AUSOM"",""CDARS"",""JMDC"", ""NHIRD""), inpatient = c(TRUE, TRUE, TRUE, TRUE), ambulatory = c(FALSE, FALSE, TRUE, TRUE), stringsAsFactors = FALSE) + +pathToCsv <- system.file(""csv"", + ""CustomClassification.csv"", + package = ""DrugsInPeds"") +classes <- unique(read.csv(pathToCsv, as.is = TRUE)$CLASS_ID) + +### Decrypt, decompress, and generate tables and figures per DB ### +for (i in 1:nrow(dbs)) { + dbFolder <- file.path(folder, dbs$name[i]) + #if (dbs$name[i] != ""PBS"" & dbs$name[i] != ""AUSOM"") { + # try(OhdsiSharing::decryptAndDecompressFolder(file.path(dbFolder, ""StudyResults.zip.enc""), + # dbFolder, + # privateKey)) + #} + createFiguresAndTables(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + cdmVersion = cdmVersion, + folder = dbFolder) +} + + +### Combine table 1 across DBs ### +table1 <- data.frame() +for (i in 1:nrow(dbs)) { + dbFolder <- file.path(folder, dbs$name[i]) + dbTable1 <- read.csv(file.path(dbFolder, ""table1.csv""), stringsAsFactors = FALSE) + if (!dbs$inpatient[i]) { + dbTable1[,4] <- NA + } + if (!dbs$ambulatory[i]) { + dbTable1[,5] <- NA + } + emptyRow <- dbTable1[1,] + emptyRow[1,] <- """" + headerRow <- emptyRow + headerRow[1,1] <- dbs$name[i] + table1 <- rbind(table1, emptyRow, headerRow, dbTable1) +} +write.csv(table1, file.path(folder, ""table1.csv""), row.names = FALSE, na = """") + + +### Combine tables 2a and 2b across DBs ### +table2a <- NULL +table2b <- NULL +for (i in 1:nrow(dbs)) { + dbFolder <- file.path(folder, dbs$name[i]) + if (dbs$inpatient[i]) { + dbTable2a <- read.csv(file.path(dbFolder, ""table2a.csv""), stringsAsFactors = FALSE) + names(dbTable2a)[2:3] <- paste(names(dbTable2a)[2:3], dbs$name[i], sep=""\n"") + if (is.null(table2a)){ + table2a <- dbTable2a + } else { + table2a <- merge(table2a, dbTable2a, all = TRUE) + } + } + if (dbs$ambulatory[i]) { + dbTable2b <- read.csv(file.path(dbFolder, ""table2b.csv""), stringsAsFactors = FALSE) + names(dbTable2b)[2:3] <- paste(names(dbTable2b)[2:3], dbs$name[i], sep=""\n"") + if (is.null(table2b)){ + table2b <- dbTable2b + } else { + table2b <- merge(table2b, dbTable2b, all = TRUE) + } + } +} +table2a <- table2a[,order(names(table2a))] +table2b <- table2b[,order(names(table2b))] +write.csv(table2a, file.path(folder, ""table2a.csv""), row.names = FALSE, na = """") +write.csv(table2b, file.path(folder, ""table2b.csv""), row.names = FALSE, na = """") + + +### Combine tables 3a and 3b across DBs ### +table3a <- NULL +table3b <- NULL +for (i in 1:nrow(dbs)) { + dbFolder <- file.path(folder, dbs$name[i]) + if (dbs$inpatient[i]) { + dbTable3a <- read.csv(file.path(dbFolder, ""table3a.csv""), stringsAsFactors = FALSE) + counts <- aggregate(Drug ~ Class, data = dbTable3a, length) + counts$Drug <- 5 - counts$Drug + counts <- counts[counts$Drug != 0, ] + for (j in 1:nrow(counts)) { + dbTable3a <- rbind(dbTable3a, + data.frame(Class = rep(counts$Class[j], each = counts$Drug[j]), + Drug = """", + UserPrevalence = NA)) + } + dbTable3a <- dbTable3a[order(dbTable3a$Class, -dbTable3a$UserPrevalence), ] + names(dbTable3a)[2:3] <- paste(dbs$name[i], names(dbTable3a)[2:3], sep=""\n"") + + if (is.null(table3a)){ + table3a <- dbTable3a + } else { + table3a <- cbind(table3a, dbTable3a[, c(2,3)]) + } + } + dbFolder <- file.path(folder, dbs$name[i]) + if (dbs$ambulatory[i]) { + dbTable3b <- read.csv(file.path(dbFolder, ""table3b.csv""), stringsAsFactors = FALSE) + dbTable3b <- dbTable3b[!is.na(dbTable3b$Class),] + counts <- aggregate(Drug ~ Class, data = dbTable3b, length) + counts$Drug <- 5 - counts$Drug + counts <- counts[counts$Drug != 0, ] + for (j in 1:nrow(counts)) { + dbTable3b <- rbind(dbTable3b, + data.frame(Class = rep(counts$Class[j], each = counts$Drug[j]), + Drug = """", + UserPrevalence = NA)) + } + dbTable3b <- dbTable3b[order(dbTable3b$Class, -dbTable3b$UserPrevalence), ] + names(dbTable3b)[2:3] <- paste(dbs$name[i], names(dbTable3b)[2:3], sep=""\n"") + if (is.null(table3b)){ + table3b <- dbTable3b + } else { + table3b <- cbind(table3b, dbTable3b[, c(2,3)]) + } + } +} +write.csv(table3a, file.path(folder, ""table3a.csv""), row.names = FALSE, na = """") +write.csv(table3b, file.path(folder, ""table3b.csv""), row.names = FALSE, na = """") + + +### Combine figures 1a and 1b across DBs ### +denominator <- data.frame() +numerator <- data.frame() +for (i in 1:nrow(dbs)) { + dbFolder <- file.path(folder, dbs$name[i]) + dbDenominator <- read.csv(file.path(dbFolder, ""DenominatorByAgeGroup.csv""), stringsAsFactors = FALSE) + dbNumerator <- read.csv(file.path(dbFolder, ""NumeratorByAgeGroupByClass.csv""), stringsAsFactors = FALSE) + dbDenominator$db <- dbs$name[i] + dbNumerator$db <- dbs$name[i] + if (!dbs$inpatient[i]) { + dbNumerator <- dbNumerator[dbNumerator$inpatient == 0,] + } + if (!dbs$ambulatory[i]) { + dbNumerator <- dbNumerator[dbNumerator$inpatient == 1,] + } + denominator <- rbind(denominator, dbDenominator) + numerator <- rbind(numerator, dbNumerator) +} +numeratorInpatient <- numerator[numerator$inpatient == 1,] + +data <- merge(denominator, numeratorInpatient) +if (denominatorType == ""persons"") { + data$Prevalence <- data$personCount/(data$persons / 1000) +} else { + data$Prevalence <- data$personCount/(data$days / 365.25 / 1000) +} +data$ageGroup <- factor(data$ageGroup, levels = c(""<2 years"",""2-11 years"",""12-18 years"")) +ggplot2::ggplot(data, ggplot2::aes(x = ageGroup, y = Prevalence)) + + ggplot2::geom_bar(stat = ""identity"") + + ggplot2::facet_grid(db ~ conceptName, scales = ""free_y"") + + ggplot2::xlab(""Age group"") + + ggplot2::theme(axis.text.x = ggplot2::element_text(angle=-90), + strip.text.x = ggplot2::element_text(angle=-90)) +ggplot2::ggsave(file.path(folder, ""Figure1a.png""), width = 9, height = 7, dpi= 200) + +numeratorNotInpatient <- numerator[numerator$inpatient == 0,] +data <- merge(denominator, numeratorNotInpatient) +if (denominatorType == ""persons"") { + data$Prevalence <- data$personCount/(data$persons / 1000) +} else { + data$Prevalence <- data$personCount/(data$days / 365.25 / 1000) +} +data$ageGroup <- factor(data$ageGroup, levels = c(""<2 years"",""2-11 years"",""12-18 years"")) +ggplot2::ggplot(data, ggplot2::aes(x = ageGroup, y = Prevalence)) + + ggplot2::geom_bar(stat = ""identity"") + + ggplot2::facet_grid(db ~ conceptName, scales = ""free_y"") + + ggplot2::xlab(""Age group"") + + ggplot2::theme(axis.text.x = ggplot2::element_text(angle=-90), + strip.text.x = ggplot2::element_text(angle=-90)) +ggplot2::ggsave(file.path(folder, ""Figure1b.png""), width = 9, height = 7, dpi= 200) + + +### Combine figures 2a and 2b across DBs ### +denominator <- data.frame() +numerator <- data.frame() +for (i in 1:nrow(dbs)) { + dbFolder <- file.path(folder, dbs$name[i]) + dbDenominator <- read.csv(file.path(dbFolder, ""DenominatorByGender.csv""), stringsAsFactors = FALSE) + dbNumerator <- read.csv(file.path(dbFolder, ""NumeratorByGenderByClass.csv""), stringsAsFactors = FALSE) + dbDenominator$db <- dbs$name[i] + dbNumerator$db <- dbs$name[i] + if (!dbs$inpatient[i]) { + dbNumerator <- dbNumerator[dbNumerator$inpatient == 0,] + } + if (!dbs$ambulatory[i]) { + dbNumerator <- dbNumerator[dbNumerator$inpatient == 1,] + } + denominator <- rbind(denominator, dbDenominator) + numerator <- rbind(numerator, dbNumerator) +} +numeratorInpatient <- numerator[numerator$inpatient == 1,] + +data <- merge(denominator, numeratorInpatient) +if (denominatorType == ""persons"") { + data$Prevalence <- data$personCount/(data$persons / 1000) +} else { + data$Prevalence <- data$personCount/(data$days / 365.25 / 1000) +} +data$Gender <- ""Male"" +data$Gender[data$genderConceptId == 8532] <- ""Female"" +ggplot2::ggplot(data, ggplot2::aes(x = Gender, y = Prevalence)) + + ggplot2::geom_bar(stat = ""identity"") + + ggplot2::facet_grid(db ~ conceptName, scales = ""free_y"") + + ggplot2::theme(axis.text.x = ggplot2::element_text(angle=-90), + strip.text.x = ggplot2::element_text(angle=-90)) +ggplot2::ggsave(file.path(folder, ""Figure2a.png""), width = 9, height = 9, dpi= 200) + +numeratorNotInpatient <- numerator[numerator$inpatient == 0,] +data <- merge(denominator, numeratorNotInpatient) +if (denominatorType == ""persons"") { + data$Prevalence <- data$personCount/(data$persons / 1000) +} else { + data$Prevalence <- data$personCount/(data$days / 365.25 / 1000) +} +data$Gender <- ""Male"" +data$Gender[data$genderConceptId == 8532] <- ""Female"" +ggplot2::ggplot(data, ggplot2::aes(x = Gender, y = Prevalence)) + + ggplot2::geom_bar(stat = ""identity"") + + ggplot2::facet_grid(db ~ conceptName, scales = ""free_y"") + + ggplot2::theme(axis.text.x = ggplot2::element_text(angle=-90), + strip.text.x = ggplot2::element_text(angle=-90)) +ggplot2::ggsave(file.path(folder, ""Figure2b.png""), width = 9, height = 9, dpi= 200) + + +### Combine figures 3a and 3b across DBs ### +denominator <- data.frame() +numerator <- data.frame() +for (i in 1:nrow(dbs)) { + dbFolder <- file.path(folder, dbs$name[i]) + dbDenominator <- read.csv(file.path(dbFolder, ""DenominatorByAgeGroupByYear.csv""), stringsAsFactors = FALSE) + dbNumerator <- read.csv(file.path(dbFolder, ""NumeratorByAgeGroupByYearByClass.csv""), stringsAsFactors = FALSE) + dbDenominator$db <- dbs$name[i] + dbNumerator$db <- dbs$name[i] + dbDenominator <- dbDenominator[dbDenominator$calendarYear >= 2008 & dbDenominator$calendarYear <= 2013,] + dbNumerator <- dbNumerator[dbNumerator$calendarYear >= 2008 & dbNumerator$calendarYear <= 2013,] + if (!dbs$inpatient[i]) { + dbNumerator <- dbNumerator[dbNumerator$inpatient == 0,] + } + if (!dbs$ambulatory[i]) { + dbNumerator <- dbNumerator[dbNumerator$inpatient == 1,] + } + denominator <- rbind(denominator, dbDenominator) + numerator <- rbind(numerator, dbNumerator) +} +numeratorInpatient <- numerator[numerator$inpatient == 1,] +data <- merge(denominator, numeratorInpatient) +if (denominatorType == ""persons"") { + data$Prevalence <- data$personCount/(data$persons / 1000) +} else { + data$Prevalence <- data$personCount/(data$days / 365.25 / 1000) +} +data$ageGroup <- factor(data$ageGroup, levels = c(""<2 years"",""2-11 years"",""12-18 years"")) +ggplot2::ggplot(data, ggplot2::aes(x = calendarYear, y = Prevalence, group = db, color = db)) + + ggplot2::geom_line() + + ggplot2::facet_grid(conceptName ~ ageGroup, scales = ""free"") + + ggplot2::theme(axis.text.x = ggplot2::element_text(angle=-90), + strip.text.y = ggplot2::element_text(angle=0)) +ggplot2::ggsave(file.path(folder, ""Figure3a.png""), width = 12, height = 8, dpi= 200) + +numeratorNotInpatient <- numerator[numerator$inpatient == 0,] +data <- merge(denominator, numeratorNotInpatient) +if (denominatorType == ""persons"") { + data$Prevalence <- data$personCount/(data$persons / 1000) +} else { + data$Prevalence <- data$personCount/(data$days / 365.25 / 1000) +} +data$ageGroup <- factor(data$ageGroup, levels = c(""<2 years"",""2-11 years"",""12-18 years"")) +ggplot2::ggplot(data, ggplot2::aes(x = calendarYear, y = Prevalence, group = db, color = db)) + + ggplot2::geom_line() + + ggplot2::facet_grid(conceptName ~ ageGroup, scales = ""free"") + + ggplot2::theme(axis.text.x = ggplot2::element_text(angle=-90), + strip.text.y = ggplot2::element_text(angle=0)) +ggplot2::ggsave(file.path(folder, ""Figure3b.png""), width = 12, height = 8, dpi= 200) + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","DrugsInPeds/extras/CentralizedProcessingAntibioticsOnly.R",".R","18217","405","# Copyright 2016 Observational Health Data Sciences and Informatics +# +# This file is part of DrugsInPeds +# +# 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. + +denominatorType <- ""persons"" # denominatorType can be ""persons"" or ""person time"" + +library(DrugsInPeds) +dbms <- ""sql server"" +server <- ""RNDUSRDHIT06.jnj.com"" +cdmDatabaseSchema <- ""cdm_jmdc.dbo"" +port <- NULL +cdmVersion <- ""4"" +password <- NULL +user <- NULL +oracleTempSchema <- NULL +connectionDetails <- DatabaseConnector::createConnectionDetails(dbms = dbms, + server = server, + user = user, + password = password, + port = port) +folder <- ""C:/home/Research/DrugsInPeds/results"" +antibioticsFolder <- ""C:/home/Research/DrugsInPeds/results/antibiotics"" +if (!file.exists(antibioticsFolder)){ + dir.create(antibioticsFolder) +} + +privateKey <- file.path(folder, ""private.key"") + +dbs <- data.frame(name = c(""AUSOM"",""CDARS"",""JMDC"", ""NHIRD"", ""PBS""), inpatient = c(TRUE, TRUE, TRUE, TRUE, FALSE), ambulatory = c(FALSE, FALSE, TRUE, TRUE, TRUE), stringsAsFactors = FALSE) +#dbs <- data.frame(name = c(""AUSOM"",""JMDC"", ""PBS"", ""NHIRD""), inpatient = c(TRUE, TRUE, FALSE, TRUE), ambulatory = c(FALSE, TRUE, TRUE, TRUE), stringsAsFactors = FALSE) + +classes <- c(""Antibiotics"") + +### Decrypt, decompress, and generate tables and figures per DB ### +for (i in 1:nrow(dbs)) { + dbFolder <- file.path(folder, dbs$name[i]) + #if (dbs$name[i] != ""PBS"" & dbs$name[i] != ""AUSOM"") { + # try(OhdsiSharing::decryptAndDecompressFolder(file.path(dbFolder, ""StudyResults.zip.enc""), + # dbFolder, + # privateKey)) + #} + # createFiguresAndTables(connectionDetails = connectionDetails, + # cdmDatabaseSchema = cdmDatabaseSchema, + # oracleTempSchema = oracleTempSchema, + # cdmVersion = cdmVersion, + # folder = dbFolder) + + setwd(dbFolder) + DrugsInPeds:::createTable3(denominatorType = ""persons"", drugsPerClass = 20) +} + + +### Combine table 1 across DBs ### +table1 <- data.frame() +for (i in 1:nrow(dbs)) { + dbFolder <- file.path(folder, dbs$name[i]) + dbTable1 <- read.csv(file.path(dbFolder, ""table1.csv""), stringsAsFactors = FALSE) + if (!dbs$inpatient[i]) { + dbTable1[,4] <- NA + } + if (!dbs$ambulatory[i]) { + dbTable1[,5] <- NA + } + emptyRow <- dbTable1[1,] + emptyRow[1,] <- """" + headerRow <- emptyRow + headerRow[1,1] <- dbs$name[i] + table1 <- rbind(table1, emptyRow, headerRow, dbTable1) +} +write.csv(table1, file.path(antibioticsFolder, ""table1.csv""), row.names = FALSE, na = """") + + +### Combine tables 2a and 2b across DBs ### +table2a <- NULL +table2b <- NULL +for (i in 1:nrow(dbs)) { + dbFolder <- file.path(folder, dbs$name[i]) + if (dbs$inpatient[i]) { + dbTable2a <- read.csv(file.path(dbFolder, ""table2a.csv""), stringsAsFactors = FALSE) + dbTable2a <- dbTable2a[dbTable2a$Class %in% classes, ] + names(dbTable2a)[2:3] <- paste(names(dbTable2a)[2:3], dbs$name[i], sep=""\n"") + if (is.null(table2a)){ + table2a <- dbTable2a + } else { + table2a <- merge(table2a, dbTable2a, all.x = TRUE) + } + } + if (dbs$ambulatory[i]) { + dbTable2b <- read.csv(file.path(dbFolder, ""table2b.csv""), stringsAsFactors = FALSE) + dbTable2b <- dbTable2b[dbTable2b$Class %in% classes, ] + names(dbTable2b)[2:3] <- paste(names(dbTable2b)[2:3], dbs$name[i], sep=""\n"") + if (is.null(table2b)){ + table2b <- dbTable2b + } else { + table2b <- merge(table2b, dbTable2b, all.x = TRUE) + } + } +} +table2a <- table2a[,order(names(table2a))] +table2b <- table2b[,order(names(table2b))] +write.csv(table2a, file.path(antibioticsFolder, ""table2a.csv""), row.names = FALSE, na = """") +write.csv(table2b, file.path(antibioticsFolder, ""table2b.csv""), row.names = FALSE, na = """") + + +### Combine tables 3a and 3b across DBs ### +table3a <- NULL +table3b <- NULL +for (i in 1:nrow(dbs)) { + dbFolder <- file.path(folder, dbs$name[i]) + if (dbs$inpatient[i]) { + dbTable3a <- read.csv(file.path(dbFolder, ""table3a.csv""), stringsAsFactors = FALSE) + dbTable3a <- dbTable3a[dbTable3a$Class %in% classes, ] + dbTable3a <- dbTable3a[order(dbTable3a$Class, -dbTable3a$UserPrevalence), ] + names(dbTable3a)[2:3] <- paste(dbs$name[i], names(dbTable3a)[2:3], sep=""\n"") + + if (is.null(table3a)){ + table3a <- dbTable3a + } else { + table3a <- cbind(table3a, dbTable3a[, c(2,3)]) + } + } + dbFolder <- file.path(folder, dbs$name[i]) + if (dbs$ambulatory[i]) { + dbTable3b <- read.csv(file.path(dbFolder, ""table3b.csv""), stringsAsFactors = FALSE) + dbTable3b <- dbTable3b[dbTable3b$Class %in% classes, ] + dbTable3b <- dbTable3b[!is.na(dbTable3b$Class),] + dbTable3b <- dbTable3b[order(dbTable3b$Class, -dbTable3b$UserPrevalence), ] + names(dbTable3b)[2:3] <- paste(dbs$name[i], names(dbTable3b)[2:3], sep=""\n"") + if (is.null(table3b)){ + table3b <- dbTable3b + } else { + table3b <- cbind(table3b, dbTable3b[, c(2,3)]) + } + } +} +write.csv(table3a, file.path(antibioticsFolder, ""table3a.csv""), row.names = FALSE, na = """") +write.csv(table3b, file.path(antibioticsFolder, ""table3b.csv""), row.names = FALSE, na = """") + +denominator <- data.frame() +numerator <- data.frame() +for (i in 1:nrow(dbs)) { + dbFolder <- file.path(folder, dbs$name[i]) + dbDenominator <- read.csv(file.path(dbFolder, ""DenominatorByAgeGroup.csv""), stringsAsFactors = FALSE) + dbNumerator <- read.csv(file.path(dbFolder, ""NumeratorByAgeGroupByClass.csv""), stringsAsFactors = FALSE) + dbDenominator$db <- dbs$name[i] + dbNumerator$db <- dbs$name[i] + if (!dbs$inpatient[i]) { + dbNumerator <- dbNumerator[dbNumerator$inpatient == 0,] + } + if (!dbs$ambulatory[i]) { + dbNumerator <- dbNumerator[dbNumerator$inpatient == 1,] + } + denominator <- rbind(denominator, dbDenominator) + numerator <- rbind(numerator, dbNumerator) +} +numeratorInpatient <- numerator[numerator$inpatient == 1,] + +data <- merge(denominator, numeratorInpatient) +if (denominatorType == ""persons"") { + data$Prevalence <- data$personCount/(data$persons / 1000) +} else { + data$Prevalence <- data$personCount/(data$days / 365.25 / 1000) +} +data$ageGroup <- factor(data$ageGroup, levels = c(""<2 years"",""2-11 years"",""12-18 years"")) +ggplot2::ggplot(data, ggplot2::aes(x = ageGroup, y = Prevalence)) + + ggplot2::geom_bar(stat = ""identity"") + + ggplot2::facet_grid(db ~ conceptName, scales = ""free_y"") + + ggplot2::xlab(""Age group"") + + ggplot2::theme(axis.text.x = ggplot2::element_text(angle=-90), + strip.text.x = ggplot2::element_text(angle=-90)) +ggplot2::ggsave(file.path(antibioticsFolder, ""Figure1a.png""), width = 9, height = 7, dpi= 200) + +numeratorNotInpatient <- numerator[numerator$inpatient == 0,] +data <- merge(denominator, numeratorNotInpatient) +if (denominatorType == ""persons"") { + data$Prevalence <- data$personCount/(data$persons / 1000) +} else { + data$Prevalence <- data$personCount/(data$days / 365.25 / 1000) +} +data$ageGroup <- factor(data$ageGroup, levels = c(""<2 years"",""2-11 years"",""12-18 years"")) +ggplot2::ggplot(data, ggplot2::aes(x = ageGroup, y = Prevalence)) + + ggplot2::geom_bar(stat = ""identity"") + + ggplot2::facet_grid(db ~ conceptName, scales = ""free_y"") + + ggplot2::xlab(""Age group"") + + ggplot2::theme(axis.text.x = ggplot2::element_text(angle=-90), + strip.text.x = ggplot2::element_text(angle=-90)) +ggplot2::ggsave(file.path(antibioticsFolder, ""Figure1b.png""), width = 9, height = 7, dpi= 200) + + +### Combine figures 2a and 2b across DBs ### +denominator <- data.frame() +numerator <- data.frame() +for (i in 1:nrow(dbs)) { + dbFolder <- file.path(folder, dbs$name[i]) + dbDenominator <- read.csv(file.path(dbFolder, ""DenominatorByGender.csv""), stringsAsFactors = FALSE) + dbNumerator <- read.csv(file.path(dbFolder, ""NumeratorByGenderByClass.csv""), stringsAsFactors = FALSE) + dbDenominator$db <- dbs$name[i] + dbNumerator$db <- dbs$name[i] + if (!dbs$inpatient[i]) { + dbNumerator <- dbNumerator[dbNumerator$inpatient == 0,] + } + if (!dbs$ambulatory[i]) { + dbNumerator <- dbNumerator[dbNumerator$inpatient == 1,] + } + denominator <- rbind(denominator, dbDenominator) + numerator <- rbind(numerator, dbNumerator) +} +numeratorInpatient <- numerator[numerator$inpatient == 1,] + +data <- merge(denominator, numeratorInpatient) +if (denominatorType == ""persons"") { + data$Prevalence <- data$personCount/(data$persons / 1000) +} else { + data$Prevalence <- data$personCount/(data$days / 365.25 / 1000) +} +data$Gender <- ""Male"" +data$Gender[data$genderConceptId == 8532] <- ""Female"" +ggplot2::ggplot(data, ggplot2::aes(x = Gender, y = Prevalence)) + + ggplot2::geom_bar(stat = ""identity"") + + ggplot2::facet_grid(db ~ conceptName, scales = ""free_y"") + + ggplot2::theme(axis.text.x = ggplot2::element_text(angle=-90), + strip.text.x = ggplot2::element_text(angle=-90)) +ggplot2::ggsave(file.path(antibioticsFolder, ""Figure2a.png""), width = 9, height = 9, dpi= 200) + +numeratorNotInpatient <- numerator[numerator$inpatient == 0,] +data <- merge(denominator, numeratorNotInpatient) +if (denominatorType == ""persons"") { + data$Prevalence <- data$personCount/(data$persons / 1000) +} else { + data$Prevalence <- data$personCount/(data$days / 365.25 / 1000) +} +data$Gender <- ""Male"" +data$Gender[data$genderConceptId == 8532] <- ""Female"" +ggplot2::ggplot(data, ggplot2::aes(x = Gender, y = Prevalence)) + + ggplot2::geom_bar(stat = ""identity"") + + ggplot2::facet_grid(db ~ conceptName, scales = ""free_y"") + + ggplot2::theme(axis.text.x = ggplot2::element_text(angle=-90), + strip.text.x = ggplot2::element_text(angle=-90)) +ggplot2::ggsave(file.path(antibioticsFolder, ""Figure2b.png""), width = 9, height = 9, dpi= 200) + + +# ### Combine figures 1a and 1b across DBs ### +# denominator <- data.frame() +# numerator <- data.frame() +# for (i in 1:nrow(dbs)) { +# dbFolder <- file.path(folder, dbs$name[i]) +# dbDenominator <- read.csv(file.path(dbFolder, ""DenominatorByAgeGroup.csv""), stringsAsFactors = FALSE) +# dbNumerator <- read.csv(file.path(dbFolder, ""NumeratorByAgeGroupByClass.csv""), stringsAsFactors = FALSE) +# dbNumerator <- dbNumerator[dbNumerator$conceptName %in% classes, ] +# dbDenominator$db <- dbs$name[i] +# dbNumerator$db <- dbs$name[i] +# if (!dbs$inpatient[i]) { +# dbNumerator <- dbNumerator[dbNumerator$inpatient == 0,] +# } +# if (!dbs$ambulatory[i]) { +# dbNumerator <- dbNumerator[dbNumerator$inpatient == 1,] +# } +# denominator <- rbind(denominator, dbDenominator) +# numerator <- rbind(numerator, dbNumerator) +# } +# numeratorInpatient <- numerator[numerator$inpatient == 1,] +# +# data <- merge(denominator, numeratorInpatient) +# if (denominatorType == ""persons"") { +# data$Prevalence <- data$personCount/(data$persons / 1000) +# } else { +# data$Prevalence <- data$personCount/(data$days / 365.25 / 1000) +# } +# data$ageGroup <- factor(data$ageGroup, levels = c(""<2 years"",""2-11 years"",""12-18 years"")) +# ggplot2::ggplot(data, ggplot2::aes(x = ageGroup, y = Prevalence, group = db, color = db, fill = db)) + +# ggplot2::geom_bar(stat = ""identity"") + +# ggplot2::theme(axis.text.x = ggplot2::element_text(angle=-90), +# strip.text.x = ggplot2::element_text(angle=-90)) +# ggplot2::ggsave(file.path(antibioticsFolder, ""Figure1a.png""), width = 9, height = 7, dpi= 200) +# +# numeratorNotInpatient <- numerator[numerator$inpatient == 0,] +# data <- merge(denominator, numeratorNotInpatient) +# if (denominatorType == ""persons"") { +# data$Prevalence <- data$personCount/(data$persons / 1000) +# } else { +# data$Prevalence <- data$personCount/(data$days / 365.25 / 1000) +# } +# data$ageGroup <- factor(data$ageGroup, levels = c(""<2 years"",""2-11 years"",""12-18 years"")) +# ggplot2::ggplot(data, ggplot2::aes(x = ageGroup, y = Prevalence, group = db, color = db, fill = db)) + +# ggplot2::geom_bar(stat = ""identity"") + +# ggplot2::theme(axis.text.x = ggplot2::element_text(angle=-90), +# strip.text.x = ggplot2::element_text(angle=-90)) +# ggplot2::ggsave(file.path(antibioticsFolder, ""Figure1b.png""), width = 9, height = 7, dpi= 200) +# +# +# ### Combine figures 2a and 2b across DBs ### +# denominator <- data.frame() +# numerator <- data.frame() +# for (i in 1:nrow(dbs)) { +# dbFolder <- file.path(folder, dbs$name[i]) +# dbDenominator <- read.csv(file.path(dbFolder, ""DenominatorByGender.csv""), stringsAsFactors = FALSE) +# dbNumerator <- read.csv(file.path(dbFolder, ""NumeratorByGenderByClass.csv""), stringsAsFactors = FALSE) +# dbNumerator <- dbNumerator[dbNumerator$conceptName %in% classes, ] +# dbDenominator$db <- dbs$name[i] +# dbNumerator$db <- dbs$name[i] +# if (!dbs$inpatient[i]) { +# dbNumerator <- dbNumerator[dbNumerator$inpatient == 0,] +# } +# if (!dbs$ambulatory[i]) { +# dbNumerator <- dbNumerator[dbNumerator$inpatient == 1,] +# } +# denominator <- rbind(denominator, dbDenominator) +# numerator <- rbind(numerator, dbNumerator) +# } +# numeratorInpatient <- numerator[numerator$inpatient == 1,] +# +# data <- merge(denominator, numeratorInpatient) +# if (denominatorType == ""persons"") { +# data$Prevalence <- data$personCount/(data$persons / 1000) +# } else { +# data$Prevalence <- data$personCount/(data$days / 365.25 / 1000) +# } +# data$Gender <- ""Male"" +# data$Gender[data$genderConceptId == 8532] <- ""Female"" +# ggplot2::ggplot(data, ggplot2::aes(x = Gender, y = Prevalence, group = db, color = db, fill = db)) + +# ggplot2::geom_bar(stat = ""identity"") + +# ggplot2::theme(axis.text.x = ggplot2::element_text(angle=-90), +# strip.text.x = ggplot2::element_text(angle=-90)) +# ggplot2::ggsave(file.path(antibioticsFolder, ""Figure2a.png""), width = 9, height = 9, dpi= 200) +# +# numeratorNotInpatient <- numerator[numerator$inpatient == 0,] +# data <- merge(denominator, numeratorNotInpatient) +# if (denominatorType == ""persons"") { +# data$Prevalence <- data$personCount/(data$persons / 1000) +# } else { +# data$Prevalence <- data$personCount/(data$days / 365.25 / 1000) +# } +# data$Gender <- ""Male"" +# data$Gender[data$genderConceptId == 8532] <- ""Female"" +# ggplot2::ggplot(data, ggplot2::aes(x = Gender, y = Prevalence, group = db, color = db, fill = db)) + +# ggplot2::geom_bar(stat = ""identity"") + +# ggplot2::theme(axis.text.x = ggplot2::element_text(angle=-90), +# strip.text.x = ggplot2::element_text(angle=-90)) +# ggplot2::ggsave(file.path(antibioticsFolder, ""Figure2b.png""), width = 9, height = 9, dpi= 200) + + +### Combine figures 3a and 3b across DBs ### +denominator <- data.frame() +numerator <- data.frame() +for (i in 1:nrow(dbs)) { + dbFolder <- file.path(folder, dbs$name[i]) + dbDenominator <- read.csv(file.path(dbFolder, ""DenominatorByAgeGroupByYear.csv""), stringsAsFactors = FALSE) + dbNumerator <- read.csv(file.path(dbFolder, ""NumeratorByAgeGroupByYearByClass.csv""), stringsAsFactors = FALSE) + dbNumerator <- dbNumerator[dbNumerator$conceptName %in% classes, ] + dbDenominator$db <- dbs$name[i] + dbNumerator$db <- dbs$name[i] + dbDenominator <- dbDenominator[dbDenominator$calendarYear >= 2008 & dbDenominator$calendarYear <= 2013,] + dbNumerator <- dbNumerator[dbNumerator$calendarYear >= 2008 & dbNumerator$calendarYear <= 2013,] + if (!dbs$inpatient[i]) { + dbNumerator <- dbNumerator[dbNumerator$inpatient == 0,] + } + if (!dbs$ambulatory[i]) { + dbNumerator <- dbNumerator[dbNumerator$inpatient == 1,] + } + denominator <- rbind(denominator, dbDenominator) + numerator <- rbind(numerator, dbNumerator) +} +numeratorInpatient <- numerator[numerator$inpatient == 1,] +data <- merge(denominator, numeratorInpatient) +if (denominatorType == ""persons"") { + data$Prevalence <- data$personCount/(data$persons / 1000) +} else { + data$Prevalence <- data$personCount/(data$days / 365.25 / 1000) +} +data$ageGroup <- factor(data$ageGroup, levels = c(""<2 years"",""2-11 years"",""12-18 years"")) +ggplot2::ggplot(data, ggplot2::aes(x = calendarYear, y = Prevalence, group = db, color = db)) + + ggplot2::geom_line() + + ggplot2::facet_grid( ~ ageGroup, scales = ""free"") + + ggplot2::theme(axis.text.x = ggplot2::element_text(angle=-90), + strip.text.y = ggplot2::element_text(angle=0)) +ggplot2::ggsave(file.path(antibioticsFolder, ""Figure3a.png""), width = 12, height = 8, dpi= 200) + +numeratorNotInpatient <- numerator[numerator$inpatient == 0,] +data <- merge(denominator, numeratorNotInpatient) +if (denominatorType == ""persons"") { + data$Prevalence <- data$personCount/(data$persons / 1000) +} else { + data$Prevalence <- data$personCount/(data$days / 365.25 / 1000) +} +data$ageGroup <- factor(data$ageGroup, levels = c(""<2 years"",""2-11 years"",""12-18 years"")) +ggplot2::ggplot(data, ggplot2::aes(x = calendarYear, y = Prevalence, group = db, color = db)) + + ggplot2::geom_line() + + ggplot2::facet_grid( ~ ageGroup, scales = ""free"") + + ggplot2::theme(axis.text.x = ggplot2::element_text(angle=-90), + strip.text.y = ggplot2::element_text(angle=0)) +ggplot2::ggsave(file.path(antibioticsFolder, ""Figure3b.png""), width = 12, height = 8, dpi= 200) + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iAcutePancreatitis/R/CountCohorts.R",".R","1659","33","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# 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. + +countCohorts <- function(connection, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable = ""cohort"", + oracleTempSchema, + outputFolder) { + sql <- SqlRender::loadRenderTranslateSql(""GetCounts.sql"", + ""AHAsAcutePancreatitis"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + work_database_schema = cohortDatabaseSchema, + study_cohort_table = cohortTable) + counts <- DatabaseConnector::querySql(connection, sql) + colnames(counts) <- SqlRender::snakeCaseToCamelCase(colnames(counts)) + counts <- addCohortNames(counts) + write.csv(counts, file.path(outputFolder, ""CohortCounts.csv""), row.names = FALSE) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iAcutePancreatitis/R/Main.R",".R","7833","146","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# 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. + +#' Execute AHAsAcutePancreatitis Study +#' +#' @details +#' This function executes the AHAsAcutePancreatitis Study. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param cohortDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param cohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/). Do not use a folder on a network drive since this greatly impacts +#' performance. +#' @param createCohorts Create the cohortTable table with the exposure and outcome cohorts? +#' @param runAnalyses Perform the cohort method analyses? +#' @param getPriorExposureData Get data on prior exposure to AHAs? +#' @param runDiagnostics Should study diagnostics be generated? +#' @param prepareResults Prepare results for analysis? +#' @param maxCores How many parallel cores should be used? If more cores are made available +#' this can speed up the analyses. +#' +#' @examples +#' \dontrun{ +#' connectionDetails <- createConnectionDetails(dbms = ""postgresql"", +#' user = ""joe"", +#' password = ""secret"", +#' server = ""myserver"") +#' +#' execute(connectionDetails, +#' cdmDatabaseSchema = ""cdm_data"", +#' cohortDatabaseSchema = ""results"", +#' cohortTable = ""cohort"", +#' oracleTempSchema = NULL, +#' outputFolder = ""c:/temp/study_results"", +#' maxCores = 4) +#' } +#' +#' @export +execute <- function(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema = cdmDatabaseSchema, + cohortTable = ""cohort"", + oracleTempSchema = cohortDatabaseSchema, + outputFolder, + databaseName, + createCohorts = TRUE, + runAnalyses = TRUE, + getPriorExposureData = TRUE, + runDiagnostics = TRUE, + prepareResults = TRUE, + maxCores = maxCores) { + if (!file.exists(outputFolder)) + dir.create(outputFolder, recursive = TRUE) + + # prevent multiple logging of the same output across executions + OhdsiRTools::clearLoggers() + OhdsiRTools::addDefaultFileLogger(file.path(outputFolder, ""log.txt"")) + + if (createCohorts) { + OhdsiRTools::logInfo(""Creating exposure and outcome cohorts"") + createCohorts(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder) + } + + if (runAnalyses) { + OhdsiRTools::logInfo(""Running analyses"") + cmOutputFolder <- file.path(outputFolder, ""cmOutput"") + if (!file.exists(cmOutputFolder)) + dir.create(cmOutputFolder) + cmAnalysisListFile <- system.file(""settings"", + ""cmAnalysisList.json"", + package = ""AHAsAcutePancreatitis"") + cmAnalysisList <- CohortMethod::loadCmAnalysisList(cmAnalysisListFile) + cmAnalysisList <- setOutcomeDatabaseSchemaAndTable(cmAnalysisList, cohortDatabaseSchema, cohortTable) + dcosList <- createTcos(outputFolder = outputFolder) + results <- CohortMethod::runCmAnalyses(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + exposureDatabaseSchema = cohortDatabaseSchema, + exposureTable = cohortTable, + outcomeDatabaseSchema = cohortDatabaseSchema, + outcomeTable = cohortTable, + outputFolder = cmOutputFolder, + oracleTempSchema = oracleTempSchema, + cmAnalysisList = cmAnalysisList, + drugComparatorOutcomesList = dcosList, + getDbCohortMethodDataThreads = min(3, maxCores), + createStudyPopThreads = min(3, maxCores), + createPsThreads = max(1, round(maxCores/10)), + psCvThreads = min(10, maxCores), + computeCovarBalThreads = min(3, maxCores), + trimMatchStratifyThreads = min(10, maxCores), + fitOutcomeModelThreads = max(1, round(maxCores/4)), + outcomeCvThreads = min(4, maxCores), + refitPsForEveryOutcome = FALSE, + refitPsForEveryStudyPopulation = FALSE, + outcomeIdsOfInterest = c(6479)) + } + if (getPriorExposureData) { + OhdsiRTools::logInfo(""Getting prior AHA exposure data from server"") + getPriorAhaExposureData(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder) + } + if (runDiagnostics) { + OhdsiRTools::logInfo(""Running diagnostics"") + generateDiagnostics(outputFolder = outputFolder) + } + if (prepareResults) { + OhdsiRTools::logInfo(""Preparing results for analysis"") + prepareResultsForAnalysis(outputFolder = outputFolder, + databaseName = databaseName, + maxCores = maxCores) + } + invisible(NULL) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iAcutePancreatitis/R/PriorOutcomeCovariateBuilder.R",".R","6131","120","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# 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. + + +#' Create settings for adding prior outcomes as covariates +#' +#' @param outcomeDatabaseSchema The name of the database schema that is the location +#' where the data used to define the outcome cohorts is +#' available. +#' @param outcomeTable The tablename that contains the outcome cohorts. +#' @param outcomeIds A vector of cohort_definition_ids used to define outcomes +#' @param outcomeNames A vector of names of the outcomes, to be used to create +#' covariate names. +#' @param windowStart Start day of the window where covariates are captured, +#' relative to the index date (0 = index date). +#' @param windowEnd End day of the window where covariates are captured, +#' relative to the index date (0 = index date). +#' +#' @return +#' A covariateSettings object. +#' +#' @export +createPriorOutcomesCovariateSettings <- function(outcomeDatabaseSchema = ""unknown"", + outcomeTable = ""unknown"", + outcomeIds, + outcomeNames, + windowStart = -365, + windowEnd = -1) { + covariateSettings <- list(outcomeDatabaseSchema = outcomeDatabaseSchema, + outcomeTable = outcomeTable, + outcomeIds = outcomeIds, + outcomeNames = outcomeNames, + windowStart = windowStart, + windowEnd = windowEnd) + attr(covariateSettings, ""fun"") <- ""AHAsAcutePancreatitis::getDbPriorOutcomesCovariateData"" + class(covariateSettings) <- ""covariateSettings"" + return(covariateSettings) +} + +#' @export +getDbPriorOutcomesCovariateData <- function(connection, + oracleTempSchema = NULL, + cdmDatabaseSchema, + cohortTable = ""#cohort_person"", + cohortId = -1, + cdmVersion = ""5"", + rowIdField = ""subject_id"", + covariateSettings, + aggregated = FALSE) { + if (aggregated) + stop(""Aggregation not supported"") + writeLines(""Creating covariates based on prior outcomes"") + sql <- SqlRender::loadRenderTranslateSql(""getPriorOutcomeCovariates.sql"", + packageName = ""AHAsAcutePancreatitis"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + window_start = covariateSettings$windowStart, + window_end = covariateSettings$windowEnd, + row_id_field = rowIdField, + cohort_temp_table = cohortTable, + cohort_id = cohortId, + outcome_database_schema = covariateSettings$outcomeDatabaseSchema, + outcome_table = covariateSettings$outcomeTable, + outcome_ids = covariateSettings$outcomeIds) + covariates <- DatabaseConnector::querySql.ffdf(connection, sql) + colnames(covariates) <- SqlRender::snakeCaseToCamelCase(colnames(covariates)) + covariateRef <- data.frame(covariateId = covariateSettings$outcomeIds * 1000 + 999, + covariateName = paste(""Prior outcome:"", covariateSettings$outcomeNames), + analysisId = 999, + conceptId = 0) + covariateRef <- ff::as.ffdf(covariateRef) + + # Construct analysis reference: + analysisRef <- data.frame(analysisId = as.numeric(1), + analysisName = ""Prior outcome"", + domainId = ""Cohort"", + startDay = as.numeric(covariateSettings$windowStart), + endDay = as.numeric(covariateSettings$windowEnd), + isBinary = ""Y"", + missingMeansZero = ""Y"") + analysisRef <- ff::as.ffdf(analysisRef) + # Construct analysis reference: + metaData <- list(sql = sql, call = match.call()) + result <- list(covariates = covariates, + covariateRef = covariateRef, + analysisRef = analysisRef, + metaData = metaData) + class(result) <- ""covariateData"" + return(result) +} + +#' @export +setOutcomeDatabaseSchemaAndTable <-function(settings, outcomeDatabaseSchema, outcomeTable) { + if (class(settings) == ""covariateSettings"") { + if (!is.null(settings$outcomeDatabaseSchema)) { + settings$outcomeDatabaseSchema <- outcomeDatabaseSchema + settings$outcomeTable <- outcomeTable + } + } else { + if (is.list(settings) && length(settings) != 0) { + for (i in 1:length(settings)) { + if (is.list(settings[[i]])) { + settings[[i]] <- setOutcomeDatabaseSchemaAndTable(settings[[i]], outcomeDatabaseSchema, outcomeTable) + } + } + } + } + return(settings) +}","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iAcutePancreatitis/R/GetPriorAhaExposureData.R",".R","4352","74","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# 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. + +#' Get data on prior exposure to AHAs. +#' +#' @details +#' Downloads data on prior exposure to anti-hyperglycemic agents for the cohorts of interest. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param cohortDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param cohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' +#' @export +getPriorAhaExposureData <- function(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable = ""cohort"", + oracleTempSchema, + outputFolder) { + if (!file.exists(outputFolder)) + dir.create(outputFolder, recursive = TRUE) + + conn <- DatabaseConnector::connect(connectionDetails) + + pathToCsv <- system.file(""settings"", ""TcosOfInterest.csv"", package = ""AHAsAcutePancreatitis"") + tcosOfInterest <- read.csv(pathToCsv, stringsAsFactors = FALSE) + sql <- SqlRender::loadRenderTranslateSql(""PriorAhaExposureCovariates.sql"", + ""AHAsAcutePancreatitis"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + cohort_database_schema = cohortDatabaseSchema, + cohort_table = cohortTable, + cohort_ids = unique(c(tcosOfInterest$targetId, + tcosOfInterest$comparatorId))) + covariates <- DatabaseConnector::querySql.ffdf(conn, sql) + colnames(covariates) <- SqlRender::snakeCaseToCamelCase(colnames(covariates)) + + sql <- SqlRender::loadRenderTranslateSql(""PriorAhaExposureCovariateRef.sql"", + ""AHAsAcutePancreatitis"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema) + covariateRef <- DatabaseConnector::querySql.ffdf(conn, sql) + colnames(covariateRef) <- SqlRender::snakeCaseToCamelCase(colnames(covariateRef)) + + DatabaseConnector::disconnect(conn) + + ffbase::save.ffdf(covariates, covariateRef, dir = file.path(outputFolder, ""priorAhaExposures"")) +}","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iAcutePancreatitis/R/CreateCohorts.R",".R","3574","69","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of AHAsAcutePancreatitis +# +# 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. + +.createCohorts <- function(connection, + cdmDatabaseSchema, + vocabularyDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable, + oracleTempSchema, + outputFolder) { + + # Create study cohort table structure: + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""CreateCohortTable.sql"", + packageName = ""AHAsAcutePancreatitis"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + cohort_database_schema = cohortDatabaseSchema, + cohort_table = cohortTable) + DatabaseConnector::executeSql(connection, sql, progressBar = FALSE, reportOverallTime = FALSE) + + + + # Instantiate cohorts: + pathToCsv <- system.file(""settings"", ""ConfigCohortsToCreate.csv"", package = ""AHAsAcutePancreatitis"") + cohortsToCreate <- read.csv(pathToCsv) + for (i in 1:nrow(cohortsToCreate)) { + writeLines(paste(""Creating cohort:"", cohortsToCreate$name[i])) + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = paste0(cohortsToCreate$name[i], "".sql""), + packageName = ""AHAsAcutePancreatitis"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + vocabulary_database_schema = vocabularyDatabaseSchema, + + target_database_schema = cohortDatabaseSchema, + target_cohort_table = cohortTable, + target_cohort_id = cohortsToCreate$cohortId[i]) + DatabaseConnector::executeSql(connection, sql) + } + + # Fetch cohort counts: + sql <- ""SELECT cohort_definition_id, COUNT(*) AS count FROM @cohort_database_schema.@cohort_table GROUP BY cohort_definition_id"" + sql <- SqlRender::renderSql(sql, + cohort_database_schema = cohortDatabaseSchema, + cohort_table = cohortTable)$sql + sql <- SqlRender::translateSql(sql, targetDialect = attr(connection, ""dbms""))$sql + counts <- DatabaseConnector::querySql(connection, sql) + names(counts) <- SqlRender::snakeCaseToCamelCase(names(counts)) + counts <- merge(counts, data.frame(cohortDefinitionId = cohortsToCreate$cohortId, + cohortName = cohortsToCreate$name)) + write.csv(counts, file.path(outputFolder, ""CohortCounts.csv"")) + + +} + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iAcutePancreatitis/R/PrepareResultsForAnalysis.R",".R","18414","448","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# 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. + +#' Prepare results for analysis +#' +#' @details +#' This function generates analyses results, and prepares data for the Shiny app. Requires the study to be executed first. +#' +#' @param outputFolder Name of local folder where the results were generated; make sure to use forward slashes +#' (/). Do not use a folder on a network drive since this greatly impacts +#' performance. +#' @param databaseName A unique name for the database. +#' @param maxCores How many parallel cores should be used? If more cores are made available +#' this can speed up the analyses. +#' +#' @export +prepareResultsForAnalysis <- + function(outputFolder, databaseName, maxCores) { + packageName <- ""AHAsAcutePancreatitis"" + cmOutputFolder <- file.path(outputFolder, ""cmOutput"") + + resultsFolder <- file.path(outputFolder, ""results"") + if (!file.exists(resultsFolder)) + dir.create(resultsFolder) + shinyDataFolder <- file.path(resultsFolder, ""shinyData"") + if (!file.exists(shinyDataFolder)) + dir.create(shinyDataFolder) + balanceDataFolder <- file.path(resultsFolder, ""balance"") + if (!file.exists(balanceDataFolder)) + dir.create(balanceDataFolder) + + pathToCsv <- + system.file(""settings"", ""TcosOfInterest.csv"", package = packageName) + tcosOfInterest <- read.csv(pathToCsv, stringsAsFactors = FALSE) + pathToCsv <- + system.file(""settings"", ""Analyses.csv"", package = packageName) + analyses <- read.csv(pathToCsv, stringsAsFactors = FALSE) + pathToCsv <- + system.file(""settings"", ""NegativeControls.csv"", package = packageName) + negativeControls <- + read.csv(pathToCsv, stringsAsFactors = FALSE) + + reference <- + readRDS(file.path(cmOutputFolder, ""outcomeModelReference.rds"")) + # file location remapping may not be necessary + # reference$cohortMethodDataFolder <- gsub(""^[a-z]:/"", ""r:/"", reference$cohortMethodDataFolder) + # reference$studyPopFile <- gsub(""^[a-z]:/"", ""r:/"", reference$studyPopFile) + # reference$sharedPsFile <- gsub(""^[a-z]:/"", ""r:/"", reference$sharedPsFile) + # reference$psFile <- gsub(""^[a-z]:/"", ""r:/"", reference$psFile) + # reference$strataFile <- gsub(""^[a-z]:/"", ""r:/"", reference$strataFile) + # reference$outcomeModelFile <- gsub(""^[a-z]:/"", ""r:/"", reference$outcomeModelFile) + + analysisSummary <- CohortMethod::summarizeAnalyses(reference) + saveRDS(analysisSummary, file.path(resultsFolder, ""analysisSummary.rds"")) + + analysisSummary <- merge(analysisSummary, analyses) + subset <- tcosOfInterest + subset$excludedCovariateConceptIds <- NULL + subset$outcomeIds <- NULL + subset$outcomeNames <- NULL + analysisSummary <- merge(analysisSummary, subset) + analysisSummary <- + merge(analysisSummary, negativeControls[, c(""outcomeId"", ""outcomeName"")], all.x = TRUE) + analysisSummary$type <- ""Outcome of interest"" + analysisSummary$type[analysisSummary$outcomeId %in% negativeControls$outcomeId] <- + ""Negative control"" + analysisSummary$database <- databaseName + + # Present analyses without censoring at switch as another time-at-risk + analysisSummary$timeAtRisk[!analysisSummary$censorAtSwitch] <- + paste(analysisSummary$timeAtRisk[!analysisSummary$censorAtSwitch], ""(no censor at switch)"") + analysisSummary <- + analysisSummary[!( + analysisSummary$timeAtRisk %in% c( + ""Intent to Treat (no censor at switch)"", + ""Modified ITT (no censor at switch)"" + ) + ), ] + analysisSummary$censorAtSwitch <- NULL + chunk <- + analysisSummary[analysisSummary$targetId == 2006492 & + analysisSummary$comparatorId == 2106493, ] + runTc <- + function(chunk, + tcosOfInterest, + negativeControls, + shinyDataFolder, + balanceDataFolder, + outputFolder, + databaseName, + reference) { + ffbase::load.ffdf(file.path(outputFolder, ""priorAhaExposures"")) + targetId <- chunk$targetId[1] + comparatorId <- chunk$comparatorId[1] + OhdsiRTools::logTrace(""Preparing results for target ID "", + targetId, + "", comparator ID"", + comparatorId) + idx <- + which( + tcosOfInterest$targetId == targetId & + tcosOfInterest$comparatorId == comparatorId + )[1] + outcomeIds <- as.character(tcosOfInterest$outcomeIds[idx]) + outcomeIds <- + as.numeric(strsplit(outcomeIds, split = "";"")[[1]]) + outcomeNames <- + as.character(tcosOfInterest$outcomeNames[idx]) + outcomeNames <- strsplit(outcomeNames, split = "";"")[[1]] + for (analysisId in unique(reference$analysisId)) { + OhdsiRTools::logTrace(""Analysis ID "", analysisId) + negControlSubset <- chunk[chunk$targetId == targetId & + chunk$comparatorId == comparatorId & + chunk$outcomeId %in% negativeControls$outcomeId & + chunk$analysisId == analysisId, ] + validNcs <- sum(!is.na(negControlSubset$seLogRr)) + if (validNcs >= 5) { + fileName <- + file.path( + shinyDataFolder, + paste0( + ""null_a"", + analysisId, + ""_t"", + targetId, + ""_c"", + comparatorId, + ""_"", + databaseName, + "".rds"" + ) + ) + if (file.exists(fileName)) { + null <- readRDS(fileName) + } else { + null <- + EmpiricalCalibration::fitMcmcNull(negControlSubset$logRr, negControlSubset$seLogRr) + saveRDS(null, fileName) + } + idx <- chunk$targetId == targetId & + chunk$comparatorId == comparatorId & + chunk$analysisId == analysisId + calibratedP <- EmpiricalCalibration::calibrateP( + null = null, + logRr = chunk$logRr[idx], + seLogRr = chunk$seLogRr[idx] + ) + chunk$calP[idx] <- calibratedP$p + chunk$calP_lb95ci[idx] <- calibratedP$lb95ci + chunk$calP_ub95ci[idx] <- calibratedP$ub95ci + } + + for (outcomeId in outcomeIds) { + OhdsiRTools::logTrace(""Outcome ID "", outcomeId) + outcomeName <- outcomeNames[outcomeIds == outcomeId] + idx <- chunk$targetId == targetId & + chunk$comparatorId == comparatorId & + chunk$outcomeId == outcomeId & + chunk$analysisId == analysisId + + # Compute MDRR + strataFile <- + reference$strataFile[reference$analysisId == analysisId & + reference$targetId == targetId & + reference$comparatorId == comparatorId & + reference$outcomeId == outcomeId] + population <- readRDS(strataFile) + mdrr <- + CohortMethod::computeMdrr( + population, + alpha = 0.05, + power = 0.8, + twoSided = TRUE, + modelType = ""cox"" + ) + chunk$mdrr[idx] <- mdrr$mdrr + chunk$outcomeName[idx] <- outcomeName + + # Compute time-at-risk distribtion stats + distTarget <- + quantile(population$timeAtRisk[population$treatment == 1], + c(0, 0.1, 0.25, 0.5, 0.75, 0.9, 1)) + distComparator <- + quantile(population$timeAtRisk[population$treatment == 0], + c(0, 0.1, 0.25, 0.5, 0.75, 0.9, 1)) + chunk$tarTargetMean[idx] <- + mean(population$timeAtRisk[population$treatment == 1]) + chunk$tarTargetSd[idx] <- + sd(population$timeAtRisk[population$treatment == 1]) + chunk$tarTargetMin[idx] <- distTarget[1] + chunk$tarTargetP10[idx] <- distTarget[2] + chunk$tarTargetP25[idx] <- distTarget[3] + chunk$tarTargetMedian[idx] <- distTarget[4] + chunk$tarTargetP75[idx] <- distTarget[5] + chunk$tarTargetP90[idx] <- distTarget[6] + chunk$tarTargetMax[idx] <- distTarget[7] + chunk$tarComparatorMean[idx] <- + mean(population$timeAtRisk[population$treatment == 0]) + chunk$tarComparatorSd[idx] <- + sd(population$timeAtRisk[population$treatment == 0]) + chunk$tarComparatorMin[idx] <- distComparator[1] + chunk$tarComparatorP10[idx] <- distComparator[2] + chunk$tarComparatorP25[idx] <- distComparator[3] + chunk$tarComparatorMedian[idx] <- distComparator[4] + chunk$tarComparatorP75[idx] <- distComparator[5] + chunk$tarComparatorP90[idx] <- distComparator[6] + chunk$tarComparatorMax[idx] <- distComparator[7] + + # Compute covariate balance + refRow <- reference[reference$analysisId == analysisId & + reference$targetId == targetId & + reference$comparatorId == comparatorId & + reference$outcomeId == outcomeId, ] + psAfterMatching <- readRDS(refRow$strataFile) + + if (nrow(psAfterMatching) == 0 | nrow(psAfterMatching[psAfterMatching$treatment==1,]) == 0 | nrow(psAfterMatching[psAfterMatching$treatment==0,]) == 0) { + OhdsiRTools::logTrace(paste(""Missing rows overall or in t/c: "", refRow$strataFile)) + next() + } + + cmData <- CohortMethod::loadCohortMethodData(refRow$cohortMethodDataFolder) + fileName <- + file.path( + balanceDataFolder, + paste0( + ""bal_a"", + analysisId, + ""_t"", + targetId, + ""_c"", + comparatorId, + ""_o"", + outcomeId, + ""_"", + databaseName, + "".rds"" + ) + ) + + print(paste(""checking file - "", fileName)) + if (!file.exists(fileName)) { + print(paste(""file does not exist computing balance - "", fileName)) + balance <- CohortMethod::computeCovariateBalance(psAfterMatching, cmData) + print(paste(""saving file - "", fileName)) + saveRDS(balance, fileName) + } else { + print(paste(""file exists - "", fileName)) + } + + # Compute balance for prior AHA exposure covariates + fileName <- + file.path( + shinyDataFolder, + paste0( + ""ahaBal_a"", + analysisId, + ""_t"", + targetId, + ""_c"", + comparatorId, + ""_o"", + outcomeId, + ""_"", + databaseName, + "".rds"" + ) + ) + if (!file.exists(fileName)) { + dummyCmData <- cmData + dummyCmData$covariates <- merge(covariates, + ff::as.ffdf(cmData$cohorts[, c(""rowId"", ""subjectId"", ""cohortStartDate"")])) + dummyCmData$covariateRef <- covariateRef + balance <- + CohortMethod::computeCovariateBalance(psAfterMatching, dummyCmData) + balance$conceptId <- NULL + balance$beforeMatchingSd <- NULL + balance$afterMatchingSd <- NULL + balance$beforeMatchingSumTreated <- NULL + balance$beforeMatchingSumComparator <- NULL + balance$afterMatchingSumTreated <- NULL + balance$afterMatchingSumComparator <- NULL + if (nrow(balance) > 0) + balance$analysisId <- as.integer(balance$analysisId) + saveRDS(balance, fileName) + } + + # Create KM plot + fileName <- + file.path( + shinyDataFolder, + paste0( + ""km_a"", + analysisId, + ""_t"", + targetId, + ""_c"", + comparatorId, + ""_o"", + outcomeId, + ""_"", + databaseName, + "".rds"" + ) + ) + + # added outcomeCount > 0 filter because of error in generating kmPlot for small data sets with no outcomes. + if (!file.exists(fileName) & sum(psAfterMatching$outcomeCount) > 0) { + plot <- plotKaplanMeier(psAfterMatching) + saveRDS(plot, fileName) + } + + # Add cohort sizes before matching/stratification + chunk$treatedBefore[idx] <- + sum(cmData$cohorts$treatment == 1) + chunk$comparatorBefore[idx] <- + sum(cmData$cohorts$treatment == 0) + } + fileName <- + file.path( + shinyDataFolder, + paste0( + ""ps_a"", + analysisId, + ""_t"", + targetId, + ""_c"", + comparatorId, + ""_"", + databaseName, + "".rds"" + ) + ) + if (!file.exists(fileName)) { + exampleRef <- reference[reference$analysisId == analysisId & + reference$targetId == targetId & + reference$comparatorId == comparatorId & + reference$outcomeId == outcomeIds[1], ] + ps <- readRDS(exampleRef$sharedPsFile) + if (nrow(ps) > 10 & nrow(ps[ps$treatment==1,]) > 10 & nrow(ps[ps$treatment==0,]) > 10) { + preparedPsPlot <- EvidenceSynthesis::preparePsPlot(ps) + saveRDS(preparedPsPlot, fileName) + } else { + OhdsiRTools::logTrace(paste( + ""Skipping Evidence Synthesis - Insufficient rows in ps / treatment or comparator: "", + exampleRef$sharedPsFile + )) + } + } + } + OhdsiRTools::logDebug(""Finished chunk with "", nrow(chunk), "" rows"") + return(chunk) + } + # OhdsiRTools::addDefaultFileLogger(""s:/temp/log.log"") + cluster <- OhdsiRTools::makeCluster(min(maxCores, 10)) + comparison <- + paste(analysisSummary$targetId, analysisSummary$comparatorId) + chunks <- split(analysisSummary, comparison) + analysisSummaries <- OhdsiRTools::clusterApply( + cluster = cluster, + x = chunks, + fun = runTc, + tcosOfInterest = tcosOfInterest, + negativeControls = negativeControls, + shinyDataFolder = shinyDataFolder, + balanceDataFolder = balanceDataFolder, + outputFolder = outputFolder, + databaseName = databaseName, + reference = reference + ) + OhdsiRTools::stopCluster(cluster) + analysisSummary <- do.call(plyr::rbind.fill, analysisSummaries) + + fileName <- + file.path(resultsFolder, paste0(""results_"", databaseName, "".csv"")) + write.csv(analysisSummary, fileName, row.names = FALSE) + + hois <- + analysisSummary[analysisSummary$type == ""Outcome of interest"", ] + fileName <- + file.path(shinyDataFolder, + paste0(""resultsHois_"", databaseName, "".rds"")) + saveRDS(hois, fileName) + + ncs <- + analysisSummary[analysisSummary$type == ""Negative control"", c( + ""targetId"", + ""comparatorId"", + ""outcomeId"", + ""analysisId"", + ""database"", + ""logRr"", + ""seLogRr"" + )] + fileName <- + file.path(shinyDataFolder, + paste0(""resultsNcs_"", databaseName, "".rds"")) + saveRDS(ncs, fileName) + + OhdsiRTools::logInfo(""Minimizing balance files for Shiny app"") + allCovarNames <- data.frame() + balanceFiles <- list.files(balanceDataFolder, ""bal.*.rds"") + pb <- txtProgressBar(style = 3) + for (i in 1:length(balanceFiles)) { + fileName <- balanceFiles[i] + balance <- readRDS(file.path(balanceDataFolder, fileName)) + idx <- !(balance$covariateId %in% allCovarNames$covariateId) + if (any(idx)) { + allCovarNames <- + rbind(allCovarNames, balance[idx, c(""covariateId"", ""covariateName"")]) + } + balance$covariateName <- NULL + balance$conceptId <- NULL + balance$beforeMatchingSd <- NULL + balance$afterMatchingSd <- NULL + balance$beforeMatchingSumTreated <- NULL + balance$beforeMatchingSumComparator <- NULL + balance$afterMatchingSumTreated <- NULL + balance$afterMatchingSumComparator <- NULL + balance$analysisId <- as.integer(balance$analysisId) + saveRDS(balance, file.path(shinyDataFolder, fileName)) + if (i %% 100 == 0) { + setTxtProgressBar(pb, i / length(balanceFiles)) + } + } + setTxtProgressBar(pb, 1) + close(pb) + fileName <- + file.path(shinyDataFolder, + paste0(""covarNames_"", databaseName, "".rds"")) + saveRDS(allCovarNames, fileName) + } + +# files <- list.files(shinyDataFolder, ""ahaBal_a.*.rds"", full.names = TRUE) +# targetFiles <- gsub(shinyDataFolder, balanceDataFolder, sourceFiles) +# file.rename(sourceFiles, targetFiles) +# unlink(files) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iAcutePancreatitis/R/CreateAllCohorts.R",".R","5717","109","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# 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. + +#' Create the exposure and outcome cohorts +#' +#' @details +#' This function will create the exposure and outcome cohorts following the definitions included in +#' this package. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param cohortDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param cohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' +#' @export +createCohorts <- function(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable = ""cohort"", + oracleTempSchema, + outputFolder) { + if (!file.exists(outputFolder)) + dir.create(outputFolder, recursive = TRUE) + + conn <- DatabaseConnector::connect(connectionDetails) + + .createCohorts(connection = conn, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder) + + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""AHAsAcutePancreatitis"") + negativeControls <- read.csv(pathToCsv) + + OhdsiRTools::logInfo(""Creating negative control outcome cohorts"") + negativeControlOutcomes <- negativeControls[negativeControls$type == ""Outcome"", ] + sql <- SqlRender::loadRenderTranslateSql(""NegativeControlOutcomes.sql"", + ""AHAsAcutePancreatitis"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = cohortDatabaseSchema, + target_cohort_table = cohortTable, + outcome_ids = negativeControlOutcomes$outcomeId) + DatabaseConnector::executeSql(conn, sql) + + # Check number of subjects per cohort: + OhdsiRTools::logInfo(""Counting cohorts"") + countCohorts(connection = conn, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder) + DatabaseConnector::disconnect(conn) +} + +addCohortNames <- function(data, IdColumnName = ""cohortDefinitionId"", nameColumnName = ""cohortName"") { + pathToCsv <- system.file(""settings"", ""CohortsToCreate.csv"", package = ""AHAsAcutePancreatitis"") + cohortsToCreate <- read.csv(pathToCsv) + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""AHAsAcutePancreatitis"") + negativeControls <- read.csv(pathToCsv) + + idToName <- data.frame(cohortId = c(cohortsToCreate$cohortId, + negativeControls$targetId, + negativeControls$comparatorId, + negativeControls$outcomeId), + cohortName = c(as.character(cohortsToCreate$name), + as.character(negativeControls$targetName), + as.character(negativeControls$comparatorName), + as.character(negativeControls$outcomeName))) + idToName <- idToName[order(idToName$cohortId), ] + idToName <- idToName[!duplicated(idToName$cohortId), ] + names(idToName)[1] <- IdColumnName + names(idToName)[2] <- nameColumnName + data <- merge(data, idToName, all.x = TRUE) + # Change order of columns: + idCol <- which(colnames(data) == IdColumnName) + if (idCol < ncol(data) - 1) { + data <- data[, c(1:idCol, ncol(data) , (idCol+1):(ncol(data)-1))] + } + return(data) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iAcutePancreatitis/R/GenerateAppendix.R",".R","19195","388","# # studyFolder <- ""D:/Studies/EPI534"" +# # appendixFolder <- file.path(studyFolder, ""report"", ""appendix"") +# # shinyDataFolder <- file.path(getwd(), ""extras"", ""EvidenceExplorer"", ""data"") +# # tempFolder <- ""D:/FFTemp"" +# # +# # if (!file.exists(tempFolder)) +# # dir.create(tempFolder) +# # if (!file.exists(appendixFolder)) +# # dir.create(appendixFolder) +# # +# # OhdsiRTools::addDefaultFileLogger(file.path(appendixFolder, ""log.txt"")) +# # wd <- setwd(""extras/EvidenceExplorer"") +# # source(""global.R"") +# # setwd(wd) +# # +# # # Appendix A ----------------------------------------------------------------------------------- +# # convertToPdf <- function(appendixFolder, rmdFile) { +# # wd <- setwd(appendixFolder) +# # pdfFile <- gsub("".Rmd$"", "".pdf"", rmdFile) +# # on.exit(setwd(wd)) +# # rmarkdown::render(rmdFile, +# # output_file = pdfFile, +# # rmarkdown::pdf_document(latex_engine = ""pdflatex"")) +# # } +# # +# # +# # # YOU ARE HERE - MUST CONVERT FROM HERE DOWN :) +# mainColumns <- c(""timeAtRisk"", +# ""eventType"", +# ""psStrategy"", +# ""database"", +# ""noCana"", +# ""noCensor"", +# ""priorAP"", +# ""metforminAddOn"", +# ""rr"", +# ""ci95lb"", +# ""ci95ub"", +# ""p"", +# ""calP"") +# +# mainColumnNames <- c(""Time at Risk"", +# ""Event Type"", +# ""Propensity Score Strategy"", +# ""Database"", +# ""Cana"", +# ""Censoring"", +# ""Prior AP"", +# ""Metformin Add On"", +# ""CI95 LB"", +# ""CI95 UB"", +# ""P"", +# ""Cal. P"" +# ) +# +# template <- SqlRender::readSql(""extras/AllResultsToPdf/hazardRatioTableTemplate.rmd"") +# # +# # +# # comparison <- comparisons[1] +# # outcome <- outcomes[1] +# # database <- dbs[1] +# # aNumber <- 1 +# # bNumber <- 1 +# # aAppendices <- data.frame() +# # bAppendices <- data.frame() +# # for (comparison in comparisons) { +# # for (outcome in outcomes) { +# # table <- resultsHois[resultsHois$comparison == comparison & resultsHois$outcomeName == outcome, mainColumns] +# # table$dbOrder <- match(table$database, c(""CCAE"", ""MDCD"",""MDCR"", ""Optum"", ""Meta-analysis (HKSJ)"", ""Meta-analysis (DL)"")) +# # table$timeAtRiskOrder <- match(table$timeAtRisk, c(""On Treatment"", +# # ""On Treatment (no censor at switch)"", +# # ""Lag"", +# # ""Lag (no censor at switch)"", +# # ""Intent to Treat"", +# # ""Modified ITT"")) +# # table <- table[order(table$establishedCvd, +# # table$priorExposure, +# # table$timeAtRiskOrder, +# # table$evenType, +# # table$psStrategy, +# # table$dbOrder), ] +# # table$dbOrder <- NULL +# # table$timeAtRiskOrder <- NULL +# # +# # table$rr[table$rr > 100] <- NA +# # table$ci95ub[table$ci95ub > 100] <- NA +# # table$rr <- sprintf(""%.2f (%.2f - %.2f)"", table$rr, table$ci95lb, table$ci95ub) +# # table$ci95lb <- NULL +# # table$ci95ub <- NULL +# # # table$rr <- formatC(table$rr, digits = 2, format = ""f"") +# # # table$rr <- gsub(""NA"", """", table$rr) +# # # table$ci95lb <- formatC(table$ci95lb, digits = 2, format = ""f"") +# # # table$ci95lb <- gsub(""NA"", """", table$ci95lb) +# # # table$ci95ub <- formatC(table$ci95ub, digits = 2, format = ""f"") +# # # table$ci95ub <- gsub(""NA"", """", table$ci95ub) +# # table$p <- formatC(table$p, digits = 2, format = ""f"") +# # table$p <- gsub(""NA"", """", table$p) +# # table$calP <- formatC(table$calP, digits = 2, format = ""f"") +# # table$calP <- gsub(""NA"", """", table$calP) +# # table$timeAtRisk[table$timeAtRisk == ""Intent to Treat""] <- ""ITT"" +# # table$evenType <- gsub(""First"", ""1st"", table$evenType) +# # table$priorExposure <- gsub(""at least 1"", "">= 1"", table$priorExposure) +# # table$priorExposure <- gsub(""exposure$"", """", table$priorExposure) +# # table$appendix <- sprintf(""B%05d"", bNumber:(bNumber + nrow(table) - 1)) +# # bAppendices <- rbind(bAppendices, data.frame(targetId = table$targetId, +# # comparatorId = table$comparatorId, +# # outcomeId = table$outcomeId, +# # analysisId = table$analysisId, +# # database = table$database, +# # appendix = table$appendix)) +# # table$targetId <- NULL +# # table$comparatorId <- NULL +# # table$outcomeId <- NULL +# # table$analysisId <- NULL +# # colnames(table) <- mainColumnNames +# # # table <- table[1:100, ] +# # saveRDS(table, file.path(tempFolder, ""temp.rds"")) +# # +# # rmd <- template +# # rmd <- gsub(""%number%"", sprintf(""A%02d"", aNumber), rmd) +# # rmd <- gsub(""%comparison%"", comparison, rmd) +# # rmd <- gsub(""%outcome%"", outcome, rmd) +# # rmdFile <- sprintf(""AppendixA%02d.Rmd"", aNumber) +# # sink(file.path(appendixFolder, rmdFile)) +# # writeLines(rmd) +# # sink() +# # convertToPdf(appendixFolder, rmdFile) +# # +# # +# # aNumber <- aNumber + 1 +# # bNumber <- bNumber + nrow(table) +# # +# # # Cleanup +# # unlink(file.path(appendixFolder, rmdFile)) +# # unlink(list.files(tempFolder, pattern = ""^temp"")) +# # } +# # } +# # saveRDS(bAppendices, file.path(appendixFolder, ""bAppendices.rds"")) +# # +# # +# # # Appendix B ----------------------------------------------------------------------------- +# # bAppendices <- readRDS(file.path(appendixFolder, ""bAppendices.rds"")) +# # +# # i = 544 +# # i = 2 +# # # for (i in 1:nrow(bAppendices)) { +# # generateAppendixB <- function(i) { +# # pdfFile <- sprintf(""Appendix%s.pdf"", bAppendices$appendix[i]) +# # if (!file.exists(file.path(appendixFolder, pdfFile))) { +# # OhdsiRTools::logInfo(""Generating "", pdfFile) +# # +# # tempFolder <- paste0(""s:/temp/cana"",i) +# # dir.create(tempFolder) +# # +# # wd <- setwd(""extras/EvidenceExplorer"") +# # source(""Table1.R"") +# # setwd(wd) +# # +# # convertToPdf <- function(appendixFolder, rmdFile) { +# # wd <- setwd(appendixFolder) +# # pdfFile <- gsub("".Rmd$"", "".pdf"", rmdFile) +# # on.exit(setwd(wd)) +# # rmarkdown::render(rmdFile, +# # output_file = pdfFile, +# # rmarkdown::pdf_document(latex_engine = ""pdflatex"")) +# # } +# # +# # +# # row <- resultsHois[resultsHois$targetId == bAppendices$targetId[i] & +# # resultsHois$comparatorId == bAppendices$comparatorId[i] & +# # resultsHois$outcomeId == bAppendices$outcomeId[i] & +# # resultsHois$analysisId == bAppendices$analysisId[i] & +# # resultsHois$database == bAppendices$database[i], ] +# # isMetaAnalysis <- row$database == ""Meta-analysis (HKSJ)"" || row$database == ""Meta-analysis (DL)"" +# # +# # # Power table +# # powerColumns <- c(""treated"", +# # ""comparator"", +# # ""treatedDays"", +# # ""comparatorDays"", +# # ""eventsTreated"", +# # ""eventsComparator"", +# # ""irTreated"", +# # ""irComparator"", +# # ""mdrr"") +# # +# # powerColumnNames <- c(""Target"", +# # ""Comparator"", +# # ""Target"", +# # ""Comparator"", +# # ""Target"", +# # ""Comparator"", +# # ""Target"", +# # ""Comparator"", +# # ""MDRR"") +# # table <- row +# # table$irTreated <- formatC(1000 * table$eventsTreated / (table$treatedDays / 365.25), digits = 2, format = ""f"") +# # table$irComparator <- formatC(1000 * table$eventsComparator / (table$comparatorDays / 365.25), digits = 2, format = ""f"") +# # table$treated <- formatC(table$treated, big.mark = "","", format = ""d"") +# # table$comparator <- formatC(table$comparator, big.mark = "","", format = ""d"") +# # table$treatedDays <- formatC(table$treatedDays, big.mark = "","", format = ""d"") +# # table$comparatorDays <- formatC(table$comparatorDays, big.mark = "","", format = ""d"") +# # table$eventsTreated <- formatC(table$eventsTreated, big.mark = "","", format = ""d"") +# # table$eventsComparator <- formatC(table$eventsComparator, big.mark = "","", format = ""d"") +# # table$mdrr <- formatC(table$mdrr, digits = 2, format = ""f"") +# # if (table$database == ""Meta-analysis (HKSJ)"" || table$database == ""Meta-analysis (DL)"") { +# # table <- table[, c(powerColumns, ""i2"")] +# # colnames(table) <- c(powerColumnNames, ""I2"") +# # } else { +# # table <- table[, powerColumns] +# # colnames(table) <- powerColumnNames +# # } +# # saveRDS(table, file.path(tempFolder, ""tempPower.rds"")) +# # +# # # Follow-up table +# # if (!isMetaAnalysis) { +# # table <- data.frame(Cohort = c(""Target"", ""Comparator""), +# # Mean = formatC(c(row$tarTargetMean, row$tarComparatorMean), digits = 1, format = ""f""), +# # SD = formatC(c(row$tarTargetSd, row$tarComparatorSd), digits = 1, format = ""f""), +# # Min = formatC(c(row$tarTargetMin, row$tarComparatorMin), big.mark = "","", format = ""d""), +# # P10 = formatC(c(row$tarTargetP10, row$tarComparatorP10), big.mark = "","", format = ""d""), +# # P25 = formatC(c(row$tarTargetP25, row$tarComparatorP25), big.mark = "","", format = ""d""), +# # Median = formatC(c(row$tarTargetMedian, row$tarComparatorMedian), big.mark = "","", format = ""d""), +# # P75 = formatC(c(row$tarTargetP75, row$tarComparatorP75), big.mark = "","", format = ""d""), +# # P90 = formatC(c(row$tarTargetP90, row$tarComparatorP90), big.mark = "","", format = ""d""), +# # Max = formatC(c(row$tarTargetMax, row$tarComparatorMax), big.mark = "","", format = ""d"")) +# # saveRDS(table, file.path(tempFolder, ""tempTar.rds"")) +# # } +# # +# # # Population characteristics +# # if (!isMetaAnalysis) { +# # fileName <- paste0(""bal_a"",row$analysisId,""_t"",row$targetId,""_c"",row$comparatorId,""_o"",row$outcomeId,""_"",row$database,"".rds"") +# # bal <- readRDS(file.path(shinyDataFolder, fileName)) +# # bal$absBeforeMatchingStdDiff <- abs(bal$beforeMatchingStdDiff) +# # bal$absAfterMatchingStdDiff <- abs(bal$afterMatchingStdDiff) +# # bal <- merge(bal, covarNames) +# # fileName <- paste0(""ahaBal_a"",row$analysisId,""_t"",row$targetId,""_c"",row$comparatorId,""_o"",row$outcomeId,""_"",row$database,"".rds"") +# # priorAhaBalance <- readRDS(file.path(shinyDataFolder, fileName)) +# # bal$absBeforeMatchingStdDiff <- NULL +# # bal$absAfterMatchingStdDiff <- NULL +# # priorAhaBalance <- priorAhaBalance[, colnames(bal)] +# # bal <- rbind(bal, priorAhaBalance) +# # bal$covariateName <- gsub(""hospitalizations for heart failure .primary inpatient diagnosis.$"", ""Hospitalizations for heart failure"", bal$covariateName) +# # bal$covariateName <- gsub(""Below Knee Lower Extremity Amputation events$"", ""Below knee lower extremity amputation"", bal$covariateName) +# # bal$covariateName <- gsub(""Neurologic disorder associated with diabetes mellitus$"", ""Neurologic disorder associated with diabetes"", bal$covariateName) +# # bal$covariateName <- gsub(""PSYCHOSTIMULANTS, AGENTS USED FOR ADHD AND NOOTROPICS"", ""Psychostimulants, agents for adhd & nootropics"", bal$covariateName) +# # +# # # which(grepl(""AGENTS USED FOR ADHD"", bal$covariateName)) +# # +# # wd <- setwd(""extras/EvidenceExplorer"") +# # table <- prepareTable1(bal, +# # beforeTargetPopSize = row$treatedBefore, +# # beforeComparatorPopSize = row$comparatorBefore, +# # afterTargetPopSize = row$treated, +# # afterComparatorPopSize = row$comparator, +# # beforeLabel = paste(""Before"", tolower(row$psStrategy)), +# # afterLabel = paste(""After"", tolower(row$psStrategy))) +# # setwd(wd) +# # table <- cbind(apply(table, 2, function(x) gsub("" "", "" "", x))) +# # colnames(table) <- table[2, ] +# # table <- table[3:nrow(table), ] +# # saveRDS(table, file.path(tempFolder, ""tempPopChar.rds"")) +# # +# # fileName <- paste0(""ps_a"",row$analysisId,""_t"",row$targetId,""_c"",row$comparatorId,""_"",row$database,"".rds"") +# # data <- readRDS(file.path(shinyDataFolder, fileName)) +# # data$GROUP <- row$targetDrug +# # data$GROUP[data$treatment == 0] <- row$comparatorDrug +# # data$GROUP <- factor(data$GROUP, levels = c(row$targetDrug, +# # row$comparatorDrug)) +# # saveRDS(data, file.path(tempFolder, ""tempPs.rds"")) +# # } +# # +# # # Covariate balance +# # if (!isMetaAnalysis) { +# # fileName <- paste0(""bal_a"",row$analysisId,""_t"",row$targetId,""_c"",row$comparatorId,""_o"",row$outcomeId,""_"",row$database,"".rds"") +# # bal <- readRDS(file.path(shinyDataFolder, fileName)) +# # bal$absBeforeMatchingStdDiff <- abs(bal$beforeMatchingStdDiff) +# # bal$absAfterMatchingStdDiff <- abs(bal$afterMatchingStdDiff) +# # saveRDS(bal, file.path(tempFolder, ""tempBalance.rds"")) +# # } +# # +# # # Negative controls +# # ncs <- resultsNcs[resultsNcs$targetId == row$targetId & +# # resultsNcs$comparatorId == row$comparatorId & +# # resultsNcs$analysisId == row$analysisId & +# # resultsNcs$database == row$database, ] +# # saveRDS(ncs, file.path(tempFolder, ""tempNcs.rds"")) +# # +# # # Kaplan Meier +# # if (!isMetaAnalysis) { +# # fileName <- paste0(""km_a"",row$analysisId,""_t"",row$targetId,""_c"",row$comparatorId,""_o"",row$outcomeId,""_"",row$database,"".rds"") +# # plot <- readRDS(file.path(shinyDataFolder, fileName)) +# # saveRDS(plot, file.path(tempFolder, ""tempKm.rds"")) +# # } +# # +# # template <- SqlRender::readSql(""extras/AllResultsToPdf/detailsTemplate.rmd"") +# # rmd <- template +# # rmd <- gsub(""%tempFolder%"", tempFolder, rmd) +# # rmd <- gsub(""%number%"", bAppendices$appendix[i], rmd) +# # rmd <- gsub(""%comparison%"", row$comparison, rmd) +# # rmd <- gsub(""%outcome%"", row$outcomeName, rmd) +# # rmd <- gsub(""%target%"", row$targetDrug, rmd) +# # rmd <- gsub(""%comparator%"", row$comparatorDrug, rmd) +# # rmd <- gsub(""%psStrategy%"", row$psStrategy, rmd) +# # rmd <- gsub(""%logRr%"", if (is.na(row$logRr)) 999 else row$logRr, rmd) +# # rmd <- gsub(""%seLogRr%"", if (is.na(row$seLogRr)) 999 else row$seLogRr, rmd) +# # rmd <- gsub(""%cvd%"", row$establishedCvd, rmd) +# # rmd <- gsub(""%priorExposure%"", row$priorExposure, rmd) +# # rmd <- gsub(""%timeAtRisk%"", row$timeAtRisk, rmd) +# # rmd <- gsub(""%eventType%"", row$evenType, rmd) +# # rmd <- gsub(""%psStrategy%"", row$psStrategy, rmd) +# # rmd <- gsub(""%database%"", row$database, rmd) +# # rmd <- gsub(""%isMetaAnalysis%"", isMetaAnalysis, rmd) +# # +# # rmdFile <- sprintf(""Appendix%s.Rmd"", bAppendices$appendix[i]) +# # sink(file.path(appendixFolder, rmdFile)) +# # writeLines(rmd) +# # sink() +# # convertToPdf(appendixFolder, rmdFile) +# # +# # # Cleanup +# # unlink(file.path(appendixFolder, rmdFile)) +# # # unlink(list.files(tempFolder, pattern = ""^temp"")) +# # unlink(tempFolder, recursive = TRUE) +# # } +# # } +# # #bAppendices <- readRDS(file.path(appendixFolder, ""bAppendices.rds"")) +# # +# # +# # nThreads <- 15 +# # cluster <- OhdsiRTools::makeCluster(nThreads) +# # setGlobalVars <- function(i, bAppendices, resultsHois, resultsNcs, covarNames, appendixFolder, shinyDataFolder){ +# # bAppendices <<- bAppendices +# # resultsHois <<- resultsHois +# # resultsNcs <<- resultsNcs +# # covarNames <<- covarNames +# # appendixFolder <<- appendixFolder +# # shinyDataFolder <<- shinyDataFolder +# # } +# # dummy <- OhdsiRTools::clusterApply(cluster = cluster, +# # x = 1:nThreads, +# # fun = setGlobalVars, +# # bAppendices = bAppendices, +# # resultsHois = resultsHois, +# # resultsNcs = resultsNcs, +# # covarNames = covarNames, +# # appendixFolder = appendixFolder, +# # shinyDataFolder = shinyDataFolder) +# # n <- nrow(bAppendices) +# # # when running clusterApply, the context of a function (in this case the global environment) +# # # is also transmitted with every function call. Making sure it doesn't contain anything big: +# # bAppendices <- NULL +# # resultsHois <- NULL +# # resultsNcs <- NULL +# # covarNames <- NULL +# # appendixFolder <- NULL +# # heterogeneous <- NULL +# # dummy <- NULL +# # +# # dummy <- OhdsiRTools::clusterApply(cluster = cluster, +# # x = 1:n, +# # fun = generateAppendixB) +# # +# # OhdsiRTools::stopCluster(cluster) +# # +# # # Post processing using GhostScript ------------------------------------------------------------- +# # gsPath <- ""\""C:/Program Files/gs/gs9.23/bin/gswin64.exe\"""" +# # studyFolder <- ""r:/AhasHfBkleAmputation"" +# # appendixFolder <- file.path(studyFolder, ""report"", ""appendix"") +# # tempFolder <- file.path(appendixFolder, ""optimized"") +# # if (!file.exists(tempFolder)) +# # dir.create(tempFolder) +# # +# # fileName <- ""AppendixA01.pdf"" +# # fileName <- ""AppendixB00001.pdf"" +# # files <- list.files(appendixFolder, pattern = "".*\\.pdf"", recursive = FALSE) +# # +# # for (fileName in files) { +# # args <- ""-dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dFastWebView -sOutputFile=%s %s %s"" +# # command <- paste(gsPath, sprintf(args, file.path(tempFolder, fileName), file.path(appendixFolder, fileName), file.path(getwd(), ""extras/AllResultsToPdf/pdfmarks""))) +# # shell(command) +# # } +# # +# # unlink(file.path(appendixFolder, files)) +# # +# # file.rename(from = file.path(tempFolder, files), to = file.path(appendixFolder, files)) +# # +# # unlink(tempFolder, recursive = TRUE)","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iAcutePancreatitis/R/Diagnostics.R",".R","13299","215","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# 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. + +abbreviateLabel <- function(label) { + # label <- ""new users of any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA with established cardiovascular disease and at least 1 prior non-metformin AHA exposure in 365 days prior to first exposure of any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA "" + label <- gsub(""new users of "", """", label) + label <- gsub("" with established cardiovascular disease"", "" with CV"", label) + label <- gsub("" at least 1 prior non-metformin AHA exposure in 365 days prior to.*"", "" prior AHA"", label) + label <- gsub("" no prior non-metformin AHA exposure in 365 days prior to.*"", "" no prior AHA"", label) + label <- gsub(""any DPP-4 inhibitor, GLP-1 agonist, or other select AHA"", ""traditional AHAs"", label) + label <- gsub(""any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA"", ""traditional AHAs + insulin"", label) + label <- gsub("" exposure to"", """", label) + return(label) +} + +#' Generate diagnostics +#' +#' @details +#' This function generates analyses diagnostics. Requires the study to be executed first. +#' +#' @param outputFolder Name of local folder where the results were generated; make sure to use forward slashes +#' (/). Do not use a folder on a network drive since this greatly impacts +#' performance. +#' +#' @export +generateDiagnostics <- function(outputFolder) { + packageName <- ""AHAsAcutePancreatitis"" + modelType <- ""cox"" # For MDRR computation + psStrategy <- ""matching"" # For covariate balance labels + cmOutputFolder <- file.path(outputFolder, ""cmOutput"") + + diagnosticsFolder <- file.path(outputFolder, ""diagnostics"") + if (!file.exists(diagnosticsFolder)) + dir.create(diagnosticsFolder) + + pathToCsv <- system.file(""settings"", ""TcosOfInterest.csv"", package = packageName) + tcosOfInterest <- read.csv(pathToCsv, stringsAsFactors = FALSE) + + reference <- readRDS(file.path(cmOutputFolder, ""outcomeModelReference.rds"")) + analysisSummary <- CohortMethod::summarizeAnalyses(reference) + analysisSummary <- addCohortNames(analysisSummary, ""targetId"", ""targetName"") + analysisSummary <- addCohortNames(analysisSummary, ""comparatorId"", ""comparatorName"") + analysisSummary <- addCohortNames(analysisSummary, ""outcomeId"", ""outcomeName"") + cmAnalysisList <- CohortMethod::loadCmAnalysisList(system.file(""settings"", ""cmAnalysisList.json"", package = packageName)) + analyses <- data.frame(analysisId = unique(reference$analysisId), + analysisDescription = """", + stringsAsFactors = FALSE) + for (i in 1:length(cmAnalysisList)) { + analyses$analysisDescription[analyses$analysisId == cmAnalysisList[[i]]$analysisId] <- cmAnalysisList[[i]]$description + } + analysisSummary <- merge(analysisSummary, analyses) + negativeControls <- read.csv(system.file(""settings"", ""NegativeControls.csv"", package = packageName)) + tcsOfInterest <- unique(tcosOfInterest[, c(""targetId"", ""comparatorId"")]) + mdrrs <- data.frame() + models <- data.frame() + for (i in 1:nrow(tcsOfInterest)) { + targetId <- tcsOfInterest$targetId[i] + comparatorId <- tcsOfInterest$comparatorId[i] + idx <- which(tcosOfInterest$targetId == targetId & tcosOfInterest$comparatorId == comparatorId)[1] + targetLabel <- tcosOfInterest$targetName[idx] + comparatorLabel <- tcosOfInterest$comparatorName[idx] + outcomeIds <- as.character(tcosOfInterest$outcomeIds[idx]) + outcomeIds <- as.numeric(strsplit(outcomeIds, split = "";"")[[1]]) + outcomeNames <- as.character(tcosOfInterest$outcomeNames[idx]) + outcomeNames <- strsplit(outcomeNames, split = "";"")[[1]] + for (analysisId in unique(reference$analysisId)) { + analysisDescription <- analyses$analysisDescription[analyses$analysisId == analysisId] + negControlSubset <- analysisSummary[analysisSummary$targetId == targetId & + analysisSummary$comparatorId == comparatorId & + analysisSummary$outcomeId %in% negativeControls$outcomeId & + analysisSummary$analysisId == analysisId, ] + + # Outcome controls + label <- ""OutcomeControls"" + + validNcs <- sum(!is.na(negControlSubset$seLogRr)) + if (validNcs >= 5) { + null <- EmpiricalCalibration::fitMcmcNull(negControlSubset$logRr, negControlSubset$seLogRr) + + fileName <- file.path(diagnosticsFolder, paste0(""nullDistribution_a"", analysisId, ""_t"", targetId, ""_c"", comparatorId, ""_"", label, "".png"")) + plot <- EmpiricalCalibration::plotCalibrationEffect(logRrNegatives = negControlSubset$logRr, + seLogRrNegatives = negControlSubset$seLogRr, + null = null, + showCis = TRUE) + title <- paste(abbreviateLabel(targetLabel), abbreviateLabel(comparatorLabel), sep = "" vs.\n"") + plot <- plot + ggplot2::ggtitle(title) + plot <- plot + ggplot2::theme(plot.title = ggplot2::element_text(colour = ""#000000"", size = 10, hjust = 0.5)) + ggplot2::ggsave(fileName, plot, width = 6, height = 5, dpi = 400) + } else { + null <- NULL + } + # fileName <- file.path(diagnosticsFolder, paste0(""trueAndObs_a"", analysisId, ""_t"", targetId, ""_c"", comparatorId, ""_"", label, "".png"")) + # EmpiricalCalibration::plotTrueAndObserved(logRr = controlSubset$logRr, + # seLogRr = controlSubset$seLogRr, + # trueLogRr = log(controlSubset$targetEffectSize), + # fileName = fileName) + + for (outcomeId in outcomeIds) { + outcomeName <- outcomeNames[outcomeIds == outcomeId] + # Compute MDRR + strataFile <- reference$strataFile[reference$analysisId == analysisId & + reference$targetId == targetId & + reference$comparatorId == comparatorId & + reference$outcomeId == outcomeId] + population <- readRDS(strataFile) + mdrr <- CohortMethod::computeMdrr(population, alpha = 0.05, power = 0.8, twoSided = TRUE, modelType = modelType) + mdrr$targetId <- targetId + mdrr$targetName <- targetLabel + mdrr$comparatorId <- comparatorLabel + mdrr$comparatorName <- comparatorLabel + mdrr$outcomeId <- outcomeId + mdrr$outcomeName <- outcomeName + mdrr$analysisId <- mdrr$analysisId + mdrr$analysisDescription <- analysisDescription + mdrrs <- rbind(mdrrs, mdrr) + # fileName <- file.path(diagnosticsFolder, paste0(""attrition_a"",analysisId,""_t"",targetId,""_c"",comparatorId, ""_o"", outcomeId, "".png"")) + # CohortMethod::drawAttritionDiagram(population, treatmentLabel = targetLabel, comparatorLabel = comparatorLabel, fileName = fileName) + if (!is.null(null)) { + fileName <- file.path(diagnosticsFolder, paste0(""type1Error_a"",analysisId,""_t"",targetId,""_c"",comparatorId, ""_o"", outcomeId,""_"", label, "".png"")) + title <- paste0(abbreviateLabel(targetLabel), "" vs.\n"", abbreviateLabel(comparatorLabel), "" for\n"", outcomeName) + plot <- EmpiricalCalibration::plotExpectedType1Error(seLogRrPositives = mdrr$se, + null = null, + showCis = TRUE, + title = title, + fileName = fileName) + } + } + exampleRef <- reference[reference$analysisId == analysisId & + reference$targetId == targetId & + reference$comparatorId == comparatorId & + reference$outcomeId == outcomeIds[1], ] + + ps <- readRDS(exampleRef$sharedPsFile) + psAfterMatching <- readRDS(exampleRef$strataFile) + + cmData <- CohortMethod::loadCohortMethodData(exampleRef$cohortMethodDataFolder) + + fileName <- file.path(diagnosticsFolder, paste0(""psBefore"",psStrategy,""_a"",analysisId,""_t"",targetId,""_c"",comparatorId,"".png"")) + psPlot <- CohortMethod::plotPs(data = ps, + treatmentLabel = abbreviateLabel(targetLabel), + comparatorLabel = abbreviateLabel(comparatorLabel)) + psPlot <- psPlot + ggplot2::theme(legend.title = ggplot2::element_blank(), legend.position = ""top"", legend.direction = ""vertical"") + ggplot2::ggsave(fileName, psPlot, width = 3.5, height = 4, dpi = 400) + + fileName = file.path(diagnosticsFolder, paste(""followupDist_a"",analysisId,""_t"",targetId,""_c"",comparatorId, "".png"",sep="""")) + + + + plot <- CohortMethod::plotFollowUpDistribution(psAfterMatching, + targetLabel = abbreviateLabel(targetLabel), + comparatorLabel = abbreviateLabel(comparatorLabel), + title = NULL) + plot <- plot + ggplot2::theme(legend.title = ggplot2::element_blank(), legend.position = ""top"", legend.direction = ""vertical"") + ggplot2::ggsave(fileName, plot, width = 4, height = 3.5, dpi = 400) + + model <- CohortMethod::getPsModel(ps, cmData) + model$targetId <- targetId + model$targetName <- targetLabel + model$comparatorId <- comparatorLabel + model$comparatorName <- comparatorLabel + model$analysisId <- mdrr$analysisId + model$analysisDescription <- analysisDescription + models <- rbind(models, model) + + fileName = file.path(diagnosticsFolder, paste(""time_a"",analysisId,""_t"",targetId,""_c"",comparatorId, "".png"",sep="""")) + cohorts <- cmData$cohorts + cohorts$group <- abbreviateLabel(targetLabel) + cohorts$group[cohorts$treatment == 0] <- abbreviateLabel(comparatorLabel) + plot <- ggplot2::ggplot(cohorts, ggplot2::aes(x = cohortStartDate, color = group, fill = group, group = group)) + + ggplot2::geom_density(alpha = 0.5) + + ggplot2::xlab(""Cohort start date"") + + ggplot2::ylab(""Density"") + + ggplot2::theme(legend.title = ggplot2::element_blank(), + legend.position = ""top"", + legend.direction = ""vertical"") + ggplot2::ggsave(filename = fileName, plot = plot, width = 5, height = 3.5, dpi = 400) + + balance <- CohortMethod::computeCovariateBalance(psAfterMatching, cmData) + + fileName = file.path(diagnosticsFolder, paste(""balanceScatter_a"",analysisId,""_t"",targetId,""_c"",comparatorId,"".png"",sep="""")) + balanceScatterPlot <- CohortMethod::plotCovariateBalanceScatterPlot(balance = balance, + beforeLabel = paste(""Before"", psStrategy), + afterLabel = paste(""After"", psStrategy)) + title <- paste(abbreviateLabel(targetLabel), abbreviateLabel(comparatorLabel), sep = "" vs.\n"") + balanceScatterPlot <- balanceScatterPlot + ggplot2::ggtitle(title) + balanceScatterPlot <- balanceScatterPlot + ggplot2::theme(plot.title = ggplot2::element_text(colour = ""#000000"", size = 8, hjust = 0.5)) + ggplot2::ggsave(fileName, balanceScatterPlot, width = 4, height = 4.5, dpi = 400) + + fileName = file.path(diagnosticsFolder, paste(""balanceTop_a"",analysisId,""_t"",targetId,""_c"",comparatorId,"".png"",sep="""")) + balanceTopPlot <- CohortMethod::plotCovariateBalanceOfTopVariables(balance = balance, + beforeLabel = paste(""Before"", psStrategy), + afterLabel = paste(""After"", psStrategy)) + title <- paste(abbreviateLabel(targetLabel), abbreviateLabel(comparatorLabel), sep = "" vs.\n"") + balanceTopPlot <- balanceTopPlot + ggplot2::ggtitle(title) + balanceTopPlot <- balanceTopPlot + ggplot2::theme(plot.title = ggplot2::element_text(colour = ""#000000"", size = 9, hjust = 0.5)) + ggplot2::ggsave(fileName, balanceTopPlot, width = 10, height = 6.5, dpi = 400) + } + } + fileName <- file.path(diagnosticsFolder, paste0(""mdrr.csv"")) + write.csv(mdrrs, fileName, row.names = FALSE) + fileName <- file.path(diagnosticsFolder, paste0(""propensityModels.csv"")) + write.csv(models, fileName, row.names = FALSE) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iAcutePancreatitis/R/PerformMultiplicityAdjustment.R",".R","2388","60","# tcosFile <- system.file(""settings"", ""TcosOfInterest.csv"", package = ""AHAsAcutePancreatitis"") +# tcos <- read.csv(tcosFile, stringsAsFactors = FALSE) +# studyFolder <- ""S:/Studies/EPI534"" +# databases <- c(""optum"", ""mdcr"", ""ccae"") +# reportFolder = file.path(studyFolder, ""report"") +# +# cleanResults <- function(results) { +# #fix a typo +# results[results$eventType == ""First EVer Event"", ]$eventType <- +# ""First Ever Event"" +# #create additional filter variables +# results$noCana <- +# with(results, ifelse(grepl(""no cana"", comparatorName), TRUE, FALSE)) +# results$noCensor <- +# with(results, ifelse(grepl(""no censoring"", comparatorName), TRUE, FALSE)) +# #simplify naming +# results[results$timeAtRisk == ""Per Protocol Zero Day (no censor at switch)"", ]$timeAtRisk <- +# ""On Treatment (0 Day)"" +# results[results$timeAtRisk == ""On Treatment"", ]$timeAtRisk <- +# ""On Treatment (30 Day)"" +# results[results$timeAtRisk == ""On Treatment (no censor at switch)"", ]$timeAtRisk <- +# ""On Treatment (30 Day)"" +# results[results$timeAtRisk == ""Per Protocol Sixty Day (no censor at switch)"", ]$timeAtRisk <- +# ""On Treatment (60 Day)"" +# results[results$timeAtRisk == ""Per Protocol Zero Day"", ]$timeAtRisk <- +# ""On Treatment (0 Day)"" +# results[results$timeAtRisk == ""Per Protocol Sixty Day"", ]$timeAtRisk <- +# ""On Treatment (60 Day)"" +# return(results) +# } +# +# loadResultsHois <- function(outputFolder) { +# shinyDataFolder <- file.path(outputFolder, ""results"", ""shinyData"") +# file <- +# list.files(shinyDataFolder, +# pattern = ""resultsHois_.*.rds"", +# full.names = TRUE) +# x <- readRDS(file) +# return(x) +# } +# +# for (database in databases) { +# outputFolder <- file.path(studyFolder, database) +# results <- loadResultsHois(outputFolder) +# results <- cleanResults(results) +# +# # limit to primary analysis per specification +# primary <- results[ +# results$analysisId==2 & +# results$timeAtRisk==""On Treatment (30 Day)"" & +# !is.na(results$p) & +# results$canaRestricted == T & +# results$noCensor == F,] +# +# primary$hochbergP <- p.adjust(primary$p,method=""hochberg"") +# final <- primary[c(""comparatorDrug"", ""rr"", ""ci95lb"", ""ci95ub"", ""p"", ""hochbergP"")] +# write.table(final, file.path(reportFolder, paste0(""hochbergResult_"", database, "".csv"" )), row.names=F, sep="","") +# } +# +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iAcutePancreatitis/R/MetaAnalysis.R",".R","6224","154","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# 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. + +#' Create figures and tables for report +#' +#' @details +#' This function generates tables and figures for the report on the study results. +#' +#' @param outputFolders Vector of names of local folders where the results were generated; make sure +#' to use forward slashes (/). D +#' @param maOutputFolder A local folder where the meta-anlysis results will be written. +#' @param maxCores How many parallel cores should be used? If more cores are made available +#' this can speed up the analyses. +#' +#' @export +doMetaAnalysis <- function(outputFolders, maOutputFolder, maxCores) { + OhdsiRTools::logInfo(""Performing meta-analysis"") + resultsFolder <- file.path(maOutputFolder, ""results"") + if (!file.exists(resultsFolder)) + dir.create(resultsFolder, recursive = TRUE) + shinyDataFolder <- file.path(resultsFolder, ""shinyData"") + if (!file.exists(shinyDataFolder)) + dir.create(shinyDataFolder) + + loadResults <- function(outputFolder) { + files <- list.files(file.path(outputFolder, ""results""), pattern = ""results_.*.csv"", full.names = TRUE) + OhdsiRTools::logInfo(""Loading "", files[1], "" for meta-analysis"") + return(read.csv(files[1])) + } + allResults <- lapply(outputFolders, loadResults) + allResults <- do.call(rbind, allResults) + groups <- split(allResults, paste(allResults$targetId, allResults$comparatorId, allResults$analysisId)) + cluster <- OhdsiRTools::makeCluster(min(maxCores, 15)) + results <- OhdsiRTools::clusterApply(cluster, groups, computeGroupMetaAnalysis, shinyDataFolder = shinyDataFolder) + OhdsiRTools::stopCluster(cluster) + results <- do.call(rbind, results) + + fileName <- file.path(resultsFolder, paste0(""results_Meta-analysis.csv"")) + write.csv(results, fileName, row.names = FALSE) + + hois <- results[results$type == ""Outcome of interest"", ] + fileName <- file.path(shinyDataFolder, paste0(""resultsHois_Meta-analysis.rds"")) + saveRDS(hois, fileName) + + ncs <- results[results$type == ""Negative control"", c(""targetId"", ""comparatorId"", ""outcomeId"", ""analysisId"", ""database"", ""logRr"", ""seLogRr"")] + fileName <- file.path(shinyDataFolder, paste0(""resultsNcs_Meta-analysis.rds"")) + saveRDS(ncs, fileName) +} + +computeGroupMetaAnalysis <- function(group, shinyDataFolder) { + # group <- groups[[2]] + analysisId <- group$analysisId[1] + targetId <- group$targetId[1] + comparatorId <- group$comparatorId[1] + OhdsiRTools::logTrace(""Performing meta-analysis for target "", targetId, "", comparator "", comparatorId, "", analysis"", analysisId) + outcomeGroups <- split(group, group$outcomeId) + outcomeGroupResults <- lapply(outcomeGroups, computeSingleMetaAnalysis) + groupResults <- do.call(rbind, outcomeGroupResults) + negControlSubset <- groupResults[groupResults$type == ""Negative control"", ] + validNcs <- sum(!is.na(negControlSubset$seLogRr)) + if (validNcs >= 5) { + fileName <- file.path(shinyDataFolder, paste0(""null_a"",analysisId,""_t"",targetId,""_c"",comparatorId,""_Meta-analysis.rds"")) + null <- EmpiricalCalibration::fitMcmcNull(negControlSubset$logRr, negControlSubset$seLogRr) + saveRDS(null, fileName) + + calibratedP <- EmpiricalCalibration::calibrateP(null = null, + logRr = groupResults$logRr, + seLogRr = groupResults$seLogRr) + groupResults$calP <- calibratedP$p + groupResults$calP_lb95ci <- calibratedP$lb95ci + groupResults$calP_ub95ci <- calibratedP$ub95ci + } else { + groupResults$calP <- NA + groupResults$calP_lb95ci <- NA + groupResults$calP_ub95ci <- NA + } + return(groupResults) +} + +computeSingleMetaAnalysis <- function(outcomeGroup) { + # outcomeGroup <- outcomeGroups[[1]] + maRow <- outcomeGroup[1, ] + outcomeGroup <- outcomeGroup[!is.na(outcomeGroup$seLogRr), ] + if (nrow(outcomeGroup) == 0) { + maRow$treated <- 0 + maRow$comparator <- 0 + maRow$treatedDays <- 0 + maRow$comparatorDays <- 0 + maRow$eventsTreated <- 0 + maRow$eventsComparator <- 0 + maRow$rr <- NA + maRow$ci95lb <- NA + maRow$ci95ub <- NA + maRow$p <- NA + maRow$logRr <- NA + maRow$seLogRr <- NA + maRow$i2 <- NA + } else if (nrow(outcomeGroup) == 1) { + maRow <- outcomeGroup[1, ] + maRow$i2 <- 0 + } else { + maRow$treated <- sum(outcomeGroup$treated) + maRow$comparator <- sum(outcomeGroup$comparator) + maRow$treatedDays <- sum(outcomeGroup$treatedDays) + maRow$comparatorDays <- sum(outcomeGroup$comparatorDays) + maRow$eventsTreated <- sum(outcomeGroup$eventsTreated) + maRow$eventsComparator <- sum(outcomeGroup$eventsComparator) + meta <- meta::metagen(outcomeGroup$logRr, outcomeGroup$seLogRr, sm = ""RR"", hakn = TRUE) + s <- summary(meta) + maRow$i2 <- s$I2$TE + if (maRow$i2 < .40) { + rnd <- s$random + maRow$rr <- exp(rnd$TE) + maRow$ci95lb <- exp(rnd$lower) + maRow$ci95ub <- exp(rnd$upper) + maRow$p <- rnd$p + maRow$logRr <- rnd$TE + maRow$seLogRr <- rnd$seTE + } else { + maRow$rr <- NA + maRow$ci95lb <- NA + maRow$ci95ub <- NA + maRow$p <- NA + maRow$logRr <- NA + maRow$seLogRr <- NA + } + } + if (is.na(maRow$logRr)) { + maRow$mdrr <- NA + } else { + alpha <- 0.05 + power <- 0.8 + z1MinAlpha <- qnorm(1 - alpha/2) + zBeta <- -qnorm(1 - power) + pA <- maRow$treated / (maRow$treated + maRow$comparator) + pB <- 1 - pA + totalEvents <- maRow$eventsTreated + maRow$eventsComparator + maRow$mdrr <- exp(sqrt((zBeta + z1MinAlpha)^2/(totalEvents * pA * pB))) + } + maRow$database <- ""Meta-analysis"" + return(maRow) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iAcutePancreatitis/R/CreateStudyAnalysisDetails.R",".R","26794","362","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# 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. + +#' Create the analyses details +#' +#' @details +#' This function creates files specifying the analyses that will be performed. +#' +#' @param workFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' +#' @export +createAnalysesDetails <- function(workFolder) { + defaultPrior <- Cyclops::createPrior(""laplace"", + exclude = c(0), + useCrossValidation = TRUE) + + defaultControl <- Cyclops::createControl(cvType = ""auto"", + startingVariance = 0.01, + noiseLevel = ""quiet"", + tolerance = 1e-06, + maxIterations = 2500, + cvRepetitions = 10, + seed = 1234) + + defaultCovariateSettings <- FeatureExtraction::createCovariateSettings(useDemographicsGender = TRUE, + useDemographicsAgeGroup = TRUE, + useDemographicsIndexYear = TRUE, + useDemographicsIndexMonth = TRUE, + useConditionGroupEraLongTerm = TRUE, + useDrugExposureLongTerm = TRUE, + useDrugGroupEraLongTerm = TRUE, + useProcedureOccurrenceLongTerm = TRUE, + useMeasurementLongTerm = TRUE, + useCharlsonIndex = TRUE, + useDistinctConditionCountLongTerm = TRUE, + useDistinctIngredientCountLongTerm = TRUE, + useDistinctProcedureCountLongTerm = TRUE, + useDistinctMeasurementCountLongTerm = TRUE, + useDistinctObservationCountLongTerm = TRUE, + useVisitCountLongTerm = TRUE, + useVisitConceptCountLongTerm = TRUE, + longTermStartDays = -365, + mediumTermStartDays = -180, + shortTermStartDays = -30, + endDays = 0, + addDescendantsToExclude = TRUE) + + priorOutcomesCovariateSettings <- createPriorOutcomesCovariateSettings(windowStart = -99999, + windowEnd = -1, + outcomeIds = c(6479), + outcomeNames = c(""Acute Pancreatitis"")) + + covariateSettings <- list(priorOutcomesCovariateSettings, defaultCovariateSettings) + + getDbCmDataArgs <- CohortMethod::createGetDbCohortMethodDataArgs(washoutPeriod = 0, + firstExposureOnly = FALSE, + removeDuplicateSubjects = FALSE, + restrictToCommonPeriod = TRUE, + maxCohortSize = 0, + excludeDrugsFromCovariates = FALSE, + covariateSettings = covariateSettings) + + timeToFirstEverEventPP <- CohortMethod::createCreateStudyPopulationArgs(removeSubjectsWithPriorOutcome = TRUE, + firstExposureOnly = FALSE, + washoutPeriod = 0, + removeDuplicateSubjects = FALSE, + minDaysAtRisk = 1, + riskWindowStart = 1, + addExposureDaysToStart = FALSE, + riskWindowEnd = 30, + addExposureDaysToEnd = TRUE, + censorAtNewRiskWindow = FALSE) + + timeToFirstPostIndexEventPP <- CohortMethod::createCreateStudyPopulationArgs(removeSubjectsWithPriorOutcome = FALSE, + firstExposureOnly = FALSE, + washoutPeriod = 0, + removeDuplicateSubjects = FALSE, + minDaysAtRisk = 1, + riskWindowStart = 1, + addExposureDaysToStart = FALSE, + riskWindowEnd = 30, + addExposureDaysToEnd = TRUE, + censorAtNewRiskWindow = FALSE) + + timeToFirstEverEventPPZero <- CohortMethod::createCreateStudyPopulationArgs(removeSubjectsWithPriorOutcome = TRUE, + firstExposureOnly = FALSE, + washoutPeriod = 0, + removeDuplicateSubjects = FALSE, + minDaysAtRisk = 1, + riskWindowStart = 1, + addExposureDaysToStart = FALSE, + riskWindowEnd = 0, + addExposureDaysToEnd = TRUE, + censorAtNewRiskWindow = FALSE) + + timeToFirstPostIndexEventPPZero <- CohortMethod::createCreateStudyPopulationArgs(removeSubjectsWithPriorOutcome = FALSE, + firstExposureOnly = FALSE, + washoutPeriod = 0, + removeDuplicateSubjects = FALSE, + minDaysAtRisk = 1, + riskWindowStart = 1, + addExposureDaysToStart = FALSE, + riskWindowEnd = 0, + addExposureDaysToEnd = TRUE, + censorAtNewRiskWindow = FALSE) + + timeToFirstEverEventPPSixty <- CohortMethod::createCreateStudyPopulationArgs(removeSubjectsWithPriorOutcome = TRUE, + firstExposureOnly = FALSE, + washoutPeriod = 0, + removeDuplicateSubjects = FALSE, + minDaysAtRisk = 1, + riskWindowStart = 1, + addExposureDaysToStart = FALSE, + riskWindowEnd = 60, + addExposureDaysToEnd = TRUE, + censorAtNewRiskWindow = FALSE) + + timeToFirstPostIndexEventPPSixty <- CohortMethod::createCreateStudyPopulationArgs(removeSubjectsWithPriorOutcome = FALSE, + firstExposureOnly = FALSE, + washoutPeriod = 0, + removeDuplicateSubjects = FALSE, + minDaysAtRisk = 1, + riskWindowStart = 1, + addExposureDaysToStart = FALSE, + riskWindowEnd = 60, + addExposureDaysToEnd = TRUE, + censorAtNewRiskWindow = FALSE) + + timeToFirstEverEventITT <- CohortMethod::createCreateStudyPopulationArgs(removeSubjectsWithPriorOutcome = TRUE, + firstExposureOnly = FALSE, + washoutPeriod = 0, + removeDuplicateSubjects = FALSE, + minDaysAtRisk = 1, + riskWindowStart = 1, + addExposureDaysToStart = FALSE, + riskWindowEnd = 9999, + addExposureDaysToEnd = FALSE, + censorAtNewRiskWindow = FALSE) + + timeToFirstPostIndexEventITT <- CohortMethod::createCreateStudyPopulationArgs(removeSubjectsWithPriorOutcome = FALSE, + firstExposureOnly = FALSE, + washoutPeriod = 0, + removeDuplicateSubjects = FALSE, + minDaysAtRisk = 1, + riskWindowStart = 1, + addExposureDaysToStart = FALSE, + riskWindowEnd = 9999, + addExposureDaysToEnd = FALSE, + censorAtNewRiskWindow = FALSE) + + + createPsArgs1 <- CohortMethod::createCreatePsArgs(control = defaultControl, + errorOnHighCorrelation = FALSE, + stopOnError = FALSE) + + matchOnPsArgs1 <- CohortMethod::createMatchOnPsArgs(maxRatio = 100) + matchOnPsArgsCaliperSensitivity <- CohortMethod::createMatchOnPsArgs(caliper = 0.1, maxRatio=100) + + stratifyByPsArgs <- CohortMethod::createStratifyByPsArgs(numberOfStrata = 10) + + fitOutcomeModelArgs1 <- CohortMethod::createFitOutcomeModelArgs(useCovariates = FALSE, + modelType = ""cox"", + stratified = TRUE, + prior = defaultPrior, + control = defaultControl) + + a1 <- CohortMethod::createCmAnalysis(analysisId = 1, + description = ""Time to First Ever Event Per Protocol, Matching"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstEverEventPP, + createPs = TRUE, + createPsArgs = createPsArgs1, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgs1, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + a9 <- CohortMethod::createCmAnalysis(analysisId = 9, + description = ""Time to First Ever Event Per Protocol, Matching, Zero Day"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstEverEventPPZero, + createPs = TRUE, + createPsArgs = createPsArgs1, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgs1, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + a10 <- CohortMethod::createCmAnalysis(analysisId = 10, + description = ""Time to First Ever Event Per Protocol, Matching, Sixty Day"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstEverEventPPSixty, + createPs = TRUE, + createPsArgs = createPsArgs1, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgs1, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + a2 <- CohortMethod::createCmAnalysis(analysisId = 2, + description = ""Time to First Post Index Event Per Protocol, Matching"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstPostIndexEventPP, + createPs = TRUE, + createPsArgs = createPsArgs1, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgs1, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + a13 <- CohortMethod::createCmAnalysis(analysisId = 13, + description = ""Time to First Post Index Event Per Protocol, Matching"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstPostIndexEventPP, + createPs = TRUE, + createPsArgs = createPsArgs1, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgsCaliperSensitivity, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + a11 <- CohortMethod::createCmAnalysis(analysisId = 11, + description = ""Time to First Post Index Event Per Protocol, Matching, Zero Day"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstPostIndexEventPPZero, + createPs = TRUE, + createPsArgs = createPsArgs1, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgs1, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + a12 <- CohortMethod::createCmAnalysis(analysisId = 12, + description = ""Time to First Post Index Event Per Protocol, Matching, Sixty Day"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstPostIndexEventPPSixty, + createPs = TRUE, + createPsArgs = createPsArgs1, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgs1, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + a3 <- CohortMethod::createCmAnalysis(analysisId = 3, + description = ""Time to First Ever Event Intent to Treat, Matching"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstEverEventITT, + createPs = TRUE, + createPsArgs = createPsArgs1, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgs1, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + a4 <- CohortMethod::createCmAnalysis(analysisId = 4, + description = ""Time to First Post Index Event Intent to Treat, Matching"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstPostIndexEventITT, + createPs = TRUE, + createPsArgs = createPsArgs1, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgs1, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + a14 <- CohortMethod::createCmAnalysis(analysisId = 14, + description = ""Time to First Post Index Event Intent to Treat, Matching"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstPostIndexEventITT, + createPs = TRUE, + createPsArgs = createPsArgs1, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgsCaliperSensitivity, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + a5 <- CohortMethod::createCmAnalysis(analysisId = 5, + description = ""Time to First Ever Event Per Protocol, Stratification"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstEverEventPP, + createPs = TRUE, + createPsArgs = createPsArgs1, + stratifyByPs = TRUE, + stratifyByPsArgs = stratifyByPsArgs, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + a6 <- CohortMethod::createCmAnalysis(analysisId = 6, + description = ""Time to First Post Index Event Per Protocol, Stratification"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstPostIndexEventPP, + createPs = TRUE, + createPsArgs = createPsArgs1, + stratifyByPs = TRUE, + stratifyByPsArgs = stratifyByPsArgs, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + a7 <- CohortMethod::createCmAnalysis(analysisId = 7, + description = ""Time to First Ever Event Intent to Treat, Stratification"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstEverEventITT, + createPs = TRUE, + createPsArgs = createPsArgs1, + stratifyByPs = TRUE, + stratifyByPsArgs = stratifyByPsArgs, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + a8 <- CohortMethod::createCmAnalysis(analysisId = 8, + description = ""Time to First Post Index Event Intent to Treat, Stratification"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstPostIndexEventITT, + createPs = TRUE, + createPsArgs = createPsArgs1, + stratifyByPs = TRUE, + stratifyByPsArgs = stratifyByPsArgs, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + cmAnalysisList <- list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14) + + CohortMethod::saveCmAnalysisList(cmAnalysisList, file.path(workFolder, ""cmAnalysisList.json"")) +} + +createTcos <- function(outputFolder) { + pathToCsv <- system.file(""settings"", ""TcosOfInterest.csv"", package = ""AHAsAcutePancreatitis"") + tcosOfInterest <- read.csv(pathToCsv, stringsAsFactors = FALSE) + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""AHAsAcutePancreatitis"") + negativeControls <- read.csv(pathToCsv) + negativeControlOutcomes <- negativeControls[negativeControls$type == ""Outcome"", ] + dcosList <- list() + tcs <- unique(tcosOfInterest[, c(""targetId"", ""comparatorId"")]) + for (i in 1:nrow(tcs)) { + targetId <- tcs$targetId[i] + comparatorId <- tcs$comparatorId[i] + outcomeIds <- as.character(tcosOfInterest$outcomeIds[tcosOfInterest$targetId == targetId & tcosOfInterest$comparatorId == comparatorId]) + outcomeIds <- as.numeric(strsplit(outcomeIds, split = "";"")[[1]]) + outcomeIds <- c(outcomeIds, negativeControlOutcomes$outcomeId) + excludeConceptIds <- tcosOfInterest$excludedCovariateConceptIds[tcosOfInterest$targetId == targetId & tcosOfInterest$comparatorId == comparatorId] + excludeConceptIds <- as.numeric(strsplit(excludeConceptIds, split = "";"")[[1]]) + dcos <- CohortMethod::createDrugComparatorOutcomes(targetId = targetId, + comparatorId = comparatorId, + outcomeIds = outcomeIds, + excludedCovariateConceptIds = excludeConceptIds) + dcosList[[length(dcosList) + 1]] <- dcos + } + return(dcosList) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iAcutePancreatitis/R/CreateTablesAndFiguresForReport.R",".R","57723","1774","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# 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. + +#' Create figures and tables for report +#' +#' @details +#' This function generates tables and figures for the report on the study results. +#' +#' @param outputFolders Vector of names of local folders where the results were generated; make sure +#' to use forward slashes (/). D +#' @param databaseNames A vector of unique names for the databases. +#' @param maOutputFolder A local folder where the meta-anlysis results were be written. +#' @param reportFolder A local folder where the tables and figures will be written. +#' +#' @export +createTableAndFiguresForReport <- + function(outputFolders, + databaseNames, + maOutputFolder, + reportFolder) { + # outputFolders = c(file.path(studyFolder, ""ccae""), file.path(studyFolder, ""mdcr""), file.path(studyFolder, ""optum"")) + # databaseNames = c(""CCAE"", ""MDCR"", ""Optum"") + # reportFolder = file.path(studyFolder, ""report"") + # maOutputFolder = file.path(studyFolder, ""metaAnalysis"") + + comparisonsOfInterest <- c( + ""canagliflozin - GLP-1 inhibitors"", + ""canagliflozin - DPP-4 inhibitors"", + ""canagliflozin - Sulfonylurea"", + ""canagliflozin - TZD"", + ""canagliflozin - Insulin new users"", + ""canagliflozin - Other AHA"" + ) + + secondaryComparisons <- c( + ""canagliflozin - Alogliptin"", + ""canagliflozin - Linagliptin"", + ""canagliflozin - Saxagliptin"", + ""canagliflozin - Sitagliptin"", + ""canagliflozin - Albiglutide"", + ""canagliflozin - Dulaglutide"", + ""canagliflozin - Exenatide"", + ""canagliflozin - Liraglutide"", + ""canagliflozin - Lixisenatide"", + ""canagliflozin - Pioglitazone"", + ""canagliflozin - Rosiglitazone"", + ""canagliflozin - Glyburide"", + ""canagliflozin - Glimepiride"", + ""canagliflozin - Glipizide"", + ""canagliflozin - Acarbose"", + ""canagliflozin - Bromocriptine"", + ""canagliflozin - Miglitol"", + ""canagliflozin - Nateglinide"", + ""canagliflozin - Repaglinide"", + ""canagliflozin - Empagliflozin"", + ""canagliflozin - Dapagliflozin"" + ) + + if (!file.exists(reportFolder)) + dir.create(reportFolder, recursive = TRUE) + + #createPopCharTable(outputFolders, databaseNames, reportFolder, comparisonsOfInterest) + createHrTable(outputFolders, databaseNames, reportFolder, comparisonsOfInterest, ""PRIMARY"") + createHrTable(outputFolders, databaseNames, reportFolder, secondaryComparisons, ""SECONDARY"") + #createFullHrTable(outputFolders, databaseNames, reportFolder,c(comparisonsOfInterest,secondaryComparisons), ""FULL"") + createSensAnalysesFigure(outputFolders, databaseNames, reportFolder,comparisonsOfInterest) + createIrTable(outputFolders, databaseNames, reportFolder,comparisonsOfInterest) + #selectKaplanMeierPlots(outputFolders, databaseNames, reportFolder) + createTimeAtRiskTable(outputFolders, databaseNames, reportFolder, comparisonsOfInterest) + } + +formatHr <- function(hr, lb, ub) { + ifelse (is.na(lb) | is.na(ub) | is.na(hr), ""NA"", sprintf( + ""%s (%s-%s)"", + formatC(hr, digits = 2, format = ""f""), + formatC(lb, digits = 2, format = ""f""), + formatC(ub, digits = 2, format = ""f"") + ) + ) +} + +createIrTable <- + function(outputFolders, + databaseNames, + reportFolder, + comparisonsOfInterest) { + loadResultsHois <- function(outputFolder, fileName) { + shinyDataFolder <- file.path(outputFolder, ""results"", ""shinyData"") + file <- + list.files(shinyDataFolder, + pattern = ""resultsHois_.*.rds"", + full.names = TRUE) + x <- readRDS(file) + if (is.null(x$i2)) + x$i2 <- NA + return(x) + } + results <- lapply(outputFolders, loadResultsHois) + results <- do.call(rbind, results) + results <- cleanResults(results) + results$comparison <- + paste(results$targetDrug, results$comparatorDrug, sep = "" - "") + + results <- results[results$psStrategy == ""Matching"" & + results$eventType == ""First Post Index Event"" & + results$comparison %in% comparisonsOfInterest,] + + outcomeNames <- unique(results$outcomeName) + #timeAtRisks <- unique(results$timeAtRisk) + timeAtRisks <- c('On Treatment (30 Day)','Intent to Treat') + mainTable <- data.frame() + for (database in databaseNames) { + dbTable <- data.frame() + for (outcomeName in outcomeNames) { + for (timeAtRisk in timeAtRisks) { + subset <- results[results$database == database & + results$outcomeName == outcomeName & + results$timeAtRisk == timeAtRisk & + results$canaRestricted == TRUE,] + cana <- subset[subset$targetDrug == ""canagliflozin"",][1, ] + glp1 <- + subset[subset$comparatorDrug == "" GLP-1 inhibitors"",][1, ] + dpp4 <- + subset[subset$comparatorDrug == "" DPP-4 inhibitors"",][1, ] + su <- + subset[subset$comparatorDrug == ""Sulfonylurea"",][1, ] + insulin <- + subset[subset$comparatorDrug == ""Insulin new users"",][1, ] + tzd <- subset[subset$comparatorDrug == ""TZD"",][1, ] + oaha <- subset[subset$comparatorDrug == ""Other AHA"",][1, ] + + subTable <- data.frame( + outcomeName = outcomeName, + timeAtRisk = timeAtRisk, + exposure = c( + ""canagliflozin"", + ""GLP1"", + ""DPP4"", + ""Sulfonylurea"", + ""TZDs"", + ""Other AHAs"", + ""Insulin new users"" + ), + subjects = c( + cana$treated, + glp1$comparator, + dpp4$comparator, + su$comparator, + tzd$comparator, + oaha$comparator, + insulin$comparator + ), + personTime = c( + cana$treatedDays, + glp1$comparatorDays, + dpp4$comparatorDays, + su$comparatorDays, + tzd$comparatorDays, + oaha$comparatorDays, + insulin$comparatorDays + ) / 365.25, + events = c( + cana$eventsTreated, + glp1$eventsComparator, + dpp4$eventsComparator, + su$eventsComparator, + tzd$eventsComparator, + oaha$eventsComparator, + insulin$eventsComparator + ) + ) + subTable$ir <- + 1000 * subTable$events / subTable$personTime + dbTable <- rbind(dbTable, subTable) + } + } + colnames(dbTable)[4:7] <- + paste(colnames(dbTable)[4:7], database, sep = ""_"") + if (ncol(mainTable) == 0) { + mainTable <- dbTable + } else { + if (!all.equal(mainTable$outcomeName, dbTable$outcomeName) || + !all.equal(mainTable$timeAtRisk, dbTable$timeAtRisk) || + !all.equal(mainTable$exposure, dbTable$exposure)) { + stop(""Something wrong with data ordering"") + } + mainTable <- cbind(mainTable, dbTable[, 4:7]) + } + } + + fileName <- + file.path(reportFolder, paste0(""IRs_"", ""all"", "".xlsx"")) + unlink(fileName) + wb <- XLConnect::loadWorkbook(fileName, create = TRUE) + XLConnect::createSheet(wb, name = ""Incidence"") + + header0 <- c("""", """", """", rep(databaseNames, each = 4)) + XLConnect::writeWorksheet( + wb, + sheet = ""Incidence"", + data = as.data.frame(t(header0)), + startRow = 1, + startCol = 1, + rownames = FALSE, + header = FALSE + ) + + header1 <- + c(""Outcome"", ""Time-at-risk"", ""Exposure"", rep( + c(""Persons"", ""Person-time"", ""Events"", ""IR""), + length(databaseNames) + )) + XLConnect::writeWorksheet( + wb, + sheet = ""Incidence"", + data = as.data.frame(t(header1)), + startRow = 2, + startCol = 1, + rownames = FALSE, + header = FALSE + ) + + XLConnect::writeWorksheet( + wb, + sheet = ""Incidence"", + data = mainTable, + startRow = 3, + startCol = 1, + rownames = FALSE, + header = FALSE + ) + countStyle <- XLConnect::createCellStyle(wb) + XLConnect::setDataFormat(countStyle, format = ""###,###,##0"") + rateStyle <- XLConnect::createCellStyle(wb) + XLConnect::setDataFormat(rateStyle, format = ""##0.0"") + for (i in 1:length(databaseNames)) { + XLConnect::setCellStyle( + wb, + sheet = ""Incidence"", + row = 3:18, + col = i * 4 + rep(0, 30), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Incidence"", + row = 3:18, + col = i * 4 + rep(1, 30), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Incidence"", + row = 3:18, + col = i * 4 + rep(2, 30), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Incidence"", + row = 3:18, + col = i * 4 + rep(3, 30), + cellstyle = rateStyle + ) + } + XLConnect::saveWorkbook(wb) + } + +createSensAnalysesFigure <- + function(outputFolders, + databaseNames, + reportFolder, + comparisonsOfInterest) { + loadResultsHois <- function(outputFolder, fileName) { + shinyDataFolder <- file.path(outputFolder, ""results"", ""shinyData"") + file <- + list.files(shinyDataFolder, + pattern = ""resultsHois_.*.rds"", + full.names = TRUE) + x <- readRDS(file) + if (is.null(x$i2)) + x$i2 <- NA + return(x) + } + results <- lapply(c(outputFolders), loadResultsHois) + results <- do.call(rbind, results) + results <- cleanResults(results) + results$comparison <- + paste(results$targetDrug, results$comparatorDrug, sep = "" - "") + unique(results$timeAtRisk) + outcomeNames <- unique(results$outcomeName) + for (outcomeName in outcomeNames) { + results$dbOrder <- + match(results$database, c(""CCAE"", ""MDCR"", ""Optum"")) + results$comparisonOrder <- + match(results$comparison, comparisonsOfInterest) + results$timeAtRiskOrder <- + match( + results$timeAtRisk, + c( + ""On Treatment (30 Day)"", + ""On Treatment (0 Day)"", + ""On Treatment (60 Day)"", + ""Intent to Treat"" + ) + ) + + subset <- results[results$outcomeName == outcomeName & + results$comparison %in% comparisonsOfInterest,] + subset <- subset[order( + subset$comparisonOrder, + subset$dbOrder, + subset$timeAtRiskOrder, + subset$eventType, + subset$psStrategy + ),] + subset$rr[is.na(subset$seLogRr)] <- NA + facetCount <- + (length(unique(subset$comparison)) * length(unique(subset$database))) + subset$displayOrder <- + rep((nrow(subset) / facetCount):1, facetCount) + formatQuestion <- function(x) { + # result <- rep(""canagliflozin vs. other SGLT2i"", length(x)) + # result[x == ""canagliflozin - any DPP-4 inhibitor, GLP-1 agonist, or other select AHA""] <- ""canagliflozin vs. select non-SGLT2i"" + # result[x == ""empagliflozin or dapagliflozin - any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA""] <- ""other SGLT2i vs. all non-SGLT2"" + # result[x == ""canagliflozin - any DPP-4 inhibitor, GLP-1 agonist, TZD, SU, insulin, or other select AHA""] <- ""canagliflozin vs. all non-SGLT2i"" + # return(result) + return(x) + } + formatTimeAtRisk <- function(x) { + result <- x + # result[x == ""Intent to Treat""] <- ""Intent-to-treat"" + # result[x == ""On Treatment""] <- ""On treatment"" + # result[x == ""On Treatment (no censor at switch)""] <- ""On treatment (no censor at switch)"" + # result[x == ""Lag""] <- ""On treatment lagged"" + # result[x == ""Lag (no censor at switch)""] <- ""On treatment lagged (no censor at switch)"" + return(result) + } + subset$comparison <- formatQuestion(subset$comparison) + subset$timeAtRisk <- formatTimeAtRisk(subset$timeAtRisk) + breaks <- c(0.1, 0.25, 0.5, 1, 2, 4, 6, 8, 10) + col <- c(rgb(0, 0, 0.8, alpha = 1), rgb(0.8, 0.4, 0, alpha = 1)) + colFill <- + c(rgb(0, 0, 1, alpha = 0.5), rgb(1, 0.4, 0, alpha = 0.5)) + subset$database <- + factor(subset$database, levels = c(""CCAE"", ""MDCR"", ""Optum"")) + subset$comparison <- + factor( + subset$comparison, + levels = c( + ""canagliflozin - GLP-1 inhibitors"", + ""canagliflozin - DPP-4 inhibitors"", + ""canagliflozin - Sulfonylurea"", + ""canagliflozin - TZD"", + ""canagliflozin - Insulin new users"", + ""canagliflozin - Other AHA"" + ) + ) + subset$timeAtRisk <- + factor( + subset$timeAtRisk, + levels = c( + ""On Treatment (30 Day)"", + ""On Treatment (0 Day)"", + ""On Treatment (60 Day)"", + ""Intent to Treat"" + ) + ) + plot <- ggplot2::ggplot( + subset, + ggplot2::aes( + x = rr, + y = displayOrder, + xmin = ci95lb, + xmax = ci95ub, + colour = timeAtRisk, + fill = timeAtRisk + ), + environment = environment() + ) + + ggplot2::geom_vline( + xintercept = breaks, + colour = ""#AAAAAA"", + lty = 1, + size = 0.2 + ) + + ggplot2::geom_vline( + xintercept = 1, + colour = ""#000000"", + lty = 1, + size = 0.5 + ) + + ggplot2::geom_errorbarh(height = 0, alpha = 0.7) + + ggplot2::geom_point(shape = 16, + size = 1, + alpha = 0.7) + + # ggplot2::scale_colour_manual(values = col) + + # ggplot2::scale_fill_manual(values = colFill) + + ggplot2::coord_cartesian(xlim = c(0.1, 10)) + + ggplot2::scale_x_continuous( + ""Hazard ratio"", + trans = ""log10"", + breaks = breaks, + labels = breaks + ) + + ggplot2::facet_grid(database ~ comparison, scales = ""free_y"", space = ""free"") + + ggplot2::labs(color = ""Time-at-risk"", fill = ""Time-at-risk"") + + ggplot2::theme( + panel.grid.minor = ggplot2::element_blank(), + panel.background = ggplot2::element_rect(fill = ""#FAFAFA"", colour = NA), + panel.grid.major = ggplot2::element_line(colour = ""#EEEEEE""), + axis.ticks = ggplot2::element_blank(), + axis.title.y = ggplot2::element_blank(), + axis.title.x = ggplot2::element_blank(), + axis.text.y = ggplot2::element_blank(), + legend.position = ""top"" + ) + + fileName <- + file.path(reportFolder, paste0(""SensAnalyses "", outcomeName, "".png"")) + ggplot2::ggsave(fileName, + plot, + width = 10, + height = 12, + dpi = 400) + } + } + +cleanResults <- function(results) { + #fix a typo + results[results$eventType == ""First EVer Event"", ]$eventType <- + ""First Ever Event"" + #create additional filter variables + results$noCana <- + with(results, ifelse(grepl(""no cana"", comparatorName), TRUE, FALSE)) + results$noCensor <- + with(results, ifelse(grepl(""no censoring"", comparatorName), TRUE, FALSE)) + #simplify naming + results[results$timeAtRisk == ""Per Protocol Zero Day (no censor at switch)"", ]$timeAtRisk <- + ""On Treatment (0 Day)"" + results[results$timeAtRisk == ""On Treatment"", ]$timeAtRisk <- + ""On Treatment (30 Day)"" + results[results$timeAtRisk == ""On Treatment (no censor at switch)"", ]$timeAtRisk <- + ""On Treatment (30 Day)"" + results[results$timeAtRisk == ""Per Protocol Sixty Day (no censor at switch)"", ]$timeAtRisk <- + ""On Treatment (60 Day)"" + results[results$timeAtRisk == ""Per Protocol Zero Day"", ]$timeAtRisk <- + ""On Treatment (0 Day)"" + results[results$timeAtRisk == ""Per Protocol Sixty Day"", ]$timeAtRisk <- + ""On Treatment (60 Day)"" + results <- results[results$noCensor == F,] + return(results) +} + +createFullHrTable <- + function(outputFolders, + databaseNames, + reportFolder, + comparisonsOfInterest, + fileIdentifier) { + requireNamespace(""XLConnect"") + loadResultsHois <- function(outputFolder, fileName) { + shinyDataFolder <- file.path(outputFolder, ""results"", ""shinyData"") + file <- + list.files(shinyDataFolder, + pattern = ""resultsHois_.*.rds"", + full.names = TRUE) + x <- readRDS(file) + if (is.null(x$i2)) + x$i2 <- NA + return(x) + } + results <- lapply(c(outputFolders), loadResultsHois) + results <- do.call(rbind, results) + results <- cleanResults(results) + results$comparison <- + paste(results$targetDrug, results$comparatorDrug, sep = "" - "") + outcomeNames <- unique(results$outcomeName) + + for (outcomeName in outcomeNames) { + fileName <- file.path(reportFolder, paste0(""HRs "", outcomeName, ""_"", fileIdentifier, "".xlsx"")) + unlink(fileName) + wb <- XLConnect::loadWorkbook(fileName, create = TRUE) + XLConnect::createSheet(wb, name = ""Hazard ratios"") + + header0 <- rep("""", 14) + header0[5] <- ""On treatment"" + header0[11] <- ""Intent-to-treat"" + XLConnect::writeWorksheet( + wb, + sheet = ""Hazard ratios"", + data = as.data.frame(t(header0)), + startRow = 1, + startCol = 1, + rownames = FALSE, + header = FALSE + ) + XLConnect::mergeCells(wb, sheet = ""Hazard ratios"", reference = ""E1:J1"") + XLConnect::mergeCells(wb, sheet = ""Hazard ratios"", reference = ""K1:P1"") + header1 <- + c( + """", + """", + ""Exposed (#/PY)"", + """", + ""Outcomes"", + """", + ""HR (95% CI)"", + ""p"", + ""Cal. p"", + ""Hoch. p"", + ""Outcomes"", + "" "", + ""HR (95% CI)"", + ""p"", + ""Cal. p"", + ""Hoch. p"" + ) + XLConnect::writeWorksheet( + wb, + sheet = ""Hazard ratios"", + data = as.data.frame(t(header1)), + startRow = 2, + startCol = 1, + rownames = FALSE, + header = FALSE + ) + XLConnect::mergeCells(wb, sheet = ""Hazard ratios"", reference = ""C2:D2"") + XLConnect::mergeCells(wb, sheet = ""Hazard ratios"", reference = ""E2:F2"") + XLConnect::mergeCells(wb, sheet = ""Hazard ratios"", reference = ""K2:L2"") + header2 <- c(""Comparator"", + ""Source"", + ""T"", + ""C"", + ""T"", + ""C"", + """", + """", + """", + """", + ""T"", + ""C"") + XLConnect::writeWorksheet( + wb, + sheet = ""Hazard ratios"", + data = as.data.frame(t(header2)), + startRow = 3, + startCol = 1, + rownames = FALSE, + header = FALSE + ) + + results$dbOrder <- match(results$database, c(""CCAE"", ""MDCR"", ""Optum"")) + results$comparisonOrder <- match(results$comparison, comparisonsOfInterest) + + onTreatment <- results[results$timeAtRisk == ""On Treatment (30 Day)"",] + onTreatment <- onTreatment[order(onTreatment$comparisonOrder, onTreatment$dbOrder),] + + formatSampleSize <- function(subjects, days) { + paste( + formatC(subjects, big.mark = "","", format = ""d""), + formatC(days / 365.25, big.mark = "","", format = ""d""), + sep = "" / "" + ) + } + + mainTable <- + data.frame( + comparator = onTreatment$comparatorDrug, + source = onTreatment$database, + t = formatSampleSize(onTreatment$treated, onTreatment$treatedDays), + c = formatSampleSize(onTreatment$comparator, onTreatment$comparatorDays), + oTonTreatment = onTreatment$eventsTreated, + oConTreatment = onTreatment$eventsComparator, + hrOnTreatment = formatHr(onTreatment$rr, onTreatment$ci95lb, onTreatment$ci95ub), + pOnTreatment = onTreatment$p, + calPOnTreatment = onTreatment$calP, + hochPOnTreatment = p.adjust(onTreatment$calP,""hochberg"") + ) + XLConnect::writeWorksheet( + wb, + data = mainTable, + sheet = ""Hazard ratios"", + startRow = 4, + startCol = 1, + header = FALSE, + rownames = FALSE + ) + pStyle <- XLConnect::createCellStyle(wb) + XLConnect::setDataFormat(pStyle, format = ""0.00"") + countStyle <- XLConnect::createCellStyle(wb) + XLConnect::setDataFormat(countStyle, format = ""#,##0"") + XLConnect::setCellStyle( + wb, + sheet = ""Hazard ratios"", + row = 4:10000, + col = rep(5, 19), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Hazard ratios"", + row = 4:10000, + col = rep(6, 19), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Hazard ratios"", + row = 4:10000, + col = rep(8, 19), + cellstyle = pStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Hazard ratios"", + row = 4:10000, + col = rep(9, 19), + cellstyle = pStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Hazard ratios"", + row = 4:10000, + col = rep(10, 19), + cellstyle = pStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Hazard ratios"", + row = 4:10000, + col = rep(11, 19), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Hazard ratios"", + row = 4:10000, + col = rep(12, 19), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Hazard ratios"", + row = 4:10000, + col = rep(14, 19), + cellstyle = pStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Hazard ratios"", + row = 4:10000, + col = rep(15, 19), + cellstyle = pStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Hazard ratios"", + row = 4:10000, + col = rep(16, 19), + cellstyle = pStyle + ) + XLConnect::setColumnWidth(wb, + sheet = ""Hazard ratios"", + column = 1, + width = -1) + XLConnect::setColumnWidth(wb, + sheet = ""Hazard ratios"", + column = 2, + width = -1) + XLConnect::saveWorkbook(wb) + } + } + +createHrTable <- + function(outputFolders, + databaseNames, + reportFolder, + comparisonsOfInterest, + fileIdentifier) { + requireNamespace(""XLConnect"") + loadResultsHois <- function(outputFolder, fileName) { + shinyDataFolder <- file.path(outputFolder, ""results"", ""shinyData"") + file <- + list.files(shinyDataFolder, + pattern = ""resultsHois_.*.rds"", + full.names = TRUE) + x <- readRDS(file) + if (is.null(x$i2)) + x$i2 <- NA + return(x) + } + results <- lapply(c(outputFolders), loadResultsHois) + results <- do.call(rbind, results) + results <- cleanResults(results) + results$comparison <- + paste(results$targetDrug, results$comparatorDrug, sep = "" - "") + outcomeNames <- unique(results$outcomeName) + + for (outcomeName in outcomeNames) { + fileName <- + file.path(reportFolder, paste0(""HRs "", outcomeName, ""_"", fileIdentifier, "".xlsx"")) + unlink(fileName) + wb <- XLConnect::loadWorkbook(fileName, create = TRUE) + XLConnect::createSheet(wb, name = ""Hazard ratios"") + + header0 <- rep("""", 14) + header0[5] <- ""On treatment"" + header0[11] <- ""Intent-to-treat"" + XLConnect::writeWorksheet( + wb, + sheet = ""Hazard ratios"", + data = as.data.frame(t(header0)), + startRow = 1, + startCol = 1, + rownames = FALSE, + header = FALSE + ) + XLConnect::mergeCells(wb, sheet = ""Hazard ratios"", reference = ""E1:J1"") + XLConnect::mergeCells(wb, sheet = ""Hazard ratios"", reference = ""K1:P1"") + header1 <- + c( + """", + """", + ""Exposed (#/PY)"", + """", + ""Outcomes"", + """", + ""HR (95% CI)"", + ""p"", + ""Cal. p"", + ""Hoch. p"", + ""Outcomes"", + "" "", + ""HR (95% CI)"", + ""p"", + ""Cal. p"", + ""Hoch. p"" + ) + XLConnect::writeWorksheet( + wb, + sheet = ""Hazard ratios"", + data = as.data.frame(t(header1)), + startRow = 2, + startCol = 1, + rownames = FALSE, + header = FALSE + ) + XLConnect::mergeCells(wb, sheet = ""Hazard ratios"", reference = ""C2:D2"") + XLConnect::mergeCells(wb, sheet = ""Hazard ratios"", reference = ""E2:F2"") + XLConnect::mergeCells(wb, sheet = ""Hazard ratios"", reference = ""K2:L2"") + header2 <- c(""Comparator"", + ""Source"", + ""T"", + ""C"", + ""T"", + ""C"", + """", + """", + """", + """", + ""T"", + ""C"") + XLConnect::writeWorksheet( + wb, + sheet = ""Hazard ratios"", + data = as.data.frame(t(header2)), + startRow = 3, + startCol = 1, + rownames = FALSE, + header = FALSE + ) + + idx <- results$outcomeName == outcomeName & + results$comparison %in% comparisonsOfInterest & + results$psStrategy == ""Matching"" & + results$noCana == TRUE & + results$noCensor == FALSE & + results$eventType == ""First Post Index Event"" + + results$dbOrder <- + match(results$database, c(""CCAE"", ""MDCR"", ""Optum"")) + results$comparisonOrder <- + match(results$comparison, comparisonsOfInterest) + onTreatment <- + results[idx & results$timeAtRisk == ""On Treatment (30 Day)"",] + itt <- results[idx & results$timeAtRisk == ""Intent to Treat"",] + onTreatment <- onTreatment[order(onTreatment$comparisonOrder, + onTreatment$dbOrder),] + itt <- itt[order(itt$comparisonOrder, + itt$dbOrder),] + + formatSampleSize <- function(subjects, days) { + paste( + formatC(subjects, big.mark = "","", format = ""d""), + formatC(days / 365.25, big.mark = "","", format = ""d""), + sep = "" / "" + ) + } + + mainTable <- + data.frame( + comparator = onTreatment$comparatorDrug, + source = onTreatment$database, + t = formatSampleSize(onTreatment$treated, onTreatment$treatedDays), + c = formatSampleSize(onTreatment$comparator, onTreatment$comparatorDays), + oTonTreatment = onTreatment$eventsTreated, + oConTreatment = onTreatment$eventsComparator, + hrOnTreatment = formatHr(onTreatment$rr, onTreatment$ci95lb, onTreatment$ci95ub), + pOnTreatment = onTreatment$p, + calPOnTreatment = onTreatment$calP, + hochPOnTreatment = p.adjust(onTreatment$calP,""hochberg""), + oTitt = itt$eventsTreated, + oCitt = itt$eventsComparator, + hrItt = formatHr(itt$rr, itt$ci95lb, itt$ci95ub), + pItt = itt$p, + calPItt = itt$calP, + hochPItt = p.adjust(itt$calP, ""hochberg"") + ) + XLConnect::writeWorksheet( + wb, + data = mainTable, + sheet = ""Hazard ratios"", + startRow = 4, + startCol = 1, + header = FALSE, + rownames = FALSE + ) + pStyle <- XLConnect::createCellStyle(wb) + XLConnect::setDataFormat(pStyle, format = ""0.00"") + countStyle <- XLConnect::createCellStyle(wb) + XLConnect::setDataFormat(countStyle, format = ""#,##0"") + XLConnect::setCellStyle( + wb, + sheet = ""Hazard ratios"", + row = 4:10000, + col = rep(5, 19), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Hazard ratios"", + row = 4:1000, + col = rep(6, 19), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Hazard ratios"", + row = 4:10000, + col = rep(8, 19), + cellstyle = pStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Hazard ratios"", + row = 4:10000, + col = rep(9, 19), + cellstyle = pStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Hazard ratios"", + row = 4:10000, + col = rep(10, 19), + cellstyle = pStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Hazard ratios"", + row = 4:10000, + col = rep(11, 19), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Hazard ratios"", + row = 4:10000, + col = rep(12, 19), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Hazard ratios"", + row = 4:10000, + col = rep(14, 19), + cellstyle = pStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Hazard ratios"", + row = 4:10000, + col = rep(15, 19), + cellstyle = pStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Hazard ratios"", + row = 4:10000, + col = rep(16, 19), + cellstyle = pStyle + ) + XLConnect::setColumnWidth(wb, + sheet = ""Hazard ratios"", + column = 1, + width = -1) + XLConnect::setColumnWidth(wb, + sheet = ""Hazard ratios"", + column = 2, + width = -1) + XLConnect::saveWorkbook(wb) + } + } + +createPopCharTable <- + function(outputFolders, + databaseNames, + reportFolder, + comparisonsOfInterest) { + primaryAnalysisId <- + 2 #Time to First Post Index Event On Treatment, Matching + pathToCsv <- + system.file(""settings"", ""TcosOfInterest.csv"", package = ""AHAsAcutePancreatitis"") + tcosOfInterest <- read.csv(pathToCsv, stringsAsFactors = FALSE) + tcosOfInterest$comparison <- + paste(tcosOfInterest$targetDrug, + tcosOfInterest$comparatorDrug, + sep = "" - "") + + primaryTcos = tcosOfInterest[tcosOfInterest$censorAtSwitch == TRUE & + tcosOfInterest$canaRestricted == TRUE & + tcosOfInterest$comparison %in% comparisonsOfInterest,] + pathToCsv <- + system.file(""settings"", ""Analyses.csv"", package = ""AHAsAcutePancreatitis"") + analyses <- read.csv(pathToCsv, stringsAsFactors = FALSE) + + loadBalance <- function(outputFolder, fileName) { + shinyDataFolder <- file.path(outputFolder, ""results"", ""shinyData"") + file <- + list.files(shinyDataFolder, + pattern = fileName, + full.names = TRUE) + return(readRDS(file)) + } + + for (i in 1:nrow(primaryTcos)) { + outcomeIds <- as.character(tcosOfInterest$outcomeIds[i]) + outcomeIds <- as.numeric(strsplit(outcomeIds, split = "";"")[[1]]) + outcomeNames <- as.character(tcosOfInterest$outcomeNames[i]) + outcomeNames <- strsplit(outcomeNames, split = "";"")[[1]] + # One outcome only: + for (j in 1:length(outcomeIds)) { + outcomeId <- outcomeIds[j] + outcomeName <- outcomeNames[j] + allBalance <- list() + tables <- list() + header3 <- c(""Characteristic"") + for (k in 1:length(databaseNames)) { + databaseName <- databaseNames[k] + shinyDataFolder <- + file.path(outputFolders[k], ""results"", ""shinyData"") + fileName <- + paste0( + ""bal_a"", + primaryAnalysisId, + ""_t"", + primaryTcos$targetId[i], + ""_c"", + primaryTcos$comparatorId[i], + ""_o"", + outcomeId, + ""_"", + databaseName, + "".rds"" + ) + balance <- + readRDS(file.path(outputFolders[k], ""results"", ""balance"", fileName)) + + # Infer population sizes before matching: + beforeTargetPopSize <- + round( + mean( + balance$beforeMatchingSumTreated / balance$beforeMatchingMeanTreated, + na.rm = TRUE + ) + ) + beforeComparatorPopSize <- + round( + mean( + balance$beforeMatchingSumComparator / balance$beforeMatchingMeanComparator, + na.rm = TRUE + ) + ) + + fileName <- + paste0( + ""ahaBal_a"", + primaryAnalysisId, + ""_t"", + primaryTcos$targetId[i], + ""_c"", + primaryTcos$comparatorId[i], + ""_o"", + outcomeId, + ""_"", + databaseName, + "".rds"" + ) + priorAhaBalance <- + readRDS(file.path(shinyDataFolder, fileName)) + balance <- balance[, names(priorAhaBalance)] + balance <- rbind(balance, priorAhaBalance) + tables[[k]] <- prepareTable1(balance) + allBalance[[k]] <- balance + fileName <- + file.path(shinyDataFolder, + paste0(""resultsHois_"", databaseName, "".rds"")) + resultsHois <- readRDS(fileName) + row <- + resultsHois[resultsHois$targetId == primaryTcos$targetId[i] & + resultsHois$comparatorId == primaryTcos$comparatorId[i] & + resultsHois$outcomeId == outcomeId & + resultsHois$analysisId == primaryAnalysisId,] + + header3 <- c(header3, ""%"", ""%"", ""Std.d."", ""%"", ""%"", ""Std.d."") + } + + # Create main table by combining all balances to get complete list of covariates: + allBalance <- do.call(rbind, allBalance) + allBalance <- allBalance[order(allBalance$covariateName),] + allBalance <- + allBalance[!duplicated(allBalance$covariateName),] + headerCol <- prepareTable1(allBalance)[, 1] + mainTable <- + matrix(NA, + nrow = length(headerCol), + ncol = length(tables) * 6) + for (k in 1:length(databaseNames)) { + mainTable[match(tables[[k]]$Characteristic, headerCol), ((k - 1) * 6) + + (1:6)] <- as.matrix(tables[[k]][, 2:7]) + } + mainTable <- as.data.frame(mainTable) + mainTable <- + cbind(data.frame(headerCol = headerCol), mainTable) + + createExcelTable <- function(mainTable, part) { + library(xlsx) + workBook <- xlsx::createWorkbook(type = ""xlsx"") + sheet <- + xlsx::createSheet(workBook, sheetName = ""Population characteristics"") + percentStyle <- + xlsx::CellStyle(wb = workBook, + dataFormat = xlsx::DataFormat(""#,##0.0"")) + diffStyle <- + xlsx::CellStyle(wb = workBook, + dataFormat = xlsx::DataFormat(""#,##0.00"")) + header0 <- rep("""", 1 + 6 * length(databaseNames)) + header0[2 - 6 + 6 * (1:length(databaseNames))] <- + databaseNames + xlsx::addDataFrame( + as.data.frame(t(header0)), + sheet = sheet, + startRow = 1, + startColumn = 1, + col.names = FALSE, + row.names = FALSE, + showNA = FALSE + ) + for (k in 1:length(databaseNames)) { + xlsx::addMergedRegion( + sheet, + startRow = 1, + endRow = 1, + startColumn = (k - 1) * 6 + 2, + endColumn = (k - 1) * 6 + 7 + ) + } + header1 <- + c("""", rep( + c(""Before matching"", """", """", ""After matching"", """", """"), + length(databaseNames) + )) + xlsx::addDataFrame( + as.data.frame(t(header1)), + sheet = sheet, + startRow = 2, + startColumn = 1, + col.names = FALSE, + row.names = FALSE, + showNA = FALSE + ) + for (k in 1:length(databaseNames)) { + addMergedRegion( + sheet, + startRow = 2, + endRow = 2, + startColumn = (k - 1) * 6 + 2, + endColumn = (k - 1) * 6 + 4 + ) + addMergedRegion( + sheet, + startRow = 2, + endRow = 2, + startColumn = (k - 1) * 6 + 5, + endColumn = (k - 1) * 6 + 7 + ) + } + header2 <- + c("""", rep(c(""T"", ""c"", """"), 2 * length(databaseNames))) + xlsx::addDataFrame( + as.data.frame(t(header2)), + sheet = sheet, + startRow = 3, + startColumn = 1, + col.names = FALSE, + row.names = FALSE, + showNA = FALSE + ) + xlsx::addDataFrame( + as.data.frame(t(header3)), + sheet = sheet, + startRow = 4, + startColumn = 1, + col.names = FALSE, + row.names = FALSE, + showNA = FALSE + ) + styles <- + rep( + list( + percentStyle, + percentStyle, + diffStyle, + percentStyle, + percentStyle, + diffStyle + ), + length(databaseNames) + ) + names(styles) <- 1 + (1:length(styles)) + xlsx::addDataFrame( + mainTable, + sheet = sheet, + startRow = 5, + startColumn = 1, + col.names = FALSE, + row.names = FALSE, + showNA = FALSE, + colStyle = styles + ) + xlsx::setColumnWidth(sheet, 1, 45) + xlsx::setColumnWidth(sheet, 2:25, 6) + fileName <- + paste0( + ""Chars "", + primaryTcos$targetDrug[i], + ""_"", + primaryTcos$comparatorDrug[i], + ""_all"", + ""_part"", + part, + "".xlsx"" + ) + xlsx::saveWorkbook(workBook, file.path(reportFolder, fileName)) + } + + half <- ceiling(nrow(mainTable) / 2) + createExcelTable(mainTable[1:half,], 1) + createExcelTable(mainTable[(half + 1):nrow(mainTable),], 2) + } + } + } + +prepareTable1 <- function(balance) { + pathToCsv <- + system.file(""settings"", ""Table1Specs.csv"", package = ""AHAsAcutePancreatitis"") + specifications <- read.csv(pathToCsv, stringsAsFactors = FALSE) + + fixCase <- function(label) { + idx <- (toupper(label) == label) + if (any(idx)) { + label[idx] <- paste0(substr(label[idx], 1, 1), + tolower(substr(label[idx], 2, nchar(label[idx])))) + } + return(label) + } + + resultsTable <- data.frame() + for (i in 1:nrow(specifications)) { + if (specifications$analysisId[i] == """") { + resultsTable <- rbind(resultsTable, + data.frame(Characteristic = specifications$label[i], value = """")) + } else { + idx <- balance$analysisId == specifications$analysisId[i] + if (any(idx)) { + if (specifications$covariateIds[i] != """") { + covariateIds <- + as.numeric(strsplit(specifications$covariateIds[i], "","")[[1]]) + idx <- balance$covariateId %in% covariateIds + } else { + covariateIds <- NULL + } + if (any(idx)) { + balanceSubset <- balance[idx,] + if (is.null(covariateIds)) { + balanceSubset <- balanceSubset[order(balanceSubset$covariateId),] + } else { + balanceSubset <- + merge(balanceSubset, + data.frame( + covariateId = covariateIds, + rn = 1:length(covariateIds) + )) + balanceSubset <- balanceSubset[order(balanceSubset$rn, + balanceSubset$covariateId),] + } + balanceSubset$covariateName <- fixCase(gsub(""^.*: "", + """", + balanceSubset$covariateName)) + if (specifications$covariateIds[i] == """" || + length(covariateIds) > 1) { + resultsTable <- + rbind( + resultsTable, + data.frame( + Characteristic = specifications$label[i], + beforeMatchingMeanTreated = NA, + beforeMatchingMeanComparator = NA, + beforeMatchingStdDiff = NA, + afterMatchingMeanTreated = NA, + afterMatchingMeanComparator = NA, + afterMatchingStdDiff = NA, + stringsAsFactors = FALSE + ) + ) + resultsTable <- rbind( + resultsTable, + data.frame( + Characteristic = paste0("" "", balanceSubset$covariateName), + beforeMatchingMeanTreated = balanceSubset$beforeMatchingMeanTreated, + beforeMatchingMeanComparator = balanceSubset$beforeMatchingMeanComparator, + beforeMatchingStdDiff = balanceSubset$beforeMatchingStdDiff, + afterMatchingMeanTreated = balanceSubset$afterMatchingMeanTreated, + afterMatchingMeanComparator = balanceSubset$afterMatchingMeanComparator, + afterMatchingStdDiff = balanceSubset$afterMatchingStdDiff, + stringsAsFactors = FALSE + ) + ) + } else { + resultsTable <- + rbind( + resultsTable, + data.frame( + Characteristic = specifications$label[i], + beforeMatchingMeanTreated = balanceSubset$beforeMatchingMeanTreated, + beforeMatchingMeanComparator = balanceSubset$beforeMatchingMeanComparator, + beforeMatchingStdDiff = balanceSubset$beforeMatchingStdDiff, + afterMatchingMeanTreated = balanceSubset$afterMatchingMeanTreated, + afterMatchingMeanComparator = balanceSubset$afterMatchingMeanComparator, + afterMatchingStdDiff = balanceSubset$afterMatchingStdDiff, + stringsAsFactors = FALSE + ) + ) + } + } + } + } + } + resultsTable$beforeMatchingMeanTreated <- + resultsTable$beforeMatchingMeanTreated * 100 + resultsTable$beforeMatchingMeanComparator <- + resultsTable$beforeMatchingMeanComparator * 100 + resultsTable$afterMatchingMeanTreated <- + resultsTable$afterMatchingMeanTreated * 100 + resultsTable$afterMatchingMeanComparator <- + resultsTable$afterMatchingMeanComparator * 100 + return(resultsTable) +} + +selectKaplanMeierPlots <- + function(outputFolders, databaseNames, reportFolder) { + plotKm <- function(database, outputFolder,analysisId, outcomeId) { + cmOutputFolder <- file.path(outputFolder, ""cmOutput"") + reference <- readRDS(file.path(cmOutputFolder, ""outcomeModelReference.rds"")) + pathToCsv <- system.file(""settings"", ""TcosOfInterest.csv"", package = ""AHAsAcutePancreatitis"") + tcosOfInterest <- read.csv(pathToCsv, stringsAsFactors = FALSE) + + row <- + tcosOfInterest[tcosOfInterest$targetDrug == ""canagliflozin"" & + tcosOfInterest$comparatorDrug == "" DPP-4 inhibitors"" & + tcosOfInterest$canaRestricted == TRUE & + tcosOfInterest$censorAtSwitch == TRUE,] + strataFile <- + reference$strataFile[reference$targetId == row$targetId & + reference$comparatorId == row$comparatorId & + reference$analysisId == analysisId & + reference$outcomeId == outcomeId] + + # remapping of the folder structure was necessary in cases where we were running the analysis across multiple servers + # and then reporting on the results in a consolidated environment. + #strataFile <- gsub(""^[a-zA-Z]:/"", ""s:/"", strataFile) + strata <- readRDS(strataFile) + plot <- CohortMethod::plotKaplanMeier( + strata, + title = database, + treatmentLabel = row$targetDrug, + comparatorLabel = row$comparatorDrug + ) + return(plot) + } + for (outcomeId in c(6479)) { + for (analysisId in c(2, 4)) { + for (i in 1:length(databaseNames)) { + kmPlot <- plotKm( + database = databaseNames[i], + outputFolder = outputFolders[i], + analysisId = analysisId, + outcomeId = outcomeId + ) + + fileName <- paste0( + ""km_"", + if (analysisId == 2) + ""_ontreatment"" + else + ""_intenttotreat"", + ""_o"", + outcomeId, + ""_"", + databaseNames[i], + "".png"" + ) + ggplot2::ggsave( + plot = kmPlot, + filename = file.path(reportFolder, fileName), + width = 13, + height = 9 + ) + } + } + } +} + +createTimeAtRiskTable <- + function(outputFolders, + databaseNames, + reportFolder, + comparisonsOfInterest) { + requireNamespace(""XLConnect"") + loadResultsHois <- function(outputFolder, fileName) { + shinyDataFolder <- file.path(outputFolder, ""results"", ""shinyData"") + file <- + list.files(shinyDataFolder, + pattern = ""resultsHois_.*.rds"", + full.names = TRUE) + x <- readRDS(file) + if (is.null(x$i2)) + x$i2 <- NA + return(x) + } + results <- lapply(outputFolders, loadResultsHois) + results <- do.call(rbind, results) + results <- cleanResults(results) + results$comparison <- + paste(results$targetDrug, results$comparatorDrug, sep = "" - "") + outcomeNames <- unique(results$outcomeName) + + for (outcomeName in outcomeNames) { + fileName <- + file.path(reportFolder, paste0(""TAR "", outcomeName, ""_all"", "".xlsx"")) + unlink(fileName) + wb <- XLConnect::loadWorkbook(fileName, create = TRUE) + XLConnect::createSheet(wb, name = ""Time-at-risk"") + + header0 <- rep("""", 14) + header0[3] <- ""On treatment"" + header0[17] <- ""Intent-to-treat"" + XLConnect::writeWorksheet( + wb, + sheet = ""Time-at-risk"", + data = as.data.frame(t(header0)), + startRow = 1, + startCol = 1, + rownames = FALSE, + header = FALSE + ) + XLConnect::mergeCells(wb, sheet = ""Time-at-risk"", reference = ""C1:P1"") + XLConnect::mergeCells(wb, sheet = ""Time-at-risk"", reference = ""Q1:AD1"") + header1 <- + c( + """", + """", + ""Target"", + """", + """", + """", + """", + """", + """", + ""Comparator"", + """", + """", + """", + """", + """", + """", + ""Target"", + """", + """", + """", + """", + """", + """", + ""Comparator"", + """", + """", + """", + """", + """", + """" + ) + XLConnect::writeWorksheet( + wb, + sheet = ""Time-at-risk"", + data = as.data.frame(t(header1)), + startRow = 2, + startCol = 1, + rownames = FALSE, + header = FALSE + ) + XLConnect::mergeCells(wb, sheet = ""Time-at-risk"", reference = ""C2:I2"") + XLConnect::mergeCells(wb, sheet = ""Time-at-risk"", reference = ""J2:P2"") + XLConnect::mergeCells(wb, sheet = ""Time-at-risk"", reference = ""Q2:W2"") + XLConnect::mergeCells(wb, sheet = ""Time-at-risk"", reference = ""X2:AD2"") + header2 <- c( + ""Question"", + ""Source"", + ""Mean"", + ""SD"", + ""Min"", + ""P25"", + ""Med"", + ""P75"", + ""Max"", + ""Mean"", + ""SD"", + ""Min"", + ""P25"", + ""Med"", + ""P75"", + ""Max"", + ""Mean"", + ""SD"", + ""Min"", + ""P25"", + ""Med"", + ""P75"", + ""Max"", + ""Mean"", + ""SD"", + ""Min"", + ""P25"", + ""Med"", + ""P75"", + ""Max"" + ) + XLConnect::writeWorksheet( + wb, + sheet = ""Time-at-risk"", + data = as.data.frame(t(header2)), + startRow = 3, + startCol = 1, + rownames = FALSE, + header = FALSE + ) + + idx <- results$outcomeName == outcomeName & + results$comparison %in% comparisonsOfInterest & + results$psStrategy == ""Matching"" & + results$noCana == TRUE & + results$noCensor == FALSE & + results$eventType == ""First Post Index Event"" + + results$dbOrder <- + match(results$database, c(""CCAE"", ""MDCR"", ""Optum"")) + results$comparisonOrder <- + match(results$comparison, comparisonsOfInterest) + onTreatment <- + results[idx & results$timeAtRisk == ""On Treatment (30 Day)"",] + itt <- + results[idx & results$timeAtRisk == ""Intent to Treat"",] + onTreatment <- onTreatment[order(onTreatment$comparisonOrder, + onTreatment$dbOrder),] + itt <- itt[order(itt$comparisonOrder, + itt$dbOrder),] + if (!all.equal(onTreatment$comparison, itt$comparison) || + !all.equal(onTreatment$database, itt$database)) { + stop(""Problem with sorting of data"") + } + formatDays <- function(days) { + formatC(days, big.mark = "","", format = ""d"") + } + formatMeanSd <- function(days) { + formatC(days, digits = 1, format = ""f"") + } + formatQuestion <- function(x) { + result <- x + return(result) + } + + mainTable <- + data.frame( + question = formatQuestion(onTreatment$comparison), + source = onTreatment$database, + meanTOnTreatment = onTreatment$tarTargetMean, + sdTOnTreatment = onTreatment$tarTargetSd, + minTOnTreatment = onTreatment$tarTargetMin, + p25TOnTreatment = onTreatment$tarTargetP25, + medianTOnTreatment = onTreatment$tarTargetMedian, + p75TOnTreatment = onTreatment$tarTargetP75, + maxTOnTreatment = onTreatment$tarTargetMax, + meanCOnTreatment = onTreatment$tarComparatorMean, + sdCOnTreatment = onTreatment$tarComparatorSd, + minCOnTreatment = onTreatment$tarComparatorMin, + p25COnTreatment = onTreatment$tarComparatorP25, + medianCOnTreatment = onTreatment$tarComparatorMedian, + p75COnTreatment = onTreatment$tarComparatorP75, + maxCOnTreatment = onTreatment$tarComparatorMax, + meanTItt = itt$tarTargetMean, + sdTItt = itt$tarTargetSd, + minTItt = itt$tarTargetMin, + p25TItt = itt$tarTargetP25, + medianTItt = itt$tarTargetMedian, + p75TItt = itt$tarTargetP75, + maxTItt = itt$tarTargetMax, + meanCItt = itt$tarComparatorMean, + sdCItt = itt$tarComparatorSd, + minCItt = itt$tarComparatorMin, + p25CItt = itt$tarComparatorP25, + medianCItt = itt$tarComparatorMedian, + p75CItt = itt$tarComparatorP75, + maxCItt = itt$tarComparatorMax + ) + XLConnect::writeWorksheet( + wb, + data = mainTable, + sheet = ""Time-at-risk"", + startRow = 4, + startCol = 1, + header = FALSE, + rownames = FALSE + ) + pStyle <- XLConnect::createCellStyle(wb) + XLConnect::setDataFormat(pStyle, format = ""#,##0.0"") + countStyle <- XLConnect::createCellStyle(wb) + XLConnect::setDataFormat(countStyle, format = ""#,##0"") + XLConnect::setCellStyle( + wb, + sheet = ""Time-at-risk"", + row = 4:19, + col = rep(3, 19), + cellstyle = pStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Time-at-risk"", + row = 4:19, + col = rep(4, 19), + cellstyle = pStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Time-at-risk"", + row = 4:19, + col = rep(5, 19), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Time-at-risk"", + row = 4:19, + col = rep(6, 19), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Time-at-risk"", + row = 4:19, + col = rep(7, 19), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Time-at-risk"", + row = 4:19, + col = rep(8, 19), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Time-at-risk"", + row = 4:19, + col = rep(9, 19), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Time-at-risk"", + row = 4:19, + col = rep(10, 19), + cellstyle = pStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Time-at-risk"", + row = 4:19, + col = rep(11, 19), + cellstyle = pStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Time-at-risk"", + row = 4:19, + col = rep(12, 19), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Time-at-risk"", + row = 4:19, + col = rep(13, 19), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Time-at-risk"", + row = 4:19, + col = rep(14, 19), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Time-at-risk"", + row = 4:19, + col = rep(15, 19), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Time-at-risk"", + row = 4:19, + col = rep(16, 19), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Time-at-risk"", + row = 4:19, + col = rep(17, 19), + cellstyle = pStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Time-at-risk"", + row = 4:19, + col = rep(18, 19), + cellstyle = pStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Time-at-risk"", + row = 4:19, + col = rep(19, 19), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Time-at-risk"", + row = 4:19, + col = rep(20, 19), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Time-at-risk"", + row = 4:19, + col = rep(21, 19), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Time-at-risk"", + row = 4:19, + col = rep(22, 19), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Time-at-risk"", + row = 4:19, + col = rep(23, 19), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Time-at-risk"", + row = 4:19, + col = rep(24, 19), + cellstyle = pStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Time-at-risk"", + row = 4:19, + col = rep(25, 19), + cellstyle = pStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Time-at-risk"", + row = 4:19, + col = rep(26, 19), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Time-at-risk"", + row = 4:19, + col = rep(27, 19), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Time-at-risk"", + row = 4:19, + col = rep(28, 19), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Time-at-risk"", + row = 4:19, + col = rep(29, 19), + cellstyle = countStyle + ) + XLConnect::setCellStyle( + wb, + sheet = ""Time-at-risk"", + row = 4:19, + col = rep(30, 19), + cellstyle = countStyle + ) + XLConnect::setColumnWidth(wb, + sheet = ""Time-at-risk"", + column = 1, + width = -1) + XLConnect::setColumnWidth(wb, + sheet = ""Time-at-risk"", + column = 2, + width = -1) + XLConnect::saveWorkbook(wb) + } + }","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iAcutePancreatitis/extras/PackageMaintenance.R",".R","5813","128","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# 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. + +# Format and check code --------------------------------------------------- +OhdsiRTools::formatRFolder() +OhdsiRTools::checkUsagePackage(""AHAsAcutePancreatitis"") +OhdsiRTools::updateCopyrightYearFolder() + +# Create manual ----------------------------------------------------------- +shell(""rm extras/AHAsAcutePancreatitis"") +shell(""R CMD Rd2pdf ./ --output=extras/AHAsAcutePancreatitis"") + +baseUrl <- """" + +# Insert cohort definitions from ATLAS into package ----------------------- +OhdsiRTools::insertCohortDefinitionSetInPackage(fileName = ""ConfigCohortsToCreate.csv"", + baseUrl = baseUrl, + insertTableSql = TRUE, + insertCohortCreationR = TRUE, + generateStats = FALSE, + packageName = ""AHAsAcutePancreatitis"") + + + +# Create exposure cohorts without censoring by modifying cohorts with censoring ---------------- +tcos <- read.csv(""inst/settings/ConfigTcosOfInterest.csv"", stringsAsFactors = FALSE) +cohorts <- read.csv(""inst/settings/CohortsToCreateWithCensoring.csv"", stringsAsFactors = FALSE) +exposureCohortIds <- unique(c(tcos$targetId, tcos$comparatorId)) +newCohorts <- list(cohorts) +for (exposureCohortId in exposureCohortIds) { + cohort <- cohorts[cohorts$cohortId == exposureCohortId, ] + writeLines(paste(""Dropping censoring criteria for"", cohort$fullName)) + cohortDef <- RJSONIO::fromJSON(file.path(""inst"", ""cohorts"", paste0(cohort$name, "".json""))) + + cohort$cohortId <- exposureCohortId + 10000 + cohort$atlasId <- NA + cohort$name <- paste0(cohort$name, ""NoCensor"") + cohort$fullName <- paste0(cohort$fullName, "", no censoring"") + newCohorts[[length(newCohorts) + 1]] <- cohort + + # Drop censoring criteria + cohortDef$CensoringCriteria <- NULL + fileConn <- file(file.path(""inst/cohorts"", paste(cohort$name, ""json"", sep = "".""))) + writeLines(RJSONIO::toJSON(cohortDef), fileConn) + close(fileConn) + jsonBody <- RJSONIO::toJSON(list(expression = cohortDef), digits = 23) + httpheader <- c(Accept = ""application/json; charset=UTF-8"", `Content-Type` = ""application/json"") + url <- paste(baseUrl, ""cohortdefinition"", ""sql"", sep = ""/"") + cohortSqlJson <- httr::POST(url, body = jsonBody, config = httr::add_headers(httpheader)) + cohortSqlJson <- httr::content(cohortSqlJson) + sql <- cohortSqlJson$templateSql + fileConn <- file(file.path(""inst/sql/sql_server"", paste(cohort$name, ""sql"", sep = "".""))) + writeLines(sql, fileConn) + close(fileConn) +} + +# add the no censor cohorts +cohorts <- do.call(rbind, newCohorts) + +# add censor cohorts +newTcos <- tcos +newTcos$targetId <- 10000 + newTcos$targetId +newTcos$comparatorId <- 10000 + newTcos$comparatorId +newTcos$targetName <- paste0(newTcos$targetName, "", no censoring"") +newTcos$comparatorName <- paste0(newTcos$comparatorName, "", no censoring"") +newTcos$censorAtSwitch <- FALSE +tcos$censorAtSwitch <- TRUE +tcos <- rbind(tcos, newTcos) + +# create no cana entries but the cohorts will be created by a sql script +exposureCohortIds <- unique(c(tcos$targetId, tcos$comparatorId)) +newCohorts <- list(cohorts) +for (exposureCohortId in exposureCohortIds) { + cohort <- cohorts[cohorts$cohortId == exposureCohortId, ] + noCanaCohort <- cohort + noCanaCohort$cohortId <- exposureCohortId + 100000 + noCanaCohort$atlasId <- NA + noCanaCohort$name <- paste0(cohort$name, ""NoCana"") + noCanaCohort$fullName <- paste0(cohort$fullName, "", no cana"") + newCohorts[[length(newCohorts) + 1]] <- noCanaCohort +} + +cohorts <- do.call(rbind, newCohorts) +write.csv(cohorts, ""inst/settings/CohortsToCreate.csv"", row.names = FALSE) + +# add cana restricted cohorts +newTcos <- tcos +newTcos$targetId <- 100000 + newTcos$targetId +newTcos$comparatorId <- 100000 + newTcos$comparatorId +newTcos$targetName <- paste0(newTcos$targetName, "", no cana"") +newTcos$comparatorName <- paste0(newTcos$comparatorName, "", no cana"") +newTcos$canaRestricted <- TRUE +tcos$canaRestricted <- FALSE +newTcos[which(newTcos$targetId==106492),]$targetName <- 'Canagliflozin new users' +newTcos[which(newTcos$targetId==106492),]$targetId <- 6492 +newTcos[which(newTcos$targetId==116492),]$targetName <- 'Canagliflozin new users, no censoring' +newTcos[which(newTcos$targetId==116492),]$targetId <- 16492 +tcos <- rbind(tcos, newTcos) + +write.csv(tcos, ""inst/settings/TcosOfInterest.csv"", row.names = FALSE) + +# Create analysis details ------------------------------------------------- +source(""R/CreateStudyAnalysisDetails.R"") +createAnalysesDetails(""inst/settings/"") + +# Store environment in which the study was executed ----------------------- +OhdsiRTools::insertEnvironmentSnapshotInPackage(""AHAsAcutePancreatitis"") + +# low population counts were identified by the cohort counts and removed to prevent package failure during execution due to insufficient sample. +removeLowPopulationTcos <- function() { + tcos <- read.csv(""inst/settings/TcosOfInterest.csv"", stringsAsFactors = FALSE) + tcos <- tcos[! tcos$comparatorId %in% c(6519,6517,106517,116517,16517,106519,16519,116519,6518,116518,16518,106518),] + write.csv(tcos, ""inst/settings/TcosOfInterest.csv"", row.names = FALSE) +} + + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iAcutePancreatitis/extras/EvaluateTimeAtRiskWithoutCensorAtSwitch.R",".R","6243","128","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# 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. + +cohortTable2 <- paste0(cohortTable, ""_noCensor"") +noCensorFolder <- file.path(outputFolder, ""noCensor"") + +if (!file.exists(noCensorFolder)) + dir.create(noCensorFolder) + +pathToCsv <- system.file(""settings"", ""TcosOfInterest.csv"", package = ""AHAsAcutePancreatitis"") +tcosOfInterest <- read.csv(pathToCsv, stringsAsFactors = FALSE) +cohortIds <- unique(c(tcosOfInterest$targetId, tcosOfInterest$comparatorId)) + +pathToCsv <- system.file(""settings"", ""CohortsToCreate.csv"", package = ""AHAsAcutePancreatitis"") +cohortsToCreate <- read.csv(pathToCsv, stringsAsFactors = FALSE) +cohortsToCreate <- cohortsToCreate[cohortsToCreate$cohortId %in% cohortIds, ] + +# Create new cohort table with modified cohorts ----------------------------------------------- +connection <- DatabaseConnector::connect(connectionDetails) +sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""CreateCohortTable.sql"", + packageName = ""AHAsAcutePancreatitis"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + cohort_database_schema = cohortDatabaseSchema, + cohort_table = cohortTable2) +DatabaseConnector::executeSql(connection, sql, progressBar = FALSE, reportOverallTime = FALSE) + +# baseUrl = Sys.getenv(""baseUrl"") +# definitionId <- cohortsToCreate$atlasId[1] +# cohortId <- cohortsToCreate$cohortId[1] +createModifiedCohortDefinition <- function(definitionId, + cohortId, + baseUrl, + connection, + cdmDatabaseSchema, + oracleTempSchema, + cohortDatabaseSchema, + cohortTable2) { + ### Fetch JSON object ### + url <- paste(baseUrl, ""cohortdefinition"", definitionId, sep = ""/"") + json <- httr::GET(url) + json <- httr::content(json) + name <- json$name + parsedExpression <- RJSONIO::fromJSON(json$expression) + + # Drop censoring criteria + parsedExpression$CensoringCriteria <- NULL + + ### Fetch SQL by posting JSON object ### + jsonBody <- RJSONIO::toJSON(list(expression = parsedExpression), digits = 23) + httpheader <- c(Accept = ""application/json; charset=UTF-8"", `Content-Type` = ""application/json"") + url <- paste(baseUrl, ""cohortdefinition"", ""sql"", sep = ""/"") + cohortSqlJson <- httr::POST(url, body = jsonBody, config = httr::add_headers(httpheader)) + cohortSqlJson <- httr::content(cohortSqlJson) + sql <- cohortSqlJson$templateSql + sql <- SqlRender::renderSql(sql = sql, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = cohortDatabaseSchema, + target_cohort_table = cohortTable2, + target_cohort_id = cohortId)$sql + sql <- SqlRender::translateSql(sql, + targetDialect = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema)$sql + DatabaseConnector::executeSql(connection, sql) +} + +for (i in 1:nrow(cohortsToCreate)) { + writeLines(paste(""Creating modified cohort"", cohortsToCreate$name[i])) + createModifiedCohortDefinition(definitionId = cohortsToCreate$atlasId[i], + cohortId = cohortsToCreate$cohortId[i], + baseUrl = Sys.getenv(""baseUrl""), + connection = connection, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable2 = cohortTable2) +} +DatabaseConnector::disconnect(connection) + +# Get cohort statistics ----------------------------------------------- +connection <- DatabaseConnector::connect(connectionDetails) +templateSql <- ""SELECT DATEDIFF(DAY, cohort_start_date, cohort_end_date) AS days FROM @cohort_database_schema.@cohort_table WHERE cohort_definition_id = @cohort_id"" +results <- data.frame(cohortId = rep(cohortsToCreate$atlasId, 2), + cohortName = rep(cohortsToCreate$fullName, 2), + type = rep(c(""Modified"", ""Original""), each = nrow(cohortsToCreate))) + +for (i in 1:nrow(results)) { + if (results$type[i] == ""Original"") { + table <- cohortTable + } else { + table <- cohortTable2 + } + sql <- SqlRender::renderSql(sql = templateSql, + cohort_database_schema = cohortDatabaseSchema, + cohort_table = table, + cohort_id = results$cohortId[i])$sql + sql <- SqlRender::translateSql(sql, + targetDialect = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema)$sql + days <- DatabaseConnector::querySql(connection, sql) + days <- days$DAYS + q <- quantile(days, c(0, 0.1, 0.25, 0.5, 0.75, 0.9, 1)) + results$count[i] <- length(days) + results$mean[i] <- mean(days) + results$sd[i] <- sd(days) + results$min[i] <- q[1] + results$p10[i] <- q[2] + results$p25[i] <- q[3] + results$median[i] <- q[4] + results$p50[i] <- q[5] + results$p90[i] <- q[6] + results$max[i] <- q[7] +} +DatabaseConnector::disconnect(connection) + +write.csv(results, file.path(noCensorFolder, ""tarDist.csv""), row.names = FALSE) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iAcutePancreatitis/extras/InstallPackages.R",".R","420","11","install.packages(""devtools"") +install.packages(""rJava"") +library(""rJava"") +devtools::install_github(""ohdsi/SqlRender"") +devtools::install_github(""ohdsi/DatabaseConnector"") +devtools::install_github(""ohdsi/EmpiricalCalibration"") +devtools::install_github(""ohdsi/OhdsiRTools"") +devtools::install_github(""ohdsi/FeatureExtraction"") +devtools::install_github(""ohdsi/CohortMethod"") +devtools::install_github(""ohdsi/EvidenceSynthesis"") +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iAcutePancreatitis/extras/CodeToRun.R",".R","4536","101","library(AHAsAcutePancreatitis) +options(fftempdir = ""D:/FFtemp"") + +maxCores <- parallel::detectCores()-1 +studyFolder <- ""D:/Studies/EPI534"" +dbms <- """" +server <- """" +port <- """" +oracleTempSchema <- NULL +connectionDetails <- DatabaseConnector::createConnectionDetails(dbms = dbms, + server = server, + port = port) + +# MDCR settings ---------------------------------------------------------------- +cdmDatabaseSchema <- ""cdm_truven_mdcr_v698.dbo"" +cohortDatabaseSchema <- ""scratch.dbo"" +cohortTable <- ""EPI534_MDCR"" +databaseName <- ""MDCR"" +outputFolder <- file.path(studyFolder, ""mdcr"") + +# CCAE settings ---------------------------------------------------------------- +cdmDatabaseSchema <- ""cdm_truven_ccae_v697.dbo"" +cohortDatabaseSchema <- ""scratch.dbo"" +cohortTable <- ""EPI534_CCAE"" +databaseName <- ""CCAE"" +outputFolder <- file.path(studyFolder, ""ccae"") + +# Optum settings ---------------------------------------------------------------- +cdmDatabaseSchema <- ""cdm_optum_extended_ses_v694.dbo"" +cohortDatabaseSchema <- ""scratch.dbo"" +cohortTable <- ""EPI534_OPTUM"" +databaseName <- ""Optum"" +outputFolder <- file.path(studyFolder, ""optum"") + +execute(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder, + databaseName = databaseName, + createCohorts = FALSE, + runAnalyses = FALSE, + getPriorExposureData = FALSE, + runDiagnostics = FALSE, + prepareResults = FALSE, + maxCores = maxCores) + +# run queries to create our additional cohorts here... + +# cana restricted cohorts - the protocol calls for comparator cohorts to exclude cana exposed people +sql <- SqlRender::loadRenderTranslateSql(""CreateCanaRestrictedCohorts.sql"", + ""AHAsAcutePancreatitis"", + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable) + +connection <- DatabaseConnector::connect(connectionDetails) +DatabaseConnector::executeSql(connection, sql) + +# metformin add-on therapy - the protocol calls for a sensitivity analysis with required prior metformin +sql <- SqlRender::loadRenderTranslateSql(""ManuallyCreateMetforminAddOnCohorts.sql"", + ""AHAsAcutePancreatitis"", + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable) + +connection <- DatabaseConnector::connect(connectionDetails) +DatabaseConnector::executeSql(connection, sql) +# +# # required prior ap - the protocol calls for a sensitivity analysis with required prior AP +sql <- SqlRender::loadRenderTranslateSql(""ManuallyCreatePriorAPCohorts.sql"", + ""AHAsAcutePancreatitis"", + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable) + +connection <- DatabaseConnector::connect(connectionDetails) +DatabaseConnector::executeSql(connection, sql) + +execute(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder, + databaseName = databaseName, + createCohorts = F, + runAnalyses = F, + getPriorExposureData = F, + runDiagnostics = F, + prepareResults = T, + maxCores = 1) + +AHAsAcutePancreatitis::createTableAndFiguresForReport(outputFolders = c(file.path(studyFolder, ""ccae""), + file.path(studyFolder, ""mdcr""), + file.path(studyFolder, ""optum"")), + databaseNames = c(""CCAE"", ""MDCR"", ""Optum""), + maOutputFolder = file.path(studyFolder, ""metaAnalysis""), + reportFolder = file.path(studyFolder, ""report"")) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iAcutePancreatitis/extras/CopyCensoredToUncensoredDataObjects.R",".R","2617","50","# This code generates CohortMethod data objects for cohorts without censoring by modifying objects for cohorts with censoring + +cmOutputFolder <- file.path(outputFolder, ""cmOutput"") + +connection <- DatabaseConnector::connect(connectionDetails) +tcos <- read.csv(""inst/settings/TcosOfInterest.csv"", stringsAsFactors = FALSE) +tcosWithCensoring <- tcos[tcos$censorAtSwitch, ] +for (i in 1:nrow(tcosWithCensoring)) { + targetId <- tcosWithCensoring$targetId[i] + comparatorId <- tcosWithCensoring$comparatorId[i] + newTargetId <- 10000 + targetId + newComparatorId <- 10000 + comparatorId + + # Copy cohortMethodData object ------------------------------------------------------------------- + sourceFileName <- file.path(cmOutputFolder, sprintf(""CmData_l1_t%s_c%s"", targetId, comparatorId)) + cmData <- CohortMethod::loadCohortMethodData(sourceFileName) + sql <- ""SELECT subject_id, + cohort_start_date, + DATEDIFF(DAY, cohort_start_date, cohort_end_date) AS days_to_cohort_end, + CASE WHEN cohort_definition_id = @target_id THEN 1 ELSE 0 END AS treatment + FROM @cohort_database_schema.@cohort_table + WHERE cohort_definition_id IN (@target_id, @comparator_id)"" + sql <- SqlRender::renderSql(sql = sql, + cohort_database_schema = cohortDatabaseSchema, + cohort_table = cohortTable, + target_id = newTargetId, + comparator_id = newComparatorId)$sql + sql <- SqlRender::translateSql(sql = sql, targetDialect = connectionDetails$dbms, oracleTempSchema = oracleTempSchema)$sql + newCohorts <- DatabaseConnector::querySql(connection, sql) + colnames(newCohorts) <- SqlRender::snakeCaseToCamelCase(colnames(newCohorts)) + cmData$cohorts$daysToCohortEnd <- NULL + cmData$cohorts <- merge(cmData$cohorts, newCohorts, all.x = TRUE) + if (any(is.na(cmData$cohorts$daysToCohortEnd))) + stop(""Cohort mismatch"") + targetFileName <- file.path(cmOutputFolder, sprintf(""CmData_l1_t%s_c%s"", newTargetId, newComparatorId)) + CohortMethod::saveCohortMethodData(cmData, targetFileName) + writeLines(paste(""Created object"", targetFileName)) + + # Copy shared PS object -------------------------------------------------------------------------- + sourceFileName <- file.path(cmOutputFolder, sprintf(""Ps_l1_p1_t%s_c%s.rds"", targetId, comparatorId)) + ps <- readRDS(sourceFileName) + targetFileName <- file.path(cmOutputFolder, sprintf(""Ps_l1_p1_t%s_c%s.rds"", newTargetId, newComparatorId)) + saveRDS(ps, targetFileName) + writeLines(paste(""Created object"", targetFileName)) +} + +DatabaseConnector::disconnect(connection) + + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iAcutePancreatitis/extras/CrudeIRFinal.R",".R","16109","267","studyFolder <- ""D:/Studies/EPI534"" +reportFolder = file.path(studyFolder, ""report"") + +drugsOfInterest <- c( + "" GLP-1 inhibitors"", + "" DPP-4 inhibitors"", + ""Sulfonylurea"", + ""TZD"", + ""Insulin new users"", + ""Other AHA"" +) + +#Read in the results tables + +optumResults <- readRDS( ""D:/Studies/EPI534/optum/results/shinyData/resultsHois_optum.rds"") +mdcrResults <- readRDS( ""D:/Studies/EPI534/mdcr/results/shinyData/resultsHois_mdcr.rds"") +ccaeResults <- readRDS( ""D:/Studies/EPI534/ccae/results/shinyData/resultsHois_ccae.rds"") + + +############################################################################### +# ccae Incidence table +############################################################################### + +##For the Comparator + +ccaeResultsIRSubsetITTComparator <-subset(ccaeResults, ccaeResults$outcomeName == "" Acute Pancreatitis"" & + ccaeResults$timeAtRisk == ""Intent to Treat"" & + ccaeResults$canaRestricted == ""TRUE"" & + ccaeResults$eventType == ""First Post Index Event"" & + ccaeResults$psStrategy == ""Stratification"" & + ccaeResults$targetName == ""Canagliflozin new users"" & + ccaeResults$comparatorDrug %in% drugsOfInterest, + select=c(timeAtRisk,comparatorDrug,comparator, comparatorDays, eventsComparator)) + +ccaeResultsIRSubsetITTComparator<-plyr::rename(ccaeResultsIRSubsetITTComparator, replace = c(""timeAtRisk""=""Time At Risk"", ""comparatorDrug"" = ""Drug"",""comparator"" = ""Persons"", + ""comparatorDays""=""personDays"",""eventsComparator""=""Events"")) + +ccaeResultsIRSubsetOTComparator <-subset(ccaeResults, ccaeResults$outcomeName == "" Acute Pancreatitis"" & + ccaeResults$timeAtRisk == ""On Treatment"" & + ccaeResults$canaRestricted == ""TRUE"" & + ccaeResults$eventType == ""First Post Index Event"" & + ccaeResults$psStrategy == ""Stratification"" & + ccaeResults$targetName == ""Canagliflozin new users"" & + ccaeResults$comparatorDrug %in% drugsOfInterest, + select=c( timeAtRisk,comparatorDrug,comparator, comparatorDays, eventsComparator)) + +ccaeResultsIRSubsetOTComparator<-plyr::rename(ccaeResultsIRSubsetOTComparator, replace = c(""timeAtRisk""=""Time At Risk"", ""comparatorDrug"" = ""Drug"",""comparator"" = ""Persons"", + ""comparatorDays""=""personDays"",""eventsComparator""=""Events"")) + + + +ccaeResultsIRSubsetComparator<-rbind(ccaeResultsIRSubsetITTComparator, ccaeResultsIRSubsetOTComparator) + + + +###For the Target + +#Intent to treat + +ccaeResultsIRSubsetITTTarget <-subset(ccaeResults, ccaeResults$outcomeName == "" Acute Pancreatitis"" & + ccaeResults$timeAtRisk == ""Intent to Treat"" & + ccaeResults$canaRestricted == ""TRUE"" & + ccaeResults$eventType == ""First Post Index Event"" & + ccaeResults$psStrategy == ""Stratification"" & + ccaeResults$targetName == ""Canagliflozin new users"" & + ccaeResults$comparatorDrug =="" GLP-1 inhibitors"", + select=c(timeAtRisk, targetDrug, treated, treatedDays, eventsTreated)) + + +ccaeResultsIRSubsetITTTarget<-plyr::rename(ccaeResultsIRSubsetITTTarget, replace = c(""timeAtRisk""=""Time At Risk"", ""targetDrug"" = ""Drug"",""treated"" = ""Persons"", + ""treatedDays""=""personDays"",""eventsTreated""=""Events"")) + +#On treatment + +ccaeResultsIRSubsetOTTarget <-subset(ccaeResults, ccaeResults$outcomeName == "" Acute Pancreatitis"" & + ccaeResults$timeAtRisk == ""On Treatment"" & + ccaeResults$canaRestricted == ""TRUE"" & + ccaeResults$eventType == ""First Post Index Event"" & + ccaeResults$psStrategy == ""Stratification"" & + ccaeResults$targetName == ""Canagliflozin new users"" & + ccaeResults$comparatorDrug =="" GLP-1 inhibitors"", + select=c(timeAtRisk, targetDrug, treated, treatedDays, eventsTreated)) + +ccaeResultsIRSubsetOTTarget<-plyr::rename(ccaeResultsIRSubsetOTTarget, replace = c(""timeAtRisk""=""Time At Risk"", ""targetDrug"" = ""Drug"",""treated"" = ""Persons"", + ""treatedDays""=""personDays"",""eventsTreated""=""Events"")) + +ccaeResultsIRSubsetTreated<-rbind(ccaeResultsIRSubsetITTTarget, ccaeResultsIRSubsetOTTarget) + + +#Combining Target and Comparator IRs + +ccaeResultsIRSubset<-rbind(ccaeResultsIRSubsetTreated, ccaeResultsIRSubsetComparator) + +ccaeResultsIRSubset$PersonYears<-round(ccaeResultsIRSubset$personDays/365.25, digits=2) +ccaeResultsIRSubset$IR_per_1000<-round((ccaeResultsIRSubset$Events/ccaeResultsIRSubset$PersonYears)*1000, digits=2) + + +database<-c(""ccae"") +ccaeResultsIRSubset <- rbind(database,ccaeResultsIRSubset) + +############################################################################### +#MDCR Incidence table + +##For the Comparator + +mdcrResultsIRSubsetITTComparator <-subset(mdcrResults, mdcrResults$outcomeName == "" Acute Pancreatitis"" & + mdcrResults$timeAtRisk == ""Intent to Treat"" & + mdcrResults$canaRestricted == ""TRUE"" & + mdcrResults$eventType == ""First Post Index Event"" & + mdcrResults$psStrategy == ""Stratification"" & + mdcrResults$targetName == ""Canagliflozin new users"" & + mdcrResults$comparatorDrug %in% drugsOfInterest, + select=c(timeAtRisk,comparatorDrug,comparator, comparatorDays, eventsComparator)) + +mdcrResultsIRSubsetITTComparator<-plyr::rename(mdcrResultsIRSubsetITTComparator, replace = c(""timeAtRisk""=""Time At Risk"", ""comparatorDrug"" = ""Drug"",""comparator"" = ""Persons"", + ""comparatorDays""=""personDays"",""eventsComparator""=""Events"")) + +mdcrResultsIRSubsetOTComparator <-subset(mdcrResults, mdcrResults$outcomeName == "" Acute Pancreatitis"" & + mdcrResults$timeAtRisk == ""On Treatment"" & + mdcrResults$canaRestricted == ""TRUE"" & + mdcrResults$eventType == ""First Post Index Event"" & + mdcrResults$psStrategy == ""Stratification"" & + mdcrResults$targetName == ""Canagliflozin new users"" & + mdcrResults$comparatorDrug %in% drugsOfInterest, + select=c( timeAtRisk,comparatorDrug,comparator, comparatorDays, eventsComparator)) + +mdcrResultsIRSubsetOTComparator<-plyr::rename(mdcrResultsIRSubsetOTComparator, replace = c(""timeAtRisk""=""Time At Risk"", ""comparatorDrug"" = ""Drug"",""comparator"" = ""Persons"", + ""comparatorDays""=""personDays"",""eventsComparator""=""Events"")) + + + +mdcrResultsIRSubsetComparator<-rbind(mdcrResultsIRSubsetITTComparator, mdcrResultsIRSubsetOTComparator) + + + +###For the Target + +#Intent to treat + +mdcrResultsIRSubsetITTTarget <-subset(mdcrResults, mdcrResults$outcomeName == "" Acute Pancreatitis"" & + mdcrResults$timeAtRisk == ""Intent to Treat"" & + mdcrResults$canaRestricted == ""TRUE"" & + mdcrResults$eventType == ""First Post Index Event"" & + mdcrResults$psStrategy == ""Stratification"" & + mdcrResults$targetName == ""Canagliflozin new users"" & + mdcrResults$comparatorDrug =="" GLP-1 inhibitors"", + select=c(timeAtRisk, targetDrug, treated, treatedDays, eventsTreated)) + + +mdcrResultsIRSubsetITTTarget<-plyr::rename(mdcrResultsIRSubsetITTTarget, replace = c(""timeAtRisk""=""Time At Risk"", ""targetDrug"" = ""Drug"",""treated"" = ""Persons"", + ""treatedDays""=""personDays"",""eventsTreated""=""Events"")) + +#On treatment + +mdcrResultsIRSubsetOTTarget <-subset(mdcrResults, mdcrResults$outcomeName == "" Acute Pancreatitis"" & + mdcrResults$timeAtRisk == ""On Treatment"" & + mdcrResults$canaRestricted == ""TRUE"" & + mdcrResults$eventType == ""First Post Index Event"" & + mdcrResults$psStrategy == ""Stratification"" & + mdcrResults$targetName == ""Canagliflozin new users"" & + mdcrResults$comparatorDrug =="" GLP-1 inhibitors"", + select=c(timeAtRisk, targetDrug, treated, treatedDays, eventsTreated)) + +mdcrResultsIRSubsetOTTarget<-plyr::rename(mdcrResultsIRSubsetOTTarget, replace = c(""timeAtRisk""=""Time At Risk"", ""targetDrug"" = ""Drug"",""treated"" = ""Persons"", + ""treatedDays""=""personDays"",""eventsTreated""=""Events"")) + +mdcrResultsIRSubsetTreated<-rbind(mdcrResultsIRSubsetITTTarget, mdcrResultsIRSubsetOTTarget) + + +#Combining Target and Comparator IRs + +mdcrResultsIRSubset<-rbind(mdcrResultsIRSubsetTreated, mdcrResultsIRSubsetComparator) + +mdcrResultsIRSubset$PersonYears<-round(mdcrResultsIRSubset$personDays/365.25, digits=2) +mdcrResultsIRSubset$IR_per_1000<-round((mdcrResultsIRSubset$Events/mdcrResultsIRSubset$PersonYears)*1000, digits=2) + + +database<-c(""mdcr"") +mdcrResultsIRSubset <- rbind(database,mdcrResultsIRSubset) + +############################################################################### +#Optum Incidence table + +##For the Comparator + +optumResultsIRSubsetITTComparator <-subset(optumResults, optumResults$outcomeName == "" Acute Pancreatitis"" & + optumResults$timeAtRisk == ""Intent to Treat"" & + optumResults$canaRestricted == ""TRUE"" & + optumResults$eventType == ""First Post Index Event"" & + optumResults$psStrategy == ""Stratification"" & + optumResults$targetName == ""Canagliflozin new users"" & + optumResults$comparatorDrug %in% drugsOfInterest, + select=c(timeAtRisk,comparatorDrug,comparator, comparatorDays, eventsComparator)) + +optumResultsIRSubsetITTComparator<-plyr::rename(optumResultsIRSubsetITTComparator, replace = c(""timeAtRisk""=""Time At Risk"", ""comparatorDrug"" = ""Drug"",""comparator"" = ""Persons"", + ""comparatorDays""=""personDays"",""eventsComparator""=""Events"")) + +optumResultsIRSubsetOTComparator <-subset(optumResults, optumResults$outcomeName == "" Acute Pancreatitis"" & + optumResults$timeAtRisk == ""On Treatment"" & + optumResults$canaRestricted == ""TRUE"" & + optumResults$eventType == ""First Post Index Event"" & + optumResults$psStrategy == ""Stratification"" & + optumResults$targetName == ""Canagliflozin new users"" & + optumResults$comparatorDrug %in% drugsOfInterest, + select=c( timeAtRisk,comparatorDrug,comparator, comparatorDays, eventsComparator)) + +optumResultsIRSubsetOTComparator<-plyr::rename(optumResultsIRSubsetOTComparator, replace = c(""timeAtRisk""=""Time At Risk"", ""comparatorDrug"" = ""Drug"",""comparator"" = ""Persons"", + ""comparatorDays""=""personDays"",""eventsComparator""=""Events"")) + + + +optumResultsIRSubsetComparator<-rbind(optumResultsIRSubsetITTComparator, optumResultsIRSubsetOTComparator) + + + +###For the Target + +#Intent to treat + +optumResultsIRSubsetITTTarget <-subset(optumResults, optumResults$outcomeName == "" Acute Pancreatitis"" & + optumResults$timeAtRisk == ""Intent to Treat"" & + optumResults$canaRestricted == ""TRUE"" & + optumResults$eventType == ""First Post Index Event"" & + optumResults$psStrategy == ""Stratification"" & + optumResults$targetName == ""Canagliflozin new users"" & + optumResults$comparatorDrug =="" GLP-1 inhibitors"", + select=c(timeAtRisk, targetDrug, treated, treatedDays, eventsTreated)) + + +optumResultsIRSubsetITTTarget<-plyr::rename(optumResultsIRSubsetITTTarget, replace = c(""timeAtRisk""=""Time At Risk"", ""targetDrug"" = ""Drug"",""treated"" = ""Persons"", + ""treatedDays""=""personDays"",""eventsTreated""=""Events"")) + +#On treatment + +optumResultsIRSubsetOTTarget <-subset(optumResults, optumResults$outcomeName == "" Acute Pancreatitis"" & + optumResults$timeAtRisk == ""On Treatment"" & + optumResults$canaRestricted == ""TRUE"" & + optumResults$eventType == ""First Post Index Event"" & + optumResults$psStrategy == ""Stratification"" & + optumResults$targetName == ""Canagliflozin new users"" & + optumResults$comparatorDrug =="" GLP-1 inhibitors"", + select=c(timeAtRisk, targetDrug, treated, treatedDays, eventsTreated)) + +optumResultsIRSubsetOTTarget<-plyr::rename(optumResultsIRSubsetOTTarget, replace = c(""timeAtRisk""=""Time At Risk"", ""targetDrug"" = ""Drug"",""treated"" = ""Persons"", + ""treatedDays""=""personDays"",""eventsTreated""=""Events"")) + +optumResultsIRSubsetTreated<-rbind(optumResultsIRSubsetITTTarget, optumResultsIRSubsetOTTarget) + + +#Combining Target and Comparator IRs + +optumResultsIRSubset<-rbind(optumResultsIRSubsetTreated, optumResultsIRSubsetComparator) + +optumResultsIRSubset$PersonYears<-round(optumResultsIRSubset$personDays/365.25, digits=2) +optumResultsIRSubset$IR_per_1000<-round((optumResultsIRSubset$Events/optumResultsIRSubset$PersonYears)*1000, digits=2) + + +database<-c(""optum"") +optumResultsIRSubset <- rbind(database,optumResultsIRSubset) +########################################################################### +#Merge the three tables together + +epi534_IR<-cbind(ccaeResultsIRSubset,mdcrResultsIRSubset,optumResultsIRSubset) + +setwd(reportFolder) +write.csv(epi534_IR, file='D:/Studies/EPI534/report/epi534_Table1_IR.csv', row.names = F) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iAcutePancreatitis/extras/EvidenceExplorer/global.R",".R","7764","140","blind <- FALSE +dataLocation <- ""S:/StudyResults/epi_534/shinyData"" + +resultsFileNames <- list.files(path = dataLocation, pattern = ""resultsHois_.*.rds"", full.names = TRUE) +ncsFileNames <- list.files(path = dataLocation, pattern = ""resultsNcs_.*.rds"", full.names = TRUE) +covarsFileNames <- list.files(path = dataLocation, pattern = ""covarNames_.*.rds"", full.names = TRUE) + +# nonDiagFileNames <- c(resultsFileNames, ncsFileNames, covarsFileNames) +# diagFileNames <- list.files(path = dataLocation, full.names = TRUE) +# diagFileNames <- setdiff(diagFileNames, nonDiagFileNames) + +# atcs <- data.frame() +# for (i in 1:length(diagFileNames)) { +# atc <- data.frame(analysisId = NA, targetId = NA, comparatorId = NA) +# ids <- gsub(""^.*_a"", """", diagFileNames[i]) +# atc$analysisId <- as.numeric(gsub(""_t.*"", """", ids)) +# ids <- gsub(""^.*_t"", """", ids) +# atc$targetId <- as.numeric(gsub(""_c.*"", """", ids)) +# ids <- gsub(""^.*_c"", """", ids) +# atc$comparatorId <- as.numeric(gsub(""_[[:alpha:]].*$"", """", ids)) +# atcs <- rbind(atcs, atc) +# } +# atcs <- unique(atcs) + +resultsHois <- lapply(resultsFileNames, readRDS) +allColumns <- unique(unlist(lapply(resultsHois, colnames))) +addMissingColumns <- function(results) { + presentCols <- colnames(results) + missingCols <- allColumns[!(allColumns %in% presentCols)] + for (missingCol in missingCols) { + results[, missingCol] <- rep(NA, nrow(results)) + } + return(results) +} +resultsHois <- lapply(resultsHois, addMissingColumns) +resultsHois <- do.call(rbind, resultsHois) + +atcs <- read.csv(""atcs.csv"") +resultsHois <- merge(resultsHois, atcs) + +# clarify naming --------------------------------------------------------------- + +resultsHois[resultsHois$targetDrug == ""canagliflozin"", ]$targetDrug <- ""Canagliflozin"" +resultsHois[resultsHois$comparatorDrug == "" DPP-4 inhibitors"", ]$comparatorDrug <- ""DPP-4 inhibitors"" +resultsHois[resultsHois$comparatorDrug == "" GLP-1 inhibitors"", ]$comparatorDrug <- ""GLP-1 agonists"" + +resultsHois[resultsHois$eventType == ""First EVer Event"" | resultsHois$eventType == ""First Ever Event"", ]$eventType <- ""First ever event"" +resultsHois[resultsHois$eventType == ""First Post Index Event"", ]$eventType <- ""First post index event"" + +resultsHois[resultsHois$timeAtRisk == ""On Treatment"", ]$timeAtRisk <- ""On treatment (+ 30 days)"" +resultsHois[resultsHois$timeAtRisk == ""Per Protocol Zero Day"", ]$timeAtRisk <- ""On treatment (+ 0 days)"" +resultsHois[resultsHois$timeAtRisk == ""Per Protocol Sixty Day"", ]$timeAtRisk <- ""On treatment (+ 60 days)"" +resultsHois[resultsHois$timeAtRisk == ""Intent to Treat"", ]$timeAtRisk <- ""Intent to treat"" +#resultsHois[resultsHois$timeAtRisk == ""Per Protocol Zero Day (no censor at switch)"", ]$timeAtRisk <- ""On Treatment (0 Day)"" +#resultsHois[resultsHois$timeAtRisk == ""On Treatment (no censor at switch)"", ]$timeAtRisk <- ""On Treatment (30 Day)"" +#resultsHois[resultsHois$timeAtRisk == ""Per Protocol Sixty Day (no censor at switch)"", ]$timeAtRisk <- ""On Treatment (60 Day)"" + +resultsHois[resultsHois$psStrategy == ""Matching"", ]$psStrategy <- ""Matching 0.2 caliper"" +resultsHois[resultsHois$psStrategy == ""Matching 0.1 Caliper"", ]$psStrategy <- ""Matching 0.1 caliper"" +resultsHois[resultsHois$psStrategy == ""Stratification"", ]$psStrategy <- ""Stratification (deciles)"" + +# create additional filter variables ------------------------------------------- +resultsHois$noCana <- with(resultsHois, ifelse(grepl(""no cana"", comparatorName), ""No comparator exposure ever"", ""No restriction"")) +#resultsHois$noCensor <- with(resultsHois, ifelse(grepl(""no censoring"", comparatorName), TRUE, FALSE)) + +resultsHois$metforminAddOn <- ""Not required"" +resultsHois[resultsHois$comparatorId > 1000000 & resultsHois$comparatorId < 2000000, ]$metforminAddOn <- ""Required"" + +resultsHois$priorAP <- FALSE +resultsHois[resultsHois$comparatorId > 2000000, ]$priorAP <- TRUE +resultsHois <- resultsHois[resultsHois$priorAP == FALSE, ] + +# these sensitivity analyses were all using restricted cana cohorts +# because ""no cana"" wasn't in the names of the cohort the earlier flag wasn't set properly +resultsHois[resultsHois$comparatorId > 1000000, ]$noCana <- ""No comparator exposure ever"" +#resultsHois[resultsHois$comparatorId > 1000000, ]$noCensor <- FALSE +#resultsHois <- resultsHois[resultsHois$noCensor == FALSE, ] + +resultsNcs <- lapply(ncsFileNames, readRDS) +resultsNcs <- do.call(rbind, resultsNcs) +resultsNcs <- merge(resultsNcs, atcs) + +covarNames <- lapply(covarsFileNames, readRDS) +covarNames <- do.call(rbind, covarNames) +covarNames <- unique(covarNames) + +resultsHois$comparison <- paste(resultsHois$targetDrug, resultsHois$comparatorDrug, sep = "" vs. "") +comparisons <- unique(resultsHois$comparison) +comparisonsOrder <- match(comparisons, c(""Canagliflozin vs. GLP-1 agonists"", + ""Canagliflozin vs. DPP-4 inhibitors"", + ""Canagliflozin vs. Sulfonylurea"", + ""Canagliflozin vs. TZD"", + ""Canagliflozin vs. Insulin new users"", + ""Canagliflozin vs. Other AHA"", + ""Canagliflozin vs. Albiglutide"", + ""Canagliflozin vs. Dulaglutide"", + ""Canagliflozin vs. Exenatide"", + ""Canagliflozin vs. Liraglutide"", + ""Canagliflozin vs. Lixisenatide"", + ""Canagliflozin vs. Alogliptin"", + ""Canagliflozin vs. Linagliptin"", + ""Canagliflozin vs. Saxagliptin"", + ""Canagliflozin vs. Sitagliptin"", + ""Canagliflozin vs. Glipizide"", + ""Canagliflozin vs. Glyburide"", + ""Canagliflozin vs. Glimepiride"", + ""Canagliflozin vs. Pioglitazone"", + ""Canagliflozin vs. Rosiglitazone"", + ""Canagliflozin vs. Acarbose"", + ""Canagliflozin vs. Bromocriptine"", + ""Canagliflozin vs. Miglitol"", + ""Canagliflozin vs. Nateglinide"", + ""Canagliflozin vs. Repaglinide"", + ""Canagliflozin vs. Dapagliflozin"", + ""Canagliflozin vs. Empagliflozin"")) +comparisons <- comparisons[order(comparisonsOrder)] +outcomes <- unique(resultsHois$outcomeName) + +eventTypes <- unique(resultsHois$eventType) +eventTypesOrder <- match(eventTypes, c(""First post index event"", + ""First ever event"")) +eventTypes <- eventTypes[order(eventTypesOrder)] + +timeAtRisks <- unique(resultsHois$timeAtRisk) +timeAtRisksOrder <- match(timeAtRisks, c(""On treatment (+ 30 days)"", + ""Intent to treat"", + 'On treatment (+ 0 days)', + ""On treatment (+ 60 days)"")) +timeAtRisks <- timeAtRisks[order(timeAtRisksOrder)] +psStrategies <- unique(resultsHois$psStrategy) +canaFilters <- unique(resultsHois$noCana) +#censorFilters <- unique(resultsHois$noCensor) +metforminAddOns <- unique(resultsHois$metforminAddOn) +metforminAddOnsOrder <- match(metforminAddOns, c(""Not required"", ""Required"")) +metforminAddOns <- metforminAddOns[order(metforminAddOnsOrder)] +dbs <- unique(resultsHois$database) + +#priorAPs <- unique(resultsHois$priorAP) + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iAcutePancreatitis/extras/EvidenceExplorer/server.R",".R","18421","425","library(shiny) +library(DT) +library(ggplot2) +source(""functions.R"") +source(""Table1.R"") + +mainColumns <- c(""eventType"", + ""timeAtRisk"", + ""psStrategy"", + ""noCana"", + #""noCensor"", + #""priorAP"", + ""metforminAddOn"", + ""database"", + ""rr"", + ""ci95lb"", + ""ci95ub"", + ""p"", + ""calP"") + +mainColumnNames <- c(""Event type"", + ""Time at risk"", + ""PS strategy"", + ""Canagliflozin history"", + #""Prior AP"", + ""Metformin add-on"", + ""DB"", + ""HR"", + ""CI95LB"", + ""CI95UB"", + ""P"", + ""Cal. P"") + +powerColumns <- c(""treated"", + ""comparator"", + ""treatedDays"", + ""comparatorDays"", + ""eventsTreated"", + ""eventsComparator"", + ""irTreated"", + ""irComparator"", + ""mdrr"") + +powerColumnNames <- c(""Target subjects"", + ""Comparator subjects"", + ""Target days"", + ""Comparator days"", + ""Target events"", + ""Comparator events"", + ""Target IR (per 1,000 PY)"", + ""Comparator IR (per 1,000 PY)"", + ""MDRR"") + +shinyServer(function(input, output) { + + tableSubset <- reactive({ + idx <- resultsHois$comparison == input$comparison & + resultsHois$outcomeName == input$outcome & + resultsHois$timeAtRisk %in% input$timeAtRisk & + resultsHois$eventType %in% input$eventType & + resultsHois$psStrategy %in% input$psStrategy & + resultsHois$noCana %in% input$noCana & + resultsHois$database %in% input$db & + #resultsHois$priorAP %in% input$priorAP & + resultsHois$metforminAddOn %in% input$metforminAddOn + + resultsHois[idx, ] + }) + + selectedRow <- reactive({ + idx <- input$mainTable_rows_selected + if (is.null(idx)) { + return(NULL) + } else { + return(tableSubset()[idx, ]) + } + }) + + output$rowIsSelected <- reactive({ + return(!is.null(selectedRow())) + }) + outputOptions(output, ""rowIsSelected"", suspendWhenHidden = FALSE) + + output$isMetaAnalysis <- reactive({ + row <- selectedRow() + isMetaAnalysis <- !is.null(row) && row$database == ""Meta-analysis"" + if (isMetaAnalysis) { + hideTab(""tabsetPanel"", ""Population characteristics"") + hideTab(""tabsetPanel"", ""Propensity scores"") + hideTab(""tabsetPanel"", ""Covariate balance"") + hideTab(""tabsetPanel"", ""Kaplan-Meier"") + } else { + showTab(""tabsetPanel"", ""Population characteristics"") + showTab(""tabsetPanel"", ""Propensity scores"") + showTab(""tabsetPanel"", ""Covariate balance"") + showTab(""tabsetPanel"", ""Kaplan-Meier"") } + return(isMetaAnalysis) + }) + outputOptions(output, ""isMetaAnalysis"", suspendWhenHidden = FALSE) + + balance <- reactive({ + row <- selectedRow() + if (is.null(row) || row$database == ""Meta-analysis"") { + return(NULL) + } else { + fileName <- paste0(""bal_a"",row$analysisId,""_t"",row$targetId,""_c"",row$comparatorId,""_o"",row$outcomeId,""_"",row$database,"".rds"") + print(paste(""loading balance file: "", fileName)) + data <- readRDS(file.path(dataLocation, fileName)) + data$absBeforeMatchingStdDiff <- abs(data$beforeMatchingStdDiff) + data$absAfterMatchingStdDiff <- abs(data$afterMatchingStdDiff) + data <- merge(data, covarNames) + return(data) + } + }) + + output$mainTable <- renderDataTable({ + table <- tableSubset()[, mainColumns] + if (nrow(table) > 0) { + table$rr[table$rr > 100] <- NA + table$rr <- formatC(table$rr, digits = 2, format = ""f"") + table$ci95lb <- formatC(table$ci95lb, digits = 2, format = ""f"") + table$ci95ub <- formatC(table$ci95ub, digits = 2, format = ""f"") + table$p <- formatC(table$p, digits = 2, format = ""f"") + table$calP <- formatC(table$calP, digits = 2, format = ""f"") + colnames(table) <- mainColumnNames + options = list(pageLength = 15, + searching = FALSE, + lengthChange = TRUE, + ordering = TRUE, + paging = TRUE) + selection = list(mode = ""single"", target = ""row"") + table <- datatable(table, + options = options, + selection = selection, + rownames = FALSE, + escape = FALSE, + class = ""stripe nowrap compact"") + return(table) + } else { + return(NULL) + } + }) + + output$powerTableCaption <- renderUI({ + row <- selectedRow() + if (!is.null(row)) { + text <- ""Table 1a. Number of subjects, follow-up time (in days), number of outcome + events, and event incidence rate (IR) per 1,000 patient years (PY) in the target (%s) and + comparator (%s) group after %s, as well as the minimum detectable relative risk (MDRR). + Note that the IR does not account for any stratification."" + return(HTML(sprintf(text, row$targetDrug, row$comparatorDrug, tolower(row$psStrategy)))) + } else { + return(NULL) + } + }) + + output$powerTable <- renderTable({ + table <- selectedRow() + if (!is.null(table)) { + table$irTreated <- formatC(1000 * table$eventsTreated / (table$treatedDays / 365.25), digits = 2, format = ""f"") + table$irComparator <- formatC(1000 * table$eventsComparator / (table$comparatorDays / 365.25), digits = 2, format = ""f"") + + table$treated <- formatC(table$treated, big.mark = "","", format = ""d"") + table$comparator <- formatC(table$comparator, big.mark = "","", format = ""d"") + table$treatedDays <- formatC(table$treatedDays, big.mark = "","", format = ""d"") + table$comparatorDays <- formatC(table$comparatorDays, big.mark = "","", format = ""d"") + table$eventsTreated <- formatC(table$eventsTreated, big.mark = "","", format = ""d"") + table$eventsComparator <- formatC(table$eventsComparator, big.mark = "","", format = ""d"") + table$mdrr <- formatC(table$mdrr, digits = 2, format = ""f"") + # if (table$database == ""Meta-analysis"") { + # table <- table[, c(powerColumns, ""i2"")] + # colnames(table) <- c(powerColumnNames, ""I2"") + # } else { + table <- table[, powerColumns] + colnames(table) <- powerColumnNames + #} + return(table) + } else { + return(table) + } + }) + + output$timeAtRiskTableCaption <- renderUI({ + row <- selectedRow() + if (!is.null(row)) { + text <- ""Table 1b. Time (days) at risk distribution expressed as mean, standard deviation (SD), + minimum (min), 25th percentile (P25), median, 75th percentile (P75), and maximum (max) in the target + (%s) and comparator (%s) cohort after %s."" + return(HTML(sprintf(text, row$targetDrug, row$comparatorDrug, tolower(row$psStrategy)))) + } else { + return(NULL) + } + }) + + output$timeAtRiskTable <- renderTable({ + row <- selectedRow() + if (!is.null(row)) { + + table <- data.frame(Cohort = c(""Target"", ""Comparator""), + Mean = formatC(c(row$tarTargetMean, row$tarComparatorMean), digits = 1, format = ""f""), + SD = formatC(c(row$tarTargetSd, row$tarComparatorSd), digits = 1, format = ""f""), + Min = formatC(c(row$tarTargetMin, row$tarComparatorMin), big.mark = "","", format = ""d""), + P10 = formatC(c(row$tarTargetP10, row$tarComparatorP10), big.mark = "","", format = ""d""), + P25 = formatC(c(row$tarTargetP25, row$tarComparatorP25), big.mark = "","", format = ""d""), + Median = formatC(c(row$tarTargetMedian, row$tarComparatorMedian), big.mark = "","", format = ""d""), + P75 = formatC(c(row$tarTargetP75, row$tarComparatorP75), big.mark = "","", format = ""d""), + P90 = formatC(c(row$tarTargetP90, row$tarComparatorP90), big.mark = "","", format = ""d""), + Max = formatC(c(row$tarTargetMax, row$tarComparatorMax), big.mark = "","", format = ""d"")) + return(table) + } else { + return(NULL) + } + }) + + output$table1Caption <- renderUI({ + bal <- balance() + if (!is.null(bal)) { + row <- selectedRow() + text <- ""Table 2. Select characteristics before and after %s, showing the (weighted) + percentage of subjects with the characteristics in the target (%s) and comparator (%s) group, as + well as the standardized difference of the means."" + return(HTML(sprintf(text, tolower(row$psStrategy), row$targetDrug, row$comparatorDrug))) + } else { + return(NULL) + } + }) + + output$table1Table <- renderDataTable({ + bal <- balance() + if (!is.null(bal)) { + row <- selectedRow() + fileName <- paste0(""ahaBal_a"",row$analysisId,""_t"",row$targetId,""_c"",row$comparatorId,""_o"",row$outcomeId,""_"",row$database,"".rds"") + print(row) + print(paste(""loading "", fileName)) + priorAhaBalance <- readRDS(file.path(dataLocation, fileName)) + bal$absBeforeMatchingStdDiff <- NULL + bal$absAfterMatchingStdDiff <- NULL + priorAhaBalance <- priorAhaBalance[, colnames(bal)] + bal <- rbind(bal, priorAhaBalance) + table1 <- prepareTable1(bal, + beforeTargetPopSize = row$treatedBefore, + beforeComparatorPopSize = row$comparatorBefore, + afterTargetPopSize = row$treated, + afterComparatorPopSize = row$comparator, + beforeLabel = paste(""Before"", tolower(row$psStrategy)), + afterLabel = paste(""After"", tolower(row$psStrategy))) + container <- htmltools::withTags(table( + class = 'display', + thead( + tr( + th(rowspan = 3, ""Characteristic""), + th(colspan = 3, class = ""dt-center"", paste(""Before"", tolower(row$psStrategy))), + th(colspan = 3, class = ""dt-center"", paste(""After"", tolower(row$psStrategy))) + ), + tr( + lapply(table1[1, 2:ncol(table1)], th) + ), + tr( + lapply(table1[2, 2:ncol(table1)], th) + ) + ) + )) + options <- list(columnDefs = list(list(className = 'dt-right', targets = 1:6)), + searching = FALSE, + ordering = FALSE, + paging = FALSE, + bInfo = FALSE) + table1 <- datatable(table1[3:nrow(table1), ], + options = options, + rownames = FALSE, + escape = FALSE, + container = container, + class = ""stripe nowrap compact"") + return(table1) + } else { + return(NULL) + } + }) + + output$psPlot <- renderPlot({ + row <- selectedRow() + if (!is.null(row) && row$database != ""Meta-analysis"") { + fileName <- paste0(""ps_a"",row$analysisId,""_t"",row$targetId,""_c"",row$comparatorId,""_"",row$database,"".rds"") + data <- readRDS(file.path(dataLocation, fileName)) + data$GROUP <- row$targetDrug + data$GROUP[data$treatment == 0] <- row$comparatorDrug + data$GROUP <- factor(data$GROUP, levels = c(row$targetDrug, + row$comparatorDrug)) + plot <- ggplot2::ggplot(data, ggplot2::aes(x = preferenceScore, y = y, color = GROUP, group = GROUP, fill = GROUP)) + + ggplot2::geom_area(position = ""identity"") + + ggplot2::scale_fill_manual(values = c(rgb(0.8, 0, 0, alpha = 0.5), rgb(0, 0, 0.8, alpha = 0.5))) + + ggplot2::scale_color_manual(values = c(rgb(0.8, 0, 0, alpha = 0.5), rgb(0, 0, 0.8, alpha = 0.5))) + + ggplot2::scale_x_continuous(""Preference score"", limits = c(0, 1)) + + ggplot2::scale_y_continuous(""Density"") + + ggplot2::theme(legend.title = ggplot2::element_blank(), + legend.position = ""top"", + legend.direction = ""horizontal"", + text = ggplot2::element_text(size = 15)) + return(plot) + } else { + return(NULL) + } + }) + + output$balancePlotCaption <- renderUI({ + bal <- balance() + if (!is.null(bal)) { + row <- selectedRow() + text <- ""Figure 2. Covariate balance before and after %s. Each dot represents + the standardizes difference of means for a single covariate before and after %s on the propensity + score. Move the mouse arrow over a dot for more details."" + return(HTML(sprintf(text, tolower(row$psStrategy), tolower(row$psStrategy)))) + } else { + return(NULL) + } + }) + + output$balancePlot <- renderPlot({ + bal <- balance() + if (!is.null(bal)) { + row <- selectedRow() + plotBalance(bal, + beforeLabel = paste(""Std. diff. before"", tolower(row$psStrategy)), + afterLabel = paste(""Std. diff. after"", tolower(row$psStrategy))) + } else { + return(NULL) + } + }) + + output$hoverInfoBalanceScatter <- renderUI({ + # Hover-over adapted from https://gitlab.com/snippets/16220 + bal <- balance() + if (is.null(bal)) + return(NULL) + row <- selectedRow() + hover <- input$plotHoverBalanceScatter + point <- nearPoints(bal, hover, threshold = 5, maxpoints = 1, addDist = TRUE) + if (nrow(point) == 0) return(NULL) + + # calculate point position INSIDE the image as percent of total dimensions + # from left (horizontal) and from top (vertical) + left_pct <- (hover$x - hover$domain$left) / (hover$domain$right - hover$domain$left) + top_pct <- (hover$domain$top - hover$y) / (hover$domain$top - hover$domain$bottom) + + # calculate distance from left and bottom side of the picture in pixels + left_px <- hover$range$left + left_pct * (hover$range$right - hover$range$left) + top_px <- hover$range$top + top_pct * (hover$range$bottom - hover$range$top) + + # create style property fot tooltip + # background color is set so tooltip is a bit transparent + # z-index is set so we are sure are tooltip will be on top + style <- paste0(""position:absolute; z-index:100; background-color: rgba(245, 245, 245, 0.85); "", + ""left:"", left_px - 251, ""px; top:"", top_px - 150, ""px; width:500px;"") + + + # actual tooltip created as wellPanel + beforeMatchingStdDiff <- formatC(point$beforeMatchingStdDiff, digits = 2, format = ""f"") + afterMatchingStdDiff <- formatC(point$afterMatchingStdDiff, digits = 2, format = ""f"") + div( + style=""position: relative; width: 0; height: 0"", + wellPanel( + style = style, + p(HTML(paste0("" Covariate: "", point$covariateName, ""
"", + "" Std. diff before "",tolower(row$psStrategy),"": "", beforeMatchingStdDiff, ""
"", + "" Std. diff after "",tolower(row$psStrategy),"": "", afterMatchingStdDiff))) + ) + ) + }) + + output$negativeControlPlot <- renderPlot({ + row <- selectedRow() + if (!is.null(row)) { + ncs <- resultsNcs[resultsNcs$targetId == row$targetId & + resultsNcs$comparatorId == row$comparatorId & + resultsNcs$analysisId == row$analysisId & + resultsNcs$database == row$database, ] + fileName <- paste0(""null_a"",row$analysisId,""_t"",row$targetId,""_c"",row$comparatorId,""_"",row$database,"".rds"") + if (file.exists(file.path(dataLocation, fileName))) { + null <- readRDS(file.path(dataLocation, fileName)) + } else { + null <- NULL + } + plot <- EmpiricalCalibration::plotCalibrationEffect(logRrNegatives = ncs$logRr, + seLogRrNegatives = ncs$seLogRr, + logRrPositives = row$logRr, + seLogRrPositives = row$seLogRr, + null = null, + xLabel = ""Hazard ratio"", + showCis = !is.null(null)) + plot <- plot + ggplot2::theme(text = ggplot2::element_text(size = 15)) + + return(plot) + } else { + return(NULL) + } + }) + + output$kaplanMeierPlot <- renderPlot({ + row <- selectedRow() + if (!is.null(row)) { + fileName <- paste0(""km_a"",row$analysisId,""_t"",row$targetId,""_c"",row$comparatorId,""_o"",row$outcomeId,""_"",row$database,"".rds"") + if (file.exists(file.path(dataLocation, fileName))) { + plot <- readRDS(file.path(dataLocation, fileName)) + return(grid::grid.draw(plot)) + } + } + return(NULL) + }, res = 100) + + output$kmPlotCaption <- renderUI({ + bal <- balance() + if (!is.null(bal)) { + row <- selectedRow() + text <- ""Table 4. Kaplan Meier plot, showing survival as a function of time. This plot + is adjusted for the propensity score %s: The target curve (%s) shows the actual observed survival. The + comparator curve (%s) applies reweighting to approximate the counterfactual of what the target survival + would look like had the target cohort been exposed to the comparator instead. The shaded area denotes + the 95 percent confidence interval."" + return(HTML(sprintf(text, tolower(row$psStrategy), row$targetDrug, row$comparatorDrug))) + } else { + return(NULL) + } + }) +}) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iAcutePancreatitis/extras/EvidenceExplorer/functions.R",".R","935","16","plotBalance <- function(balance, + beforeLabel = ""Before matching"", + afterLabel = ""After matching"") { + limits <- c(min(c(balance$absBeforeMatchingStdDiff, balance$absAfterMatchingStdDiff), na.rm = TRUE), + max(c(balance$absBeforeMatchingStdDiff, balance$absAfterMatchingStdDiff), na.rm = TRUE)) + plot <- ggplot2::ggplot(balance, + ggplot2::aes(x = absBeforeMatchingStdDiff, y = absAfterMatchingStdDiff)) + + ggplot2::geom_point(color = rgb(0, 0, 0.8, alpha = 0.3), shape = 16, size = 2) + + ggplot2::geom_abline(slope = 1, intercept = 0, linetype = ""dashed"") + + ggplot2::geom_hline(yintercept = 0) + + ggplot2::geom_vline(xintercept = 0) + + ggplot2::scale_x_continuous(beforeLabel, limits = limits) + + ggplot2::scale_y_continuous(afterLabel, limits = limits) + + ggplot2::theme(text = ggplot2::element_text(size = 15)) + return(plot) +}","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iAcutePancreatitis/extras/EvidenceExplorer/ui.R",".R","10949","82","library(shiny) +library(DT) + +shinyUI(fluidPage(style = 'width:1500px;', + titlePanel(paste(""Acute Pancreatitis Risk in Type 2 Diabetes with Canagliflozin versus Other Antihyperglycemic Agents: Retrospective Cohort Study of US Claims Databases"", if(blind){""*Blinded*""}else{""""})), + + tabsetPanel(id = ""mainTabsetPanel"", + tabPanel(""About"", + HTML(""
""), + div(p(""These research results are from a retrospective, real-world observational study to evaluate the risk of acute pancreatitis among patients with type 2 diabetes mellitus treated with antihyperglycemic agents. This web-based application provides an interactive platform to explore all analysis results generated as part of this study, as a supplement to a full manuscript which has been submitted to peer-reviewed, scientific journal. During the review period, these results are considered under embargo and should not be disclosed without explicit permission and consent from the authors.""), style=""border: 1px solid black; padding: 5px;""), + HTML(""
""), + HTML(""
""), + p(""Below is the abstract of the submitted manuscript that summarizes the collective findings:""), + HTML(""
""), + p(tags$strong(""Background:""), ""Observational evidence suggests that patients with type 2 diabetes mellitus (T2DM) are at increased risk for acute pancreatitis (AP) versus those without T2DM. A small number of AP events were reported in clinical trials of the sodium glucose co-transporter 2 inhibitor canagliflozin, though no imbalances were observed between treatment groups. This observational study evaluated risk of AP among new users of canagliflozin compared with new users of six classes of other antihyperglycemic agents (AHAs).""), + p(tags$strong(""Methods:""), ""Three US claims databases were analyzed based on a prespecified protocol approved by the European Medicines Agency. Propensity score adjustment controlled for imbalances in baseline covariates. Cox regression models estimated the hazard ratio of AP with canagliflozin compared with other AHAs using on-treatment (primary) and intent-to-treat approaches. Sensitivity analyses assessed robustness of findings.""), + p(tags$strong(""Results:""), ""Across the three databases, there were between 12,023-80,986 new users of canagliflozin; the unadjusted incidence rates of AP (per 1000 person-years) were between 1.5-2.2 for canagliflozin and 1.1-6.6 for other AHAs. The risk of AP was generally similar for new users of canagliflozin compared with new users of glucagon-like peptide-1 receptor agonists, dipeptidyl peptidase-4 inhibitors, sulfonylureas, thiazolidinediones, insulin, and other AHAs, with no consistent between-treatment differences observed across databases. Intent-to-treat and sensitivity analysis findings were qualitatively consistent with on-treatment findings.""), + p(tags$strong(""Conclusions:""), ""In this large observational study, incidence rates of AP in patients with T2DM treated with canagliflozin or other AHAs were generally similar, with no evidence suggesting that canagliflozin is associated with increased risk of AP compared with other AHAs.""), + HTML(""
""), + HTML(""
""), + HTML(""

Below are links for study-related artifacts that have been made available as part of this study:

""), + HTML("""") + ), + tabPanel(""Explore results"", + fluidRow( + column(3, + selectInput(""comparison"", ""Comparison:"", comparisons), + selectInput(""outcome"", ""Outcome:"", outcomes), + checkboxGroupInput(""eventType"", ""Event type:"", eventTypes, selected = eventTypes[1]), + checkboxGroupInput(""timeAtRisk"", ""Time at risk:"", timeAtRisks, selected = timeAtRisks[1]), + checkboxGroupInput(""psStrategy"", ""Propensity score (PS) strategy:"", psStrategies, selected = psStrategies[1]), + checkboxGroupInput(""noCana"", ""Canagliflozin exposure history:"", canaFilters, selected = canaFilters[1]), + checkboxGroupInput(""metforminAddOn"", ""Metformin add-on:"", metforminAddOns, selected = ""Not required""), + checkboxGroupInput(""db"", ""Database (DB):"", dbs, selected = dbs) + #checkboxGroupInput(""noCensor"", ""Remove Censoring:"", censorFilters, selected = censorFilters), + #checkboxGroupInput(""priorAP"", ""Prior acute pancreatitis (AP):"", priorAPs, selected = priorAPs), + ), + column(9, + dataTableOutput(""mainTable""), + conditionalPanel(""output.rowIsSelected == true"", + tabsetPanel(id = ""tabsetPanel"", + tabPanel(""Power"", + uiOutput(""powerTableCaption""), + tableOutput(""powerTable""), + conditionalPanel(""output.isMetaAnalysis == false"", + uiOutput(""timeAtRiskTableCaption""), + tableOutput(""timeAtRiskTable""))), + tabPanel(""Population characteristics"", + uiOutput(""table1Caption""), + dataTableOutput(""table1Table"")), + tabPanel(""Propensity scores"", + plotOutput(""psPlot""), + div(strong(""Figure 1.""),""Preference score distribution. The preference score is a transformation of the propensity score + that adjusts for differences in the sizes of the two treatment groups. A higher overlap indicates subjects in the + two groups were more similar in terms of their predicted probability of receiving one treatment over the other."")), + tabPanel(""Covariate balance"", + uiOutput(""hoverInfoBalanceScatter""), + plotOutput(""balancePlot"", + hover = hoverOpts(""plotHoverBalanceScatter"", delay = 100, delayType = ""debounce"")), + uiOutput(""balancePlotCaption"")), + tabPanel(""Systematic error"", + plotOutput(""negativeControlPlot""), + div(strong(""Figure 3.""),""Negative control estimates. Each blue dot represents the estimated hazard + ratio and standard error (related to the width of the confidence interval) of each of the negative + control outcomes. The yellow diamond indicated the outcome of interest. Estimates below the dashed + line have uncalibrated p < .05. Estimates in the orange area have calibrated p < .05. The red band + indicated the 95% credible interval around the boundary of the orange area. "")), + tabPanel(""Kaplan-Meier"", + plotOutput(""kaplanMeierPlot"", height = 550), + uiOutput(""kmPlotCaption"")) + ) + ) + ) + ) + ) + ) +)) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iAcutePancreatitis/extras/EvidenceExplorer/Table1.R",".R","8155","144","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# 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. + +prepareTable1 <- function(balance, + beforeTargetPopSize, + beforeComparatorPopSize, + afterTargetPopSize, + afterComparatorPopSize, + beforeLabel = ""Before matching"", + afterLabel = ""After matching"", + targetLabel = ""Target"", + comparatorLabel = ""Comparator"", + percentDigits = 1, + stdDiffDigits = 2) { + #pathToCsv <- system.file(""settings"", ""Table1Specs.csv"", package = packageName) + pathToCsv <- ""Table1Specs.csv"" + specifications <- read.csv(pathToCsv, stringsAsFactors = FALSE) + + fixCase <- function(label) { + idx <- (toupper(label) == label) + if (any(idx)) { + label[idx] <- paste0(substr(label[idx], 1, 1), + tolower(substr(label[idx], 2, nchar(label[idx])))) + } + return(label) + } + + formatPercent <- function(x) { + result <- format(round(100*x, percentDigits), digits = percentDigits+1, justify = ""right"") + # result <- formatC(x * 100, digits = percentDigits, format = ""f"") + result <- gsub(""NA"", """", result) + result <- gsub("" "", "" "", result) + return(result) + } + + formatStdDiff <- function(x) { + result <- format(round(x, stdDiffDigits), digits = stdDiffDigits+1, justify = ""right"") + result <- gsub(""NA"", """", result) + result <- gsub("" "", "" "", result) + return(result) + } + + resultsTable <- data.frame() + for (i in 1:nrow(specifications)) { + if (specifications$analysisId[i] == """") { + resultsTable <- rbind(resultsTable, + data.frame(Characteristic = specifications$label[i], value = """")) + } else { + idx <- balance$analysisId == specifications$analysisId[i] + if (any(idx)) { + if (specifications$covariateIds[i] != """") { + covariateIds <- as.numeric(strsplit(specifications$covariateIds[i], "","")[[1]]) + idx <- balance$covariateId %in% covariateIds + } else { + covariateIds <- NULL + } + if (any(idx)) { + balanceSubset <- balance[idx, ] + if (is.null(covariateIds)) { + balanceSubset <- balanceSubset[order(balanceSubset$covariateId), ] + } else { + balanceSubset <- merge(balanceSubset, data.frame(covariateId = covariateIds, + rn = 1:length(covariateIds))) + balanceSubset <- balanceSubset[order(balanceSubset$rn, + balanceSubset$covariateId), ] + } + balanceSubset$covariateName <- fixCase(gsub(""^.*: "", + """", + balanceSubset$covariateName)) + if (specifications$covariateIds[i] == """" || length(covariateIds) > 1) { + resultsTable <- rbind(resultsTable, data.frame(Characteristic = specifications$label[i], + beforeMatchingMeanTreated = NA, + beforeMatchingMeanComparator = NA, + beforeMatchingStdDiff = NA, + afterMatchingMeanTreated = NA, + afterMatchingMeanComparator = NA, + afterMatchingStdDiff = NA, + stringsAsFactors = FALSE)) + resultsTable <- rbind(resultsTable, + data.frame(Characteristic = paste0(""    "", balanceSubset$covariateName), + beforeMatchingMeanTreated = balanceSubset$beforeMatchingMeanTreated, + beforeMatchingMeanComparator = balanceSubset$beforeMatchingMeanComparator, + beforeMatchingStdDiff = balanceSubset$beforeMatchingStdDiff, + afterMatchingMeanTreated = balanceSubset$afterMatchingMeanTreated, + afterMatchingMeanComparator = balanceSubset$afterMatchingMeanComparator, + afterMatchingStdDiff = balanceSubset$afterMatchingStdDiff, + stringsAsFactors = FALSE)) + } else { + resultsTable <- rbind(resultsTable, data.frame(Characteristic = specifications$label[i], + beforeMatchingMeanTreated = balanceSubset$beforeMatchingMeanTreated, + beforeMatchingMeanComparator = balanceSubset$beforeMatchingMeanComparator, + beforeMatchingStdDiff = balanceSubset$beforeMatchingStdDiff, + afterMatchingMeanTreated = balanceSubset$afterMatchingMeanTreated, + afterMatchingMeanComparator = balanceSubset$afterMatchingMeanComparator, + afterMatchingStdDiff = balanceSubset$afterMatchingStdDiff, + stringsAsFactors = FALSE)) + } + } + } + } + } + resultsTable$beforeMatchingMeanTreated <- formatPercent(resultsTable$beforeMatchingMeanTreated) + resultsTable$beforeMatchingMeanComparator <- formatPercent(resultsTable$beforeMatchingMeanComparator) + resultsTable$beforeMatchingStdDiff <- formatStdDiff(resultsTable$beforeMatchingStdDiff) + resultsTable$afterMatchingMeanTreated <- formatPercent(resultsTable$afterMatchingMeanTreated) + resultsTable$afterMatchingMeanComparator <- formatPercent(resultsTable$afterMatchingMeanComparator) + resultsTable$afterMatchingStdDiff <- formatStdDiff(resultsTable$afterMatchingStdDiff) + + headerRow <- as.data.frame(t(rep("""", ncol(resultsTable)))) + colnames(headerRow) <- colnames(resultsTable) + headerRow$beforeMatchingMeanTreated <- targetLabel + headerRow$beforeMatchingMeanComparator <- comparatorLabel + headerRow$afterMatchingMeanTreated <- targetLabel + headerRow$afterMatchingMeanComparator <- comparatorLabel + + subHeaderRow <- as.data.frame(t(rep("""", ncol(resultsTable)))) + colnames(subHeaderRow) <- colnames(resultsTable) + subHeaderRow$Characteristic <- ""Characteristic"" + subHeaderRow$beforeMatchingMeanTreated <- paste0(""% (n = "",format(beforeTargetPopSize, big.mark = "",""), "")"") + subHeaderRow$beforeMatchingMeanComparator <- paste0(""% (n = "",format(beforeComparatorPopSize, big.mark = "",""), "")"") + subHeaderRow$beforeMatchingStdDiff <- ""Std. diff"" + subHeaderRow$afterMatchingMeanTreated <- paste0(""% (n = "",format(afterTargetPopSize, big.mark = "",""), "")"") + subHeaderRow$afterMatchingMeanComparator <- paste0(""% (n = "",format(afterComparatorPopSize, big.mark = "",""), "")"") + subHeaderRow$afterMatchingStdDiff <- ""Std. diff"" + + resultsTable <- rbind(headerRow, subHeaderRow, resultsTable) + + colnames(resultsTable) <- rep("""", ncol(resultsTable)) + # colnames(resultsTable) <- as.character(1:ncol(resultsTable)) + colnames(resultsTable)[2] <- beforeLabel + colnames(resultsTable)[5] <- afterLabel + return(resultsTable) +}","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iAcutePancreatitis/extras/AllResultsToPdf/AllResultsToPdf.R",".R","19386","465","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of AhasHfBkleAmputation +# +# 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. + +# Make sure to install: +# MikTex +# GhostScript +# R packages: knitr, rmarkdown, kableExtra + +#library(devtools) +#devtools::install_version(""rmarkdown"", version = ""1.8"", repos = ""http://cran.us.r-project.org"") + +# studyFolder <- ""y:"" +# packageFolder <- ""x:"" + +studyFolder <- ""D:/Studies/EPI534"" +packageFolder <- ""D:/epi_534"" + +appendixFolder <- file.path(studyFolder, ""report"", ""appendixV4"") +evidenceExplorerFolder <- file.path(packageFolder, ""extras"", ""EvidenceExplorer"") +shinyDataFolder <- file.path(evidenceExplorerFolder, ""data"") +# tempFolder <- ""c:/Temp"" +tempFolder <- ""D:/Temp"" + +if (!file.exists(tempFolder)) + dir.create(tempFolder) +if (!file.exists(appendixFolder)) + dir.create(appendixFolder) + +OhdsiRTools::addDefaultFileLogger(file.path(appendixFolder, ""log.txt"")) +wd <- setwd(evidenceExplorerFolder) +source(""global.R"") +setwd(wd) + +# Appendix A ----------------------------------------------------------------------------------- +convertToPdf <- function(appendixFolder, rmdFile) { + wd <- setwd(appendixFolder) + pdfFile <- gsub("".Rmd$"", "".pdf"", rmdFile) + on.exit(setwd(wd)) + rmarkdown::render(rmdFile, + output_file = pdfFile, + rmarkdown::pdf_document(latex_engine = ""pdflatex"")) +} + + +mainColumns <- c(""noCana"", + ""metforminAddOn"", + ""priorAP"", + ""timeAtRisk"", + ""eventType"", + ""psStrategy"", + ""database"", + ""rr"", + ""ci95lb"", + ""ci95ub"", + ""p"", + ""calP"", + ""targetId"", + ""comparatorId"", + ""outcomeId"", + ""analysisId"") + +mainColumnNames <- c(""Remove Cana"", + ""Metformin add on"", + ""Prior AP"", + ""Time at risk"", + ""Event"", + ""PS strategy"", + ""Data source"", + ""HR (95% CI)"", + ""P"", + ""Cal. P"", + ""App."") + + +template <- SqlRender::readSql(file.path(packageFolder,""extras/AllResultsToPdf/hazardRatioTableTemplate.rmd"")) + +aNumber <- 1 +bNumber <- 1 +aAppendices <- data.frame() +bAppendices <- data.frame() + + +# overriding for requested order +comparisons <- c( + ""canagliflozin - GLP-1 inhibitors"", + ""canagliflozin - DPP-4 inhibitors"", + ""canagliflozin - Sulfonylurea"", + ""canagliflozin - TZD"", + ""canagliflozin - Insulin new users"", + ""canagliflozin - Other AHA"", + ""canagliflozin - Empagliflozin"", + ""canagliflozin - Dapagliflozin"", + ""canagliflozin - Alogliptin"", + ""canagliflozin - Linagliptin"", + ""canagliflozin - Saxagliptin"", + ""canagliflozin - Sitagliptin"", + ""canagliflozin - Albiglutide"", + ""canagliflozin - Dulaglutide"", + ""canagliflozin - Exenatide"", + ""canagliflozin - Liraglutide"", + ""canagliflozin - Lixisenatide"", + ""canagliflozin - Pioglitazone"", + ""canagliflozin - Rosiglitazone"", + ""canagliflozin - Glyburide"", + ""canagliflozin - Glimepiride"", + ""canagliflozin - Glipizide"", + ""canagliflozin - Acarbose"", + ""canagliflozin - Bromocriptine"", + ""canagliflozin - Miglitol"", + ""canagliflozin - Nateglinide"", + ""canagliflozin - Repaglinide"" +) + +formatHr <- function(hr, lb, ub) { + ifelse (is.na(lb) | is.na(ub) | is.na(hr), ""NA"", sprintf( + ""%s (%s-%s)"", + formatC(hr, digits = 2, format = ""f""), + formatC(lb, digits = 2, format = ""f""), + formatC(ub, digits = 2, format = ""f"") + ) + ) +} + +for (comparison in comparisons) { + for (outcome in outcomes) { + table <- resultsHois[resultsHois$comparison == comparison & resultsHois$outcomeName == outcome, mainColumns] + table$dbOrder <- match(table$database, c(""CCAE"", ""MDCR"", ""Optum"")) + table$timeAtRiskOrder <- match(table$timeAtRisk, c(""On Treatment (30 Day)"", + ""Intent to Treat"", + ""On Treatment (0 Day)"", + ""On Treatment (60 Day)"")) + table <- table[order(table$noCana, + table$metforminAddOn, + table$priorAP, + table$timeAtRiskOrder, + table$eventType, + table$psStrategy), ] + table$dbOrder <- NULL + table$timeAtRiskOrder <- NULL + + table$rr[table$rr > 100] <- NA + table$ci95ub[table$ci95ub > 100] <- NA + table$rr <- formatHr(table$rr, table$ci95lb, table$ci95ub) + table$ci95lb <- NULL + table$ci95ub <- NULL + table$p <- formatC(table$p, digits = 2, format = ""f"") + table$p <- gsub(""NA"", """", table$p) + table$calP <- formatC(table$calP, digits = 2, format = ""f"") + table$calP <- gsub(""NA"", """", table$calP) + table$timeAtRisk[table$timeAtRisk == ""Intent to Treat""] <- ""ITT"" + table$eventType <- gsub(""First"", ""1st"", table$eventType) + table$appendix <- sprintf(""b%05d"", bNumber:(bNumber + nrow(table) - 1)) + bAppendices <- rbind(bAppendices, data.frame(targetId = table$targetId, + comparatorId = table$comparatorId, + outcomeId = table$outcomeId, + analysisId = table$analysisId, + database = table$database, + appendix = table$appendix)) + table$targetId <- NULL + table$comparatorId <- NULL + table$outcomeId <- NULL + table$analysisId <- NULL + colnames(table) <- mainColumnNames + saveRDS(table, file.path(tempFolder, ""temp.rds"")) + + rmd <- template + rmd <- gsub(""%number%"", sprintf(""a%02d"", aNumber), rmd) + rmd <- gsub(""%comparison%"", gsub(""GLP-1 inhibitors"", ""GLP-1 agonists"", comparison), rmd) + rmd <- gsub(""%outcome%"", outcome, rmd) + rmd <- gsub(""%tempFolder%"", tempFolder, rmd) + rmdFile <- sprintf(""appendix-a%02d.Rmd"", aNumber) + sink(file.path(appendixFolder, rmdFile)) + writeLines(rmd) + sink() + convertToPdf(appendixFolder, rmdFile) + + aNumber <- aNumber + 1 + bNumber <- bNumber + nrow(table) + + # Cleanup + unlink(file.path(appendixFolder, rmdFile)) + unlink(list.files(tempFolder, pattern = ""^temp"")) + } +} +saveRDS(bAppendices, file.path(appendixFolder, ""bAppendices.rds"")) + +# Appendix B ----------------------------------------------------------------------------- +bAppendices <- readRDS(file.path(appendixFolder, ""bAppendices.rds"")) + +generateAppendixB <- function(i) { + pdfFile <- sprintf(""appendix-%s.pdf"", bAppendices$appendix[i]) + if (!file.exists(file.path(appendixFolder, pdfFile))) { + OhdsiRTools::logInfo(""Generating "", pdfFile) + + tempFolderI <- paste0(tempFolder, i) + dir.create(tempFolderI) + + wd <- setwd(evidenceExplorerFolder) + source(""Table1.R"") + setwd(wd) + + convertToPdf <- function(appendixFolder, rmdFile) { + wd <- setwd(appendixFolder) + pdfFile <- gsub("".Rmd$"", "".pdf"", rmdFile) + on.exit(setwd(wd)) + rmarkdown::render(rmdFile, + output_file = pdfFile, + rmarkdown::pdf_document(latex_engine = ""pdflatex"")) + } + + + row <- resultsHois[resultsHois$targetId == bAppendices$targetId[i] & + resultsHois$comparatorId == bAppendices$comparatorId[i] & + resultsHois$outcomeId == bAppendices$outcomeId[i] & + resultsHois$analysisId == bAppendices$analysisId[i] & + resultsHois$database == bAppendices$database[i], ] + isMetaAnalysis <- F + # Power table + powerColumns <- c(""treated"", + ""comparator"", + ""treatedDays"", + ""comparatorDays"", + ""eventsTreated"", + ""eventsComparator"", + ""irTreated"", + ""irComparator"", + ""mdrr"") + + powerColumnNames <- c(""Target"", + ""Comparator"", + ""Target"", + ""Comparator"", + ""Target"", + ""Comparator"", + ""Target"", + ""Comparator"", + ""MDRR"") + table <- row + table$irTreated <- formatC(1000 * table$eventsTreated / (table$treatedDays / 365.25), digits = 2, format = ""f"") + table$irComparator <- formatC(1000 * table$eventsComparator / (table$comparatorDays / 365.25), digits = 2, format = ""f"") + table$treated <- formatC(table$treated, big.mark = "","", format = ""d"") + table$comparator <- formatC(table$comparator, big.mark = "","", format = ""d"") + table$treatedDays <- formatC(table$treatedDays, big.mark = "","", format = ""d"") + table$comparatorDays <- formatC(table$comparatorDays, big.mark = "","", format = ""d"") + table$eventsTreated <- formatC(table$eventsTreated, big.mark = "","", format = ""d"") + table$eventsComparator <- formatC(table$eventsComparator, big.mark = "","", format = ""d"") + table$mdrr <- formatC(table$mdrr, digits = 2, format = ""f"") + table <- table[, powerColumns] + colnames(table) <- powerColumnNames + + saveRDS(table, file.path(tempFolderI, ""tempPower.rds"")) + + # Follow-up table + if (!isMetaAnalysis) { + table <- data.frame(Cohort = c(""Target"", ""Comparator""), + Mean = formatC(c(row$tarTargetMean, row$tarComparatorMean), digits = 1, format = ""f""), + SD = formatC(c(row$tarTargetSd, row$tarComparatorSd), digits = 1, format = ""f""), + Min = formatC(c(row$tarTargetMin, row$tarComparatorMin), big.mark = "","", format = ""d""), + P10 = formatC(c(row$tarTargetP10, row$tarComparatorP10), big.mark = "","", format = ""d""), + P25 = formatC(c(row$tarTargetP25, row$tarComparatorP25), big.mark = "","", format = ""d""), + Median = formatC(c(row$tarTargetMedian, row$tarComparatorMedian), big.mark = "","", format = ""d""), + P75 = formatC(c(row$tarTargetP75, row$tarComparatorP75), big.mark = "","", format = ""d""), + P90 = formatC(c(row$tarTargetP90, row$tarComparatorP90), big.mark = "","", format = ""d""), + Max = formatC(c(row$tarTargetMax, row$tarComparatorMax), big.mark = "","", format = ""d"")) + saveRDS(table, file.path(tempFolderI, ""tempTar.rds"")) + } + + # Population characteristics + if (!isMetaAnalysis) { + fileName <- paste0(""bal_a"",row$analysisId,""_t"",row$targetId,""_c"",row$comparatorId,""_o"",row$outcomeId,""_"",row$database,"".rds"") + + if (!file.exists(file.path(shinyDataFolder, fileName))) { + ParallelLogger::logError(paste(""missing file: "", fileName)) + return(); + } + + bal <- readRDS(file.path(shinyDataFolder, fileName)) + if (""beforeMatchingMeanTarget"" %in% colnames(bal)) { + colnames(bal)[colnames(bal) == ""beforeMatchingMeanTarget""] <- ""beforeMatchingMeanTreated"" + colnames(bal)[colnames(bal) == ""beforeMatchingSumTarget""] <- ""beforeMatchingSumTreated"" + colnames(bal)[colnames(bal) == ""afterMatchingMeanTarget""] <- ""afterMatchingMeanTreated"" + colnames(bal)[colnames(bal) == ""afterMatchingSumTarget""] <- ""afterMatchingSumTreated"" + } + bal$beforeMatchingSumTreated <- NULL + bal$afterMatchingSumTreated <- NULL + bal <- merge(bal, covarNames) + fileName <- paste0(""ahaBal_a"",row$analysisId,""_t"",row$targetId,""_c"",row$comparatorId,""_o"",row$outcomeId,""_"",row$database,"".rds"") + if (!file.exists(file.path(shinyDataFolder, fileName))) { + ParallelLogger::logError(paste(""missing file: "", fileName)) + return(); + } + + priorAhaBalance <- readRDS(file.path(shinyDataFolder, fileName)) + priorAhaBalance <- priorAhaBalance[, colnames(bal)] + bal <- rbind(bal, priorAhaBalance) + + wd <- setwd(evidenceExplorerFolder) + table <- prepareTable1(bal, + beforeTargetPopSize = row$treatedBefore, + beforeComparatorPopSize = row$comparatorBefore, + afterTargetPopSize = row$treated, + afterComparatorPopSize = row$comparator, + beforeLabel = paste(""Before"", tolower(row$psStrategy)), + afterLabel = paste(""After"", tolower(row$psStrategy))) + setwd(wd) + table <- cbind(apply(table, 2, function(x) gsub("" "", "" "", x))) + colnames(table) <- table[2, ] + table <- table[3:nrow(table), ] + saveRDS(table, file.path(tempFolderI, ""tempPopChar.rds"")) + + fileName <- paste0(""ps_a"",row$analysisId,""_t"",row$targetId,""_c"",row$comparatorId,""_"",row$database,"".rds"") + if (!file.exists(file.path(shinyDataFolder, fileName))) { + ParallelLogger::logError(paste(""missing file: "", fileName)) + return(); + } + + data <- readRDS(file.path(shinyDataFolder, fileName)) + data$GROUP <- row$targetDrug + data$GROUP[data$treatment == 0] <- row$comparatorDrug + data$GROUP <- factor(data$GROUP, levels = c(row$targetDrug, + row$comparatorDrug)) + saveRDS(data, file.path(tempFolderI, ""tempPs.rds"")) + } + + # Covariate balance + if (!isMetaAnalysis) { + fileName <- paste0(""bal_a"",row$analysisId,""_t"",row$targetId,""_c"",row$comparatorId,""_o"",row$outcomeId,""_"",row$database,"".rds"") + if (!file.exists(file.path(shinyDataFolder, fileName))) { + ParallelLogger::logError(paste(""missing file: "", fileName)) + return(); + } + + bal <- readRDS(file.path(shinyDataFolder, fileName)) + bal$absBeforeMatchingStdDiff <- abs(bal$beforeMatchingStdDiff) + bal$absAfterMatchingStdDiff <- abs(bal$afterMatchingStdDiff) + saveRDS(bal, file.path(tempFolderI, ""tempBalance.rds"")) + } + + # Negative controls + ncs <- resultsNcs[resultsNcs$targetId == row$targetId & + resultsNcs$comparatorId == row$comparatorId & + resultsNcs$analysisId == row$analysisId & + resultsNcs$database == row$database, ] + saveRDS(ncs, file.path(tempFolderI, ""tempNcs.rds"")) + + # Kaplan Meier + if (!isMetaAnalysis) { + fileName <- paste0(""km_a"",row$analysisId,""_t"",row$targetId,""_c"",row$comparatorId,""_o"",row$outcomeId,""_"",row$database,"".rds"") + if (!file.exists(file.path(shinyDataFolder, fileName))) { + ParallelLogger::logError(paste(""missing file: "", fileName)) + return(); + } + + plot <- readRDS(file.path(shinyDataFolder, fileName)) + saveRDS(plot, file.path(tempFolderI, ""tempKm.rds"")) + } + + template <- SqlRender::readSql(""extras/AllResultsToPdf/detailsTemplate.rmd"") + rmd <- template + rmd <- gsub(""%tempFolder%"", tempFolderI, rmd) + rmd <- gsub(""%number%"", bAppendices$appendix[i], rmd) + rmd <- gsub(""%comparison%"", gsub(""GLP-1 inhibitors"", ""GLP-1 agonists"", comparison), rmd) + rmd <- gsub(""%outcome%"", row$outcomeName, rmd) + rmd <- gsub(""%target%"", row$targetDrug, rmd) + rmd <- gsub(""%comparator%"", row$comparatorDrug, rmd) + rmd <- gsub(""%psStrategy%"", row$psStrategy, rmd) + rmd <- gsub(""%logRr%"", if (is.na(row$logRr)) 999 else row$logRr, rmd) + rmd <- gsub(""%seLogRr%"", if (is.na(row$seLogRr)) 999 else row$seLogRr, rmd) + rmd <- gsub(""%noCana%"", row$noCana, rmd) + rmd <- gsub(""%metforminAddOn%"", row$metforminAddOn, rmd) + rmd <- gsub(""%priorAP%"", row$priorAP, rmd) + rmd <- gsub(""%timeAtRisk%"", row$timeAtRisk, rmd) + rmd <- gsub(""%eventType%"", row$eventType, rmd) + rmd <- gsub(""%psStrategy%"", row$psStrategy, rmd) + rmd <- gsub(""%database%"", row$database, rmd) + rmd <- gsub(""%isMetaAnalysis%"", isMetaAnalysis, rmd) + + rmdFile <- sprintf(""appendix-%s.Rmd"", bAppendices$appendix[i]) + sink(file.path(appendixFolder, rmdFile)) + writeLines(rmd) + sink() + convertToPdf(appendixFolder, rmdFile) + + # Cleanup + unlink(file.path(appendixFolder, rmdFile)) + unlink(tempFolderI, recursive = TRUE) + } +} + +#nThreads <- parallel::detectCores() - 1 +nThreads <- 1 +cluster <- OhdsiRTools::makeCluster(nThreads) +setGlobalVars <- function(i, bAppendices, resultsHois, resultsNcs, covarNames, appendixFolder, tempFolder, evidenceExplorerFolder, shinyDataFolder){ + bAppendices <<- bAppendices + resultsHois <<- resultsHois + resultsNcs <<- resultsNcs + covarNames <<- covarNames + appendixFolder <<- appendixFolder + shinyDataFolder <<- shinyDataFolder + evidenceExplorerFolder <<- evidenceExplorerFolder + tempFolder <<- tempFolder +} +n <- nrow(bAppendices) +if (nThreads > 1) { + dummy <- OhdsiRTools::clusterApply(cluster = cluster, + x = 1:nThreads, + fun = setGlobalVars, + bAppendices = bAppendices, + resultsHois = resultsHois, + resultsNcs = resultsNcs, + covarNames = covarNames, + appendixFolder = appendixFolder, + tempFolder = tempFolder, + shinyDataFolder = shinyDataFolder) + + + # when running clusterApply, the context of a function (in this case the global environment) + # is also transmitted with every function call. Making sure it doesn't contain anything big: + bAppendices <- NULL + resultsHois <- NULL + resultsNcs <- NULL + covarNames <- NULL + appendixFolder <- NULL + heterogeneous <- NULL + dummy <- NULL +} +dummy <- OhdsiRTools::clusterApply(cluster = cluster, + x = 1:n, + fun = generateAppendixB) + +OhdsiRTools::stopCluster(cluster) + +# Post processing using GhostScript ------------------------------------------------------------- +gsPath <- ""\""C:/Program Files/gs/gs9.23/bin/gswin64.exe\"""" + +tempFolder <- file.path(appendixFolder, ""optimized"") +if (!file.exists(tempFolder)) + dir.create(tempFolder) +files <- list.files(appendixFolder, pattern = "".*\\.pdf"", recursive = FALSE) + +for (fileName in files) { + args <- ""-dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dFastWebView -sOutputFile=%s %s %s"" + command <- paste(gsPath, sprintf(args, file.path(tempFolder, fileName), file.path(appendixFolder, fileName), file.path(getwd(), ""extras/AllResultsToPdf/pdfmarks""))) + shell(command) +} + +unlink(file.path(appendixFolder, files)) + +file.rename(from = file.path(tempFolder, files), to = file.path(appendixFolder, files)) + +unlink(tempFolder, recursive = TRUE) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","finalWoo/inst/shiny/PLPViewer/global.R",".R","975","15","# uncomment if running standalone +##runPlp <- readRDS(file.path(""data"",""results.rds"")) +##validatePlp <- readRDS(file.path(""data"",""extValidation.rds"")) +source(""utils.R"") +analysesLocation <- file.path(""data"") +allPerformance <- summaryPlpAnalyses(analysesLocation) +plpResultLocation <- allPerformance[,c('plpResultLocation', 'plpResultLoad')] +#allPerformance$combinedModelSettingName <- paste0(allPerformance$modelSettingName,'-', allPerformance$modelSettingsId +formatPerformance <- allPerformance[,c('analysisId','devDatabase','valDatabase','cohortName','outcomeName','modelSettingName','riskWindowStart', 'riskWindowEnd', 'AUC','AUPRC', 'populationSize','outcomeCount','incidence', + 'addExposureDaysToStart','addExposureDaysToEnd')] +colnames(formatPerformance) <- c('Analysis','Dev', 'Val', 'T', 'O','Model', 'TAR start', 'TAR end', 'AUC','AUPRC', 'T Size','O Count','O Incidence (%)', 'addExposureDaysToStart','addExposureDaysToEnd') + + + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","finalWoo/inst/shiny/PLPViewer/server.R",".R","11496","317","# @file server.R +# +# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of PatientLevelPrediction +# +# 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. + +library(shiny) +library(plotly) +library(shinycssloaders) + +source(""utils.R"") +source(""plots.R"") + +shiny::shinyServer(function(input, output, session) { + session$onSessionEnded(stopApp) + # reactive values - contains the location of the plpResult + ##reactVars <- shiny::reactiveValues(resultLocation=NULL, + ## plpResult= NULL) + #============= + + summaryData <- shiny::reactive({ + ind <- 1:nrow(allPerformance) + if(input$devDatabase!='All'){ + ind <- intersect(ind,which(as.character(allPerformance$devDatabase)==input$devDatabase)) + } + if(input$valDatabase!='All'){ + ind <- intersect(ind,which(as.character(allPerformance$valDatabase)==input$valDatabase)) + } + if(input$T!='All'){ + ind <- intersect(ind,which(allPerformance$cohortName==input$T)) + } + if(input$O!='All'){ + ind <- intersect(ind,which(allPerformance$outcomeName==input$O)) + } + if(input$modelSettingName!='All'){ + ind <- intersect(ind,which(as.character(allPerformance$modelSettingName)==input$modelSettingName)) + } + if(input$riskWindowStart!='All'){ + ind <- intersect(ind,which(allPerformance$riskWindowStart==input$riskWindowStart)) + } + if(input$riskWindowEnd!='All'){ + ind <- intersect(ind,which(allPerformance$riskWindowEnd==input$riskWindowEnd)) + } + + ind + }) + + + + output$summaryTable <- DT::renderDataTable(DT::datatable(formatPerformance[summaryData(),!colnames(formatPerformance)%in%c('addExposureDaysToStart','addExposureDaysToEnd')], + rownames= FALSE, selection = 'single')) + + + dataofint <- shiny::reactive({ + if(is.null(input$summaryTable_rows_selected[1])){ + ind <- 1 + }else{ + ind <- input$summaryTable_rows_selected[1] + } + + loc <- plpResultLocation[summaryData(),][ind,]$plpResultLocation + logLocation <- gsub('validationResult.rds','plpLog.txt',gsub('plpResult.rds','plpLog.txt', as.character(loc))) + if(file.exists(logLocation)){ + txt <- readLines(logLocation) + } else{ + txt <- 'log not available' + } + + covariates <- NULL + population <- NULL + modelset <- NULL + + if(file.exists(as.character(loc))){ + eval <- readRDS(as.character(loc)) + # rounding values to 2dp + for(coln in c('covariateValue','CovariateMeanWithOutcome','CovariateMeanWithNoOutcome')){ + eval$covariateSummary[,coln] <- format(round(eval$covariateSummary[,coln], 4), nsmall = 4) + class(eval$covariateSummary[,coln]) <- ""numeric"" + } + + } else{ + eval <- NULL + } + if(length(grep('/Validation',loc))>0){ + type <- 'validation' }else{ + type <- 'test' + } + + if(!is.null(eval)){ + covariates <- eval$model$metaData$call$covariateSettings + population <- eval$model$populationSettings + covariates <- data.frame(covariateName = names(covariates), + SettingValue = unlist(lapply(covariates, + function(x) paste0(x, + collapse='-'))) + ) + population$attrition <- NULL # remove the attrition as result and not setting + population <- data.frame(Setting = names(population), + Value = unlist(lapply(population, + function(x) paste0(x, + collapse='-'))) + ) + modelset <- data.frame(Setting = c('Model',names(eval$model$modelSettings[[2]])), + Value = c(eval$model$modelSettings[[1]], unlist(lapply(eval$model$modelSettings[[2]], + function(x) paste0(x, collapse='')))) + ) + + row.names(covariates) <- NULL + row.names(population) <- NULL + row.names(modelset) <- NULL + } + + return(list(eval=eval, type=type, + logtext = txt, + logLocation=logLocation, + covariates = covariates, + population = population, + modelset = modelset)) + }) + + plotters <- shiny::reactive({ + + eval <- dataofint()$eval$performanceEvaluation + if(is.null(eval)){return(NULL)} + + calPlot <- NULL + rocPlot <- NULL + prPlot <- NULL + f1Plot <- NULL + demoPlot <- NULL + boxPlot <- NULL + distPlot <- NULL + txt <- 'Empty' + predictionText <- c() + + if(!is.null(eval)){ + intPlot <- plotShiny(eval, input$slider1) + rocPlot <- intPlot$roc + prPlot <- intPlot$pr + f1Plot <- intPlot$f1score + threshold <- intPlot$threshold + prefthreshold <- intPlot$prefthreshold + TP <- intPlot$TP + FP <- intPlot$FP + TN <- intPlot$TN + FN <- intPlot$FN + prefdistPlot <- plotPreferencePDF(eval, type=dataofint()$type ) + prefdistPlot <- prefdistPlot + ggplot2::geom_vline(xintercept=prefthreshold) + preddistPlot <- plotPredictedPDF(eval, type=dataofint()$type ) + preddistPlot <- preddistPlot + ggplot2::geom_vline(xintercept=threshold) + boxPlot <- plotPredictionDistribution(eval, type=dataofint()$type ) + + calPlot <- plotSparseCalibration2(eval, type=dataofint()$type ) + demoPlot <- tryCatch(plotDemographicSummary(eval, type=dataofint()$type ), + error= function(cond){return(NULL)}) + + if(is.null(input$summaryTable_rows_selected[1])){ + ind <- 1 + }else{ + ind <- input$summaryTable_rows_selected[1] + } + predictionText <- paste0('Within ', formatPerformance[summaryData(),'T'][ind], + ' predict who will develop ', formatPerformance[summaryData(),'O'][ind], + ' during ', formatPerformance[summaryData(),'TAR start'][ind], ' day/s', + ' after ', ifelse(formatPerformance[summaryData(),'addExposureDaysToStart'][ind]==0, ' cohort start ', ' cohort end '), + ' and ', formatPerformance[summaryData(),'TAR end'][ind], ' day/s', + ' after ', ifelse(formatPerformance[summaryData(),'addExposureDaysToEnd'][ind]==0, ' cohort start ', ' cohort end ')) + + } + + twobytwo <- as.data.frame(matrix(c(FP,TP,TN,FN), byrow=T, ncol=2)) + colnames(twobytwo) <- c('Ground Truth Negative','Ground Truth Positive') + rownames(twobytwo) <- c('Predicted Positive','Predicted Negative') + + performance <- data.frame(Incidence = (TP+FN)/(TP+TN+FP+FN), + Threshold = threshold, + Sensitivity = TP/(TP+FN), + Specificity = TN/(TN+FP), + PPV = TP/(TP+FP), + NPV = TN/(TN+FN)) + + list(rocPlot= rocPlot, calPlot=calPlot, + prPlot=prPlot, f1Plot=f1Plot, + demoPlot=demoPlot, boxPlot=boxPlot, + prefdistPlot=prefdistPlot, + preddistPlot=preddistPlot, predictionText=predictionText, + threshold = format(threshold, digits=5), + twobytwo=twobytwo, + performance = performance ) + }) + + output$performance <- shiny::renderTable(plotters()$performance, + rownames = F, digits = 3) + output$twobytwo <- shiny::renderTable(plotters()$twobytwo, + rownames = T, digits = 0) + + output$modelTable <- DT::renderDataTable(dataofint()$modelset) + output$covariateTable <- DT::renderDataTable(dataofint()$covariates) + output$populationTable <- DT::renderDataTable(dataofint()$population) + + output$info <- shiny::renderText(plotters()$predictionText) + output$log <- shiny::renderText( paste(dataofint()$logtext, collapse=""\n"") ) + output$threshold <- shiny::renderText(plotters()$threshold) + + output$roc <- plotly::renderPlotly({ + plotters()$rocPlot + }) + output$cal <- shiny::renderPlot({ + plotters()$calPlot + }) + output$pr <- plotly::renderPlotly({ + plotters()$prPlot + }) + output$f1 <- plotly::renderPlotly({ + plotters()$f1Plot + }) + output$demo <- shiny::renderPlot({ + plotters()$demoPlot + }) + output$box <- shiny::renderPlot({ + plotters()$boxPlot + }) + output$preddist <- shiny::renderPlot({ + plotters()$preddistPlot + }) + output$prefdist <- shiny::renderPlot({ + plotters()$prefdistPlot + }) + + + covs <- shiny::reactive({ + if(is.null(dataofint()$eval)) + return(NULL) + plotCovariateSummary(dataofint()$eval$covariateSummary) + }) + + output$covariateSummaryBinary <- plotly::renderPlotly({ covs()$binary }) + output$covariateSummaryMeasure <- plotly::renderPlotly({ covs()$meas }) + + + output$modelView <- DT::renderDataTable(dataofint()$eval$covariateSummary[,c('covariateName','covariateValue','CovariateMeanWithOutcome','CovariateMeanWithNoOutcome' )], + colnames = c('Covariate Name', 'Value', 'Outcome Mean', 'Non-outcome Mean')) + + + # dashboard + + output$performanceBoxIncidence <- renderInfoBox({ + infoBox( + ""Incidence"", paste0(round(plotters()$performance$Incidence*100, digits=3),'%'), icon = icon(""ambulance""), + color = ""green"" + ) + }) + + output$performanceBoxThreshold <- renderInfoBox({ + infoBox( + ""Threshold"", format((plotters()$performance$Threshold), scientific = F, digits=3), icon = icon(""edit""), + color = ""yellow"" + ) + }) + + output$performanceBoxPPV <- renderInfoBox({ + infoBox( + ""PPV"", paste0(round(plotters()$performance$PPV*1000)/10, ""%""), icon = icon(""thumbs-up""), + color = ""orange"" + ) + }) + + output$performanceBoxSpecificity <- renderInfoBox({ + infoBox( + ""Specificity"", paste0(round(plotters()$performance$Specificity*1000)/10, ""%""), icon = icon(""bullseye""), + color = ""purple"" + ) + }) + + output$performanceBoxSensitivity <- renderInfoBox({ + infoBox( + ""Sensitivity"", paste0(round(plotters()$performance$Sensitivity*1000)/10, ""%""), icon = icon(""low-vision""), + color = ""blue"" + ) + }) + + output$performanceBoxNPV <- renderInfoBox({ + infoBox( + ""NPV"", paste0(round(plotters()$performance$NPV*1000)/10, ""%""), icon = icon(""minus-square""), + color = ""black"" + ) + }) + + + + # Downloadable csv of model ---- + output$downloadData <- downloadHandler( + filename = function(){'model.csv'}, + content = function(file) { + write.csv(dataofint()$eval$covariateSummary[dataofint()$eval$covariateSummary$covariateValue!=0,c('covariateName','covariateValue','CovariateMeanWithOutcome','CovariateMeanWithNoOutcome' )] + , file, row.names = FALSE) + } + ) + + + + + #============= + +})","R" +"Pharmacogenetics","OHDSI/StudyProtocols","finalWoo/inst/shiny/PLPViewer/plots.R",".R","22031","480","#============ DYNAMIC PLOTS ====================== +#++++++++++++++++++++++++++++++++++++++++++++++++++ + +plotShiny <- function(eval, pointOfInterest){ + + data <- eval$thresholdSummary[eval$thresholdSummary$Eval%in%c('test','validation'),] + # pointOfInterest # this is a threshold + pointOfInterest <- data[pointOfInterest,] + rocobject <- plotly::plot_ly(x = 1-c(0,data$specificity,1)) %>% + plotly::add_lines(y = c(1,data$sensitivity,0),name = ""hv"", + text = paste('Risk Threshold:',c(0,data$predictionThreshold,1)), + line = list(shape = ""hv"", + color = 'rgb(22, 96, 167)'), + fill = 'tozeroy') %>% + plotly::add_trace(x= c(0,1), y = c(0,1),mode = 'lines', + line = list(dash = ""dash""), color = I('black'), + type='scatter') %>% + plotly::add_trace(x= 1-pointOfInterest$specificity, y=pointOfInterest$sensitivity, + mode = 'markers', symbols='x') %>% # change the colour of this! + plotly::add_lines(x=c(1-pointOfInterest$specificity, 1-pointOfInterest$specificity), + y = c(0,1), + line = list(dash ='solid', + color = 'black')) %>% + plotly::layout(title = ""ROC Plot"", + xaxis = list(title = ""1-specificity""), + yaxis = list (title = ""Sensitivity""), + showlegend = FALSE) + + popAv <- data$trueCount[1]/(data$trueCount[1] + data$falseCount[1]) + probject <- plotly::plot_ly(x = data$sensitivity) %>% + plotly::add_lines(y = data$positivePredictiveValue, name = ""hv"", + text = paste('Risk Threshold:',data$predictionThreshold), + line = list(shape = ""hv"", + color = 'rgb(22, 96, 167)'), + fill = 'tozeroy') %>% + plotly::add_trace(x= c(0,1), y = c(popAv,popAv),mode = 'lines', + line = list(dash = ""dash""), color = I('red'), + type='scatter') %>% + plotly::add_trace(x= pointOfInterest$sensitivity, y=pointOfInterest$positivePredictiveValue, + mode = 'markers', symbols='x') %>% + plotly::add_lines(x=c(pointOfInterest$sensitivity, pointOfInterest$sensitivity), + y = c(0,1), + line = list(dash ='solid', + color = 'black')) %>% + plotly::layout(title = ""PR Plot"", + xaxis = list(title = ""Recall""), + yaxis = list (title = ""Precision""), + showlegend = FALSE) + + # add F1 score + f1object <- plotly::plot_ly(x = data$predictionThreshold) %>% + plotly::add_lines(y = data$f1Score, name = ""hv"", + text = paste('Risk Threshold:',data$predictionThreshold), + line = list(shape = ""hv"", + color = 'rgb(22, 96, 167)'), + fill = 'tozeroy') %>% + plotly::add_trace(x= pointOfInterest$predictionThreshold, y=pointOfInterest$f1Score, + mode = 'markers', symbols='x') %>% + plotly::add_lines(x=c(pointOfInterest$predictionThreshold, pointOfInterest$predictionThreshold), + y = c(0,1), + line = list(dash ='solid', + color = 'black')) %>% + plotly::layout(title = ""F1-Score Plot"", + xaxis = list(title = ""Prediction Threshold""), + yaxis = list (title = ""F1-Score""), + showlegend = FALSE) + # create 2x2 table with TP, FP, TN, FN and threshold + threshold <- pointOfInterest$predictionThreshold + TP <- pointOfInterest$truePositiveCount + TN <- pointOfInterest$trueNegativeCount + FP <- pointOfInterest$falsePositiveCount + FN <- pointOfInterest$falseNegativeCount + preferenceThreshold <- pointOfInterest$preferenceThreshold + + return(list(roc = rocobject, + pr = probject, + f1score = f1object, + threshold = threshold, prefthreshold=preferenceThreshold, + TP = TP, TN=TN, + FP= FP, FN=FN)) +} + +plotCovariateSummary <- function(covariateSummary){ + + #writeLines(paste(colnames(covariateSummary))) + #writeLines(paste(covariateSummary[1,])) + # remove na values + covariateSummary$CovariateMeanWithNoOutcome[is.na(covariateSummary$CovariateMeanWithNoOutcome)] <- 0 + covariateSummary$CovariateMeanWithOutcome[is.na(covariateSummary$CovariateMeanWithOutcome)] <- 0 + if(!'covariateValue'%in%colnames(covariateSummary)){ + covariateSummary$covariateValue <- 1 + } + if(sum(is.na(covariateSummary$covariateValue))>0){ + covariateSummary$covariateValue[is.na(covariateSummary$covariateValue)] <- 0 + } + + # SPEED EDIT remove the none model variables + covariateSummary <- covariateSummary[covariateSummary$covariateValue!=0,] + + # save dots based on coef value + covariateSummary$size <- abs(covariateSummary$covariateValue) + covariateSummary$size[is.na(covariateSummary$size)] <- 4 + covariateSummary$size <- 4+4*covariateSummary$size/max(covariateSummary$size) + + # color based on analysis id + covariateSummary$color <- sapply(covariateSummary$covariateName, function(x) ifelse(is.na(x), '', strsplit(as.character(x), ' ')[[1]][1])) + + l <- list(x = 0.01, y = 1, + font = list( + family = ""sans-serif"", + size = 10, + color = ""#000""), + bgcolor = ""#E2E2E2"", + bordercolor = ""#FFFFFF"", + borderwidth = 1) + + #covariateSummary$annotation <- sapply(covariateSummary$covariateName, getName) + covariateSummary$annotation <- covariateSummary$covariateName + + + ind <- covariateSummary$CovariateMeanWithNoOutcome <=1 & covariateSummary$CovariateMeanWithOutcome <= 1 + # create two plots -1 or less or g1 + binary <- plotly::plot_ly(x = covariateSummary$CovariateMeanWithNoOutcome[ind], + #size = covariateSummary$size[ind], + showlegend = F) %>% + plotly::add_markers(y = covariateSummary$CovariateMeanWithOutcome[ind], + color=factor(covariateSummary$color[ind]), + text = paste(covariateSummary$annotation[ind]), + showlegend = T + ) %>% + plotly::add_trace(x= c(0,1), y = c(0,1),mode = 'lines', + line = list(dash = ""dash""), color = I('black'), + type='scatter', showlegend = FALSE) %>% + plotly::layout(#title = 'Prevalance of baseline predictors in persons with and without outcome', + xaxis = list(title = ""Prevalance in persons without outcome"", + range = c(0, 1)), + yaxis = list(title = ""Prevalance in persons with outcome"", + range = c(0, 1)), + legend = l, showlegend = T) + + if(sum(!ind)>0){ + maxValue <- max(c(covariateSummary$CovariateMeanWithNoOutcome[!ind], + covariateSummary$CovariateMeanWithOutcome[!ind]), na.rm = T) + meas <- plotly::plot_ly(x = covariateSummary$CovariateMeanWithNoOutcome[!ind] ) %>% + plotly::add_markers(y = covariateSummary$CovariateMeanWithOutcome[!ind], + text = paste(covariateSummary$annotation[!ind])) %>% + plotly::add_trace(x= c(0,maxValue), y = c(0,maxValue),mode = 'lines', + line = list(dash = ""dash""), color = I('black'), + type='scatter', showlegend = FALSE) %>% + plotly::layout(#title = 'Prevalance of baseline predictors in persons with and without outcome', + xaxis = list(title = ""Mean in persons without outcome""), + yaxis = list(title = ""Mean in persons with outcome""), + showlegend = FALSE) + } else { + meas <- NULL + } + + return(list(binary=binary, + meas = meas)) +} + + + + + + +plotPredictedPDF <- function(evaluation, type='test', fileName=NULL){ + ind <- evaluation$thresholdSummary$Eval==type + + x<- evaluation$thresholdSummary[ind,c('predictionThreshold','truePositiveCount','trueNegativeCount', + 'falsePositiveCount','falseNegativeCount')] + x<- x[order(x$predictionThreshold,-x$truePositiveCount, -x$falsePositiveCount),] + x$out <- c(x$truePositiveCount[-length(x$truePositiveCount)]-x$truePositiveCount[-1], x$truePositiveCount[length(x$truePositiveCount)]) + x$nout <- c(x$falsePositiveCount[-length(x$falsePositiveCount)]-x$falsePositiveCount[-1], x$falsePositiveCount[length(x$falsePositiveCount)]) + + vals <- c() + for(i in 1:length(x$predictionThreshold)){ + if(i!=length(x$predictionThreshold)){ + upper <- x$predictionThreshold[i+1]} else {upper <- min(x$predictionThreshold[i]+0.01,1)} + val <- x$predictionThreshold[i]+runif(x$out[i])*(upper-x$predictionThreshold[i]) + vals <- c(val, vals) + } + vals[!is.na(vals)] + + vals2 <- c() + for(i in 1:length(x$predictionThreshold)){ + if(i!=length(x$predictionThreshold)){ + upper <- x$predictionThreshold[i+1]} else {upper <- min(x$predictionThreshold[i]+0.01,1)} + val2 <- x$predictionThreshold[i]+runif(x$nout[i])*(upper-x$predictionThreshold[i]) + vals2 <- c(val2, vals2) + } + vals2[!is.na(vals2)] + + x <- rbind(data.frame(variable=rep('outcome',length(vals)), value=vals), + data.frame(variable=rep('No outcome',length(vals2)), value=vals2) + ) + + plot <- ggplot2::ggplot(x, ggplot2::aes(x=x$value, + group=x$variable, + fill=x$variable)) + + ggplot2::geom_density(ggplot2::aes(x=x$value, fill=x$variable), alpha=.3) + + ggplot2::scale_x_continuous(""Prediction Threshold"")+#, limits=c(0,1)) + + ggplot2::scale_y_continuous(""Density"") + + ggplot2::guides(fill=ggplot2::guide_legend(title=""Class"")) + + if (!is.null(fileName)) + ggplot2::ggsave(fileName, plot, width = 5, height = 4.5, dpi = 400) + return(plot) +} + + +plotPreferencePDF <- function(evaluation, type='test', fileName=NULL){ + ind <- evaluation$thresholdSummary$Eval==type + + x<- evaluation$thresholdSummary[ind,c('preferenceThreshold','truePositiveCount','trueNegativeCount', + 'falsePositiveCount','falseNegativeCount')] + x<- x[order(x$preferenceThreshold,-x$truePositiveCount),] + x$out <- c(x$truePositiveCount[-length(x$truePositiveCount)]-x$truePositiveCount[-1], x$truePositiveCount[length(x$truePositiveCount)]) + x$nout <- c(x$falsePositiveCount[-length(x$falsePositiveCount)]-x$falsePositiveCount[-1], x$falsePositiveCount[length(x$falsePositiveCount)]) + + vals <- c() + for(i in 1:length(x$preferenceThreshold)){ + if(i!=length(x$preferenceThreshold)){ + upper <- x$preferenceThreshold[i+1]} else {upper <- 1} + val <- x$preferenceThreshold[i]+runif(x$out[i])*(upper-x$preferenceThreshold[i]) + vals <- c(val, vals) + } + vals[!is.na(vals)] + + vals2 <- c() + for(i in 1:length(x$preferenceThreshold)){ + if(i!=length(x$preferenceThreshold)){ + upper <- x$preferenceThreshold[i+1]} else {upper <- 1} + val2 <- x$preferenceThreshold[i]+runif(x$nout[i])*(upper-x$preferenceThreshold[i]) + vals2 <- c(val2, vals2) + } + vals2[!is.na(vals2)] + + x <- rbind(data.frame(variable=rep('outcome',length(vals)), value=vals), + data.frame(variable=rep('No outcome',length(vals2)), value=vals2) + ) + + plot <- ggplot2::ggplot(x, ggplot2::aes(x=x$value, + group=x$variable, + fill=x$variable)) + + ggplot2::geom_density(ggplot2::aes(x=x$value, fill=x$variable), alpha=.3) + + ggplot2::scale_x_continuous(""Preference Threshold"")+#, limits=c(0,1)) + + ggplot2::scale_y_continuous(""Density"") + + ggplot2::guides(fill=ggplot2::guide_legend(title=""Class"")) + + if (!is.null(fileName)) + ggplot2::ggsave(fileName, plot, width = 5, height = 4.5, dpi = 400) + return(plot) +} + + + + +plotDemographicSummary <- function(evaluation, type='test', fileName=NULL){ + if (!all(is.na(evaluation$demographicSummary$averagePredictedProbability))){ + ind <- evaluation$demographicSummary$Eval==type + x<- evaluation$demographicSummary[ind,colnames(evaluation$demographicSummary)%in%c('ageGroup','genGroup','averagePredictedProbability', + 'PersonCountAtRisk', 'PersonCountWithOutcome')] + + # remove -1 values: + x <- x[x$PersonCountWithOutcome != -1,] + if(nrow(x)==0){ + return(NULL) + } + # end remove -1 values + + x$observed <- x$PersonCountWithOutcome/x$PersonCountAtRisk + + + x <- x[,colnames(x)%in%c('ageGroup','genGroup','averagePredictedProbability','observed')] + + # if age or gender missing add + if(sum(colnames(x)=='ageGroup')==1 && sum(colnames(x)=='genGroup')==0 ){ + x$genGroup = rep('Non', nrow(x)) + evaluation$demographicSummary$genGroup = rep('Non', nrow(evaluation$demographicSummary)) + } + if(sum(colnames(x)=='ageGroup')==0 && sum(colnames(x)=='genGroup')==1 ){ + x$ageGroup = rep('-1', nrow(x)) + evaluation$demographicSummary$ageGroup = rep('-1', nrow(evaluation$demographicSummary)) + + } + + x <- reshape2::melt(x, id.vars=c('ageGroup','genGroup')) + + # 1.96*StDevPredictedProbability + ci <- evaluation$demographicSummary[,colnames(evaluation$demographicSummary)%in%c('ageGroup','genGroup','averagePredictedProbability','StDevPredictedProbability')] + ci$StDevPredictedProbability[is.na(ci$StDevPredictedProbability)] <- 1 + ci$lower <- ci$averagePredictedProbability-1.96*ci$StDevPredictedProbability + ci$lower[ci$lower <0] <- 0 + ci$upper <- ci$averagePredictedProbability+1.96*ci$StDevPredictedProbability + ci$upper[ci$upper >1] <- max(ci$upper[ci$upper <1]) + + x$age <- gsub('Age group:','', x$ageGroup) + x$age <- factor(x$age,levels=c("" 0-4"","" 5-9"","" 10-14"", + "" 15-19"","" 20-24"","" 25-29"","" 30-34"","" 35-39"","" 40-44"", + "" 45-49"","" 50-54"","" 55-59"","" 60-64"","" 65-69"","" 70-74"", + "" 75-79"","" 80-84"","" 85-89"","" 90-94"","" 95-99"",""-1""),ordered=TRUE) + + x <- merge(x, ci[,c('ageGroup','genGroup','lower','upper')], by=c('ageGroup','genGroup')) + + plot <- ggplot2::ggplot(data=x, + ggplot2::aes(x=age, group=variable*genGroup)) + + + ggplot2::geom_line(ggplot2::aes(y=value, group=variable, + color=variable, + linetype = variable))+ + ggplot2::geom_ribbon(data=x[x$variable!='observed',], + ggplot2::aes(ymin=lower, ymax=upper + , group=genGroup), + fill=""blue"", alpha=""0.2"") + + ggplot2::facet_grid(.~ genGroup, scales = ""free"") + + ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 90, hjust = 1)) + + #ggplot2::coord_flip() + + ggplot2::scale_y_continuous(""Fraction"") + + ggplot2::scale_x_discrete(""Age"") + + ggplot2::scale_color_manual(values = c(""royalblue4"",""red""), + guide = ggplot2::guide_legend(title = NULL), + labels = c(""Expected"", ""Observed"")) + + + ggplot2::guides(linetype=FALSE) + + if (!is.null(fileName)) + ggplot2::ggsave(fileName, plot, width = 7, height = 4.5, dpi = 400) + return(plot) + } +} + + +#============= +# CALIBRATIONSUMMARY PLOTS +#============= +#' Plot the calibration +#' +#' @details +#' Create a plot showing the calibration +#' #' +#' @param evaluation A prediction object as generated using the +#' \code{\link{runPlp}} function. +#' @param type options: 'train' or test' +#' @param fileName Name of the file where the plot should be saved, for example +#' 'plot.png'. See the function \code{ggsave} in the ggplot2 package for +#' supported file formats. +#' +#' @return +#' A ggplot object. Use the \code{\link[ggplot2]{ggsave}} function to save to file in a different +#' format. +#' +#' @export +plotSparseCalibration <- function(evaluation, type='test', fileName=NULL){ + ind <- evaluation$calibrationSummary$Eval==type + + x<- evaluation$calibrationSummary[ind,c('averagePredictedProbability','observedIncidence')] + maxVal <- max(x$averagePredictedProbability,x$observedIncidence) + model <- stats::lm(observedIncidence~averagePredictedProbability, data=x) + res <- model$coefficients + names(res) <- c('Intercept','Gradient') + + # confidence int + interceptConf <- stats::confint(model)[1,] + gradientConf <- stats::confint(model)[2,] + + cis <- data.frame(lci = interceptConf[1]+seq(0,1,length.out = nrow(x))*gradientConf[1], + uci = interceptConf[2]+seq(0,1,length.out = nrow(x))*gradientConf[2], + x=seq(0,1,length.out = nrow(x))) + + x <- cbind(x, cis) + # TODO: CHECK INPUT + plot <- ggplot2::ggplot(data=x, + ggplot2::aes(x=averagePredictedProbability, y=observedIncidence + )) + + ggplot2::geom_ribbon(ggplot2::aes(ymin=lci,ymax=uci, x=x), + fill=""blue"", alpha=""0.2"") + + ggplot2::geom_point(size=1, color='darkblue') + + ggplot2::coord_cartesian(ylim = c(0, maxVal), xlim =c(0,maxVal)) + + ggplot2::geom_abline(intercept = 0, slope = 1, linetype = 2, size=1, + show.legend = TRUE) + + ggplot2::geom_abline(intercept = res['Intercept'], slope = res['Gradient'], + linetype = 1,show.legend = TRUE, + color='darkblue') + + ggplot2::scale_x_continuous(""Average Predicted Probability"") + + ggplot2::scale_y_continuous(""Observed Fraction With Outcome"") + + + + if (!is.null(fileName)) + ggplot2::ggsave(fileName, plot, width = 5, height = 3.5, dpi = 400) + return(plot) +} + +#============= +# CALIBRATIONSUMMARY PLOTS 2 +#============= +#' Plot the conventional calibration +#' +#' @details +#' Create a plot showing the calibration +#' #' +#' @param evaluation A prediction object as generated using the +#' \code{\link{runPlp}} function. +#' @param type options: 'train' or test' +#' @param fileName Name of the file where the plot should be saved, for example +#' 'plot.png'. See the function \code{ggsave} in the ggplot2 package for +#' supported file formats. +#' +#' @return +#' A ggplot object. Use the \code{\link[ggplot2]{ggsave}} function to save to file in a different +#' format. +#' +#' @export +plotSparseCalibration2 <- function(evaluation, type='test', fileName=NULL){ + ind <- evaluation$calibrationSummary$Eval==type + + x<- evaluation$calibrationSummary[ind,c('averagePredictedProbability','observedIncidence', 'PersonCountAtRisk')] + + + cis <- apply(x, 1, function(x) binom.test(x[2]*x[3], x[3], alternative = c(""two.sided""), conf.level = 0.95)$conf.int) + x$lci <- cis[1,] + x$uci <- cis[2,] + + maxes <- max(max(x$averagePredictedProbability), max(x$observedIncidence))*1.1 + + # TODO: CHECK INPUT + limits <- ggplot2::aes(ymax = x$uci, ymin= x$lci) + + plot <- ggplot2::ggplot(data=x, + ggplot2::aes(x=averagePredictedProbability, y=observedIncidence + )) + + ggplot2::geom_point(size=2, color='black') + + ggplot2::geom_errorbar(limits) + + #ggplot2::geom_smooth(method=lm, se=F, colour='darkgrey') + + ggplot2::geom_line(colour='darkgrey') + + ggplot2::geom_abline(intercept = 0, slope = 1, linetype = 5, size=0.4, + show.legend = TRUE) + + ggplot2::scale_x_continuous(""Average Predicted Probability"") + + ggplot2::scale_y_continuous(""Observed Fraction With Outcome"") + + ggplot2::coord_cartesian(xlim = c(0, maxes), ylim=c(0,maxes)) + + + if (!is.null(fileName)) + ggplot2::ggsave(fileName, plot, width = 5, height = 3.5, dpi = 400) + return(plot) +} + +plotPredictionDistribution <- function(evaluation, type='test', fileName=NULL){ + ind <- evaluation$predictionDistribution$Eval==type + x<- evaluation$predictionDistribution[ind,] + + #(x=Class, y=predictedProbabllity sequence: min->P05->P25->Median->P75->P95->max) + + plot <- ggplot2::ggplot(x, ggplot2::aes(x=as.factor(class), + ymin=MinPredictedProbability, + lower=P25PredictedProbability, + middle=MedianPredictedProbability, + upper=P75PredictedProbability, + ymax=MaxPredictedProbability, + color=as.factor(class))) + + ggplot2::coord_flip() + + ggplot2::geom_boxplot(stat=""identity"") + + ggplot2::scale_x_discrete(""Class"") + + ggplot2::scale_y_continuous(""Predicted Probability"") + + ggplot2::theme(legend.position=""none"") + + ggplot2::geom_segment(ggplot2::aes(x = 0.9, y = x$P05PredictedProbability[x$class==0], + xend = 1.1, yend = x$P05PredictedProbability[x$class==0]), color='red') + + ggplot2::geom_segment(ggplot2::aes(x = 0.9, y = x$P95PredictedProbability[x$class==0], + xend = 1.1, yend = x$P95PredictedProbability[x$class==0]), color='red') + + ggplot2::geom_segment(ggplot2::aes(x = 1.9, y = x$P05PredictedProbability[x$class==1], + xend = 2.1, yend = x$P05PredictedProbability[x$class==1])) + + ggplot2::geom_segment(ggplot2::aes(x = 1.9, y = x$P95PredictedProbability[x$class==1], + xend = 2.1, yend = x$P95PredictedProbability[x$class==1])) + + + if (!is.null(fileName)) + ggplot2::ggsave(fileName, plot, width = 5, height = 4.5, dpi = 400) + return(plot) +}","R" +"Pharmacogenetics","OHDSI/StudyProtocols","finalWoo/inst/shiny/PLPViewer/ui.R",".R","25150","238","# @file Ui.R +# +# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of PatientLevelPrediction +# +# 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. + +library(shiny) +library(plotly) +library(shinycssloaders) +library(shinydashboard) + +ui <- shinydashboard::dashboardPage(skin = 'black', + + shinydashboard::dashboardHeader(title = ""Multiple PLP Viewer"", + + tags$li(div(img(src = 'logo.png', + title = ""OHDSI PLP"", height = ""40px"", width = ""40px""), + style = ""padding-top:0px; padding-bottom:0px;""), + class = ""dropdown"") + + + ), + + shinydashboard::dashboardSidebar( + shinydashboard::sidebarMenu( + shinydashboard::menuItem(""Summary"", tabName = ""Summary"", icon = shiny::icon(""table"")), + shinydashboard::menuItem(""Performance"", tabName = ""Performance"", icon = shiny::icon(""bar-chart"")), + shinydashboard::menuItem(""Model"", tabName = ""Model"", icon = shiny::icon(""clipboard"")), + shinydashboard::menuItem(""Log"", tabName = ""Log"", icon = shiny::icon(""list"")), + shinydashboard::menuItem(""Help"", tabName = ""Help"", icon = shiny::icon(""info"")) + ) + ), + + shinydashboard::dashboardBody( + shinydashboard::tabItems( + + # help tab + shinydashboard::tabItem(tabName = ""Help"", + shiny::h2(""Information""), + shiny::p(""Click on a row to explore the results for that model. When you wish to explore a different model, then select the new result row and the tabs will be updated.""), + shiny::a(""Demo Video"", href = 'https://youtu.be/StpV40yl1UE', target='_blank') + ), + + # First tab content + shinydashboard::tabItem(tabName = ""Summary"", + + shiny::fluidRow( + shiny::column(2, + shiny::h4('Filters'), + shiny::selectInput('devDatabase', 'Development Database', c('All',unique(as.character(allPerformance$devDatabase)))), + shiny::selectInput('valDatabase', 'Validation Database', c('All',unique(as.character(allPerformance$valDatabase)))), + shiny::selectInput('T', 'Target Cohort', c('All',unique(as.character(allPerformance$cohortName)))), + shiny::selectInput('O', 'Outcome Cohort', c('All',unique(as.character(allPerformance$outcomeName)))), + shiny::selectInput('riskWindowStart', 'Time-at-risk start:', c('All',unique(allPerformance$riskWindowStart))), + shiny::selectInput('riskWindowEnd', 'Time-at-risk end:', c('All',unique(as.character(allPerformance$riskWindowEnd)))), + shiny::selectInput('modelSettingName', 'Model:', c('All',unique(as.character(allPerformance$modelSettingName)))) + ), + shiny::column(10, style = ""background-color:#F3FAFC;"", + + # do this inside tabs: + shiny::tabsetPanel( + + shiny::tabPanel(""Results"", + shiny::div(DT::dataTableOutput('summaryTable'), + style = ""font-size:70%"")), + + shiny::tabPanel(""Model Settings"", + shiny::h3('Model Settings: ', + shiny::a(""help"", href=""https://ohdsi.github.io/PatientLevelPrediction/reference/index.html"", target=""_blank"") + ), + DT::dataTableOutput('modelTable')), + + shiny::tabPanel(""Population Settings"", + shiny::h3('Population Settings: ', + shiny::a(""help"", href=""https://ohdsi.github.io/PatientLevelPrediction/reference/createStudyPopulation.html"", target=""_blank"") + ), + DT::dataTableOutput('populationTable')), + + shiny::tabPanel(""Covariate Settings"", + shiny::h3('Covariate Settings: ', + shiny::a(""help"", href=""http://ohdsi.github.io/FeatureExtraction/reference/createCovariateSettings.html"", target=""_blank"") + ), + DT::dataTableOutput('covariateTable')) + ) + + ) + + )), + # second tab + shinydashboard::tabItem(tabName = ""Performance"", + + shiny::fluidRow( + tabBox( + title = ""Performance"", + # The id lets us use input$tabset1 on the server to find the current tab + id = ""tabset1"", height = ""100%"", width='100%', + tabPanel(""Summary"", + + shiny::fluidRow( + shiny::column(width = 4, + shinydashboard::box(width = 12, + title = tagList(shiny::icon(""question""),""Prediction Question""), status = ""info"", solidHeader = TRUE, + shiny::textOutput('info') + ), + shinydashboard::box(width = 12, + title = tagList(shiny::icon(""gear""), ""Input""), + status = ""info"", solidHeader = TRUE, + shiny::splitLayout( + cellWidths = c('5%', '90%', '5%'), + shiny::h5(' '), + shiny::sliderInput(""slider1"", + shiny::h4(""Threshold value slider: "", strong(shiny::textOutput('threshold'))), + min = 1, max = 100, value = 50, ticks = F), + shiny::h5(' ') + ), + shiny::splitLayout( + cellWidths = c('5%', '90%', '5%'), + shiny::h5(strong('0')), + shiny::h5(' '), + shiny::h5(strong('1')) + ), + shiny::tags$script(shiny::HTML("" + $(document).ready(function() {setTimeout(function() { + supElement = document.getElementById('slider1').parentElement; + $(supElement).find('span.irs-max, span.irs-min, span.irs-single, span.irs-from, span.irs-to').remove(); + }, 50);}) + "")) + ) + + ), + + + shiny::column(width = 8, + shinydashboard::box(width = 12, + title = ""Dashboard"", + status = ""warning"", solidHeader = TRUE, + shinydashboard::infoBoxOutput(""performanceBoxThreshold""), + shinydashboard::infoBoxOutput(""performanceBoxIncidence""), + shinydashboard::infoBoxOutput(""performanceBoxPPV""), + shinydashboard::infoBoxOutput(""performanceBoxSpecificity""), + shinydashboard::infoBoxOutput(""performanceBoxSensitivity""), + shinydashboard::infoBoxOutput(""performanceBoxNPV"") + + ), + shinydashboard::box(width = 12, + title = ""Cutoff Performance"", + status = ""warning"", solidHeader = TRUE, + shiny::tableOutput('twobytwo') + #infoBoxOutput(""performanceBox""), + ) + ) + ) + + + ), + tabPanel(""Discrimination"", + + shiny::fluidRow( + shinydashboard::box( status = 'info', + title = ""ROC Plot"", solidHeader = TRUE, + shinycssloaders::withSpinner(plotly::plotlyOutput('roc'))), + shinydashboard::box(status = 'info', + title = ""Precision recall plot"", solidHeader = TRUE, + side = ""right"", + shinycssloaders::withSpinner(plotly::plotlyOutput('pr')))), + + shiny::fluidRow( + shinydashboard::box(status = 'info', + title = ""F1 Score Plot"", solidHeader = TRUE, + shinycssloaders::withSpinner(plotly::plotlyOutput('f1'))), + shinydashboard::box(status = 'info', + title = ""Box Plot"", solidHeader = TRUE, + side = ""right"", + shinycssloaders::withSpinner(shiny::plotOutput('box')))), + + shiny::fluidRow( + shinydashboard::box(status = 'info', + title = ""Prediction Score Distribution"", solidHeader = TRUE, + shinycssloaders::withSpinner(shiny::plotOutput('preddist'))), + shinydashboard::box(status = 'info', + title = ""Preference Score Distribution"", solidHeader = TRUE, + side = ""right"", + shinycssloaders::withSpinner(shiny::plotOutput('prefdist')))) + + + ), + tabPanel(""Calibration"", + shiny::fluidRow( + shinydashboard::box(status = 'info', + title = ""Calibration Plot"", solidHeader = TRUE, + shinycssloaders::withSpinner(shiny::plotOutput('cal'))), + shinydashboard::box(status = 'info', + title = ""Demographic Plot"", solidHeader = TRUE, + side = ""right"", + shinycssloaders::withSpinner(shiny::plotOutput('demo'))) + ) + ) + ))), + + # 3rd tab + shinydashboard::tabItem(tabName = ""Model"", + shiny::fluidRow( + shinydashboard::box( status = 'info', + title = ""Binary"", solidHeader = TRUE, + shinycssloaders::withSpinner(plotly::plotlyOutput('covariateSummaryBinary'))), + shinydashboard::box(status = 'info', + title = ""Measurements"", solidHeader = TRUE, + side = ""right"", + shinycssloaders::withSpinner(plotly::plotlyOutput('covariateSummaryMeasure')))), + + shiny::fluidRow(width=12, + shinydashboard::box(status = 'info', width = 12, + title = ""Model Table"", solidHeader = TRUE, + shiny::downloadButton(""downloadData"", ""Download Model""), + DT::dataTableOutput('modelView'))) + ), + + # 4th tab + shinydashboard::tabItem(tabName = ""Log"", + shiny::verbatimTextOutput('log') + ) + + + ) + ) + )","R" +"Pharmacogenetics","OHDSI/StudyProtocols","finalWoo/inst/shiny/PLPViewer/utils.R",".R","6382","122","summaryPlpAnalyses <- function(analysesLocation){ + # loads the analyses and validations to get summaries + #======================================== + settings <- read.csv(file.path(analysesLocation,'settings.csv')) + settings <- settings[,!colnames(settings)%in%c('plpDataFolder','studyPopFile','plpResultFolder')] + settings$analysisId <- paste0('Analysis_', settings$analysisId) + + analysisIds <- dir(file.path(analysesLocation), recursive = F, full.names = T) + analysisIds <- analysisIds[grep('Analysis_',analysisIds)] + if(is.null(settings$devDatabase)){ + settings$devDatabase <- 'Missing' + } + settings$valDatabase <- settings$devDatabase + devPerformance <- do.call(rbind,lapply(file.path(analysisIds), getPerformance)) + devPerformance <- merge(settings[,c('analysisId','modelSettingsId', 'cohortName', 'outcomeName', + 'populationSettingId','modelSettingName','addExposureDaysToStart', + 'riskWindowStart', 'addExposureDaysToEnd', + 'riskWindowEnd','devDatabase','valDatabase')], + devPerformance, by='analysisId', all.x=T) + + validationLocation <- file.path(analysesLocation,'Validation') + if(length(dir(validationLocation))>0){ + valPerformances <- c() + valDatabases <- dir(validationLocation, recursive = F, full.names = T) + for( valDatabase in valDatabases){ + + valAnalyses <- dir(valDatabase, recursive = F, full.names = T) + valAnalyses <- valAnalyses[grep('Analysis_', valAnalyses)] + valPerformance <- do.call(rbind,lapply(file.path(valAnalyses), function(x) getValidationPerformance(x))) + valSettings <- settings[,c('analysisId','modelSettingsId', 'cohortName', 'outcomeName', + 'populationSettingId','modelSettingName','addExposureDaysToStart', + 'riskWindowStart', 'addExposureDaysToEnd', + 'riskWindowEnd')] + valSettings$devDatabase <- settings$devDatabase[1] + valPerformance <- merge(valSettings, + valPerformance, by='analysisId') + valPerformance <- valPerformance[,colnames(devPerformance)] # make sure same order + valPerformances <- rbind(valPerformances, valPerformance) + } + + if(ncol(valPerformances)==ncol(devPerformance)){ + allPerformance <- rbind(devPerformance,valPerformances) + } else{ + stop('Issue with dev and val performance data.frames') + } + } else { + allPerformance <- devPerformance + } + + allPerformance$AUC <- as.double(allPerformance$AUC) + allPerformance$AUPRC <- as.double(allPerformance$AUPRC) + allPerformance$outcomeCount <- as.double(allPerformance$outcomeCount) + allPerformance$populationSize <- as.double(allPerformance$populationSize) + allPerformance$incidence <- as.double(allPerformance$incidence) + return(allPerformance) +} + +getPerformance <- function(analysisLocation){ + location <- file.path(analysisLocation, 'plpResult.rds') + if(!file.exists(location)){ + analysisId <- strsplit(analysisLocation, '/')[[1]] + return(data.frame(analysisId=analysisId[length(analysisId)], + AUC=0.000, AUPRC=0, outcomeCount=0, + populationSize=0,incidence=0,plpResultLocation=location, + plpResultLoad='loadPlpResult')) + } + # read rds here + res <- readRDS(file.path(analysisLocation,'plpResult.rds')) + res <- as.data.frame(res$performanceEvaluation$evaluationStatistics) + + #if empty do edit? + + res <- tryCatch(reshape2::dcast(res[res$Eval=='test',], analysisId ~ Metric, value.var='Value'), + error = function(cont) return(NULL)) + if(is.null(res)){ + return(NULL) } + res <- res[,!colnames(res)%in%c(""BrierScore"",""BrierScaled"")] + res$incidence <- as.double(res$outcomeCount)/as.double(res$populationSize)*100 + res[, !colnames(res)%in%c('analysisId','outcomeCount','populationSize')] <- + format(as.double(res[, !colnames(res)%in%c('analysisId','outcomeCount','populationSize')]), digits = 2, scientific = F) + + if(sum(colnames(res)=='AUC.auc_ub95ci')>0){ + res$AUC <- res$AUC.auc + #res$AUC <- paste0(res$AUC.auc, ' (', res$AUC.auc_lb95ci,'-', res$AUC.auc_ub95ci,')') + } + + res$plpResultLocation <- location + res$plpResultLoad <- 'readRDS'#'loadPlpResult' + return(res[,c('analysisId', 'AUC', 'AUPRC', 'outcomeCount','populationSize','incidence','plpResultLocation', 'plpResultLoad')]) +} + +getValidationPerformance <- function(validationLocation){ + val <- readRDS(file.path(validationLocation,'validationResult.rds')) + if(""performanceEvaluation""%in%names(val)){ + valPerformance <- reshape2::dcast(as.data.frame(val$performanceEvaluation$evaluationStatistics), + analysisId ~ Metric, value.var='Value') + } else { + valPerformance <- reshape2::dcast(as.data.frame(val[[1]]$performanceEvaluation$evaluationStatistics), + analysisId ~ Metric, value.var='Value') + } + valPerformance$incidence <- as.double(valPerformance$outcomeCount)/as.double(valPerformance$populationSize)*100 + valPerformance[, !colnames(valPerformance)%in%c('analysisId','outcomeCount','populationSize')] <- + format(as.double(valPerformance[, !colnames(valPerformance)%in%c('analysisId','outcomeCount','populationSize')]), digits = 2, scientific = F) + + if(sum(colnames(valPerformance)=='AUC.auc_ub95ci')>0){ + valPerformance$AUC <- valPerformance$AUC.auc + #valPerformance$AUC <- paste0(valPerformance$AUC.auc, ' (', valPerformance$AUC.auc_lb95ci,'-', valPerformance$AUC.auc_ub95ci,')') + } + valPerformance$analysisId <- strsplit(validationLocation, '/')[[1]][[length(strsplit(validationLocation, '/')[[1]])]] + valPerformance$valDatabase <- strsplit(validationLocation, '/')[[1]][[length(strsplit(validationLocation, '/')[[1]])-1]] + valPerformance <- valPerformance[,c('analysisId','valDatabase', 'AUC', 'AUPRC', 'outcomeCount','populationSize','incidence')] + valPerformance$plpResultLocation <- file.path(validationLocation,'validationResult.rds') + valPerformance$plpResultLoad <- 'readRDS' + #valPerformance$rocplot <- file.path(validationLocation,'plots','sparseROC.pdf') + #valPerformance$calplot <- file.path(validationLocation,'plots','sparseCalibrationConventional.pdf') + return(valPerformance) +} + + + + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","finalWoo/R/Main.R",".R","10539","212","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of finalWoo +# +# 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. + +#' Execute the Study +#' +#' @details +#' This function executes the finalWoo Study. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param cdmDatabaseName Shareable name of the database +#' @param cohortDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param cohortTable The name of the table that will be created in the work database schema. +#' This table will hold the target population cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/). Do not use a folder on a network drive since this greatly impacts +#' performance. +#' @param createProtocol Creates a protocol based on the analyses specification +#' @param createCohorts Create the cohortTable table with the target population and outcome cohorts? +#' @param runAnalyses Run the model development +#' @param createResultsDoc Create a document containing the results of each prediction +#' @param createValidationPackage Create a package for sharing the models +#' @param analysesToValidate A vector of analysis ids (e.g., c(1,3,10)) specifying which analysese to export into validation package. Default is NULL and all are exported. +#' @param packageResults Should results be packaged for later sharing? +#' @param minCellCount The minimum number of subjects contributing to a count before it can be included +#' in packaged results. +#' @param createShiny Create a shiny app with the results +#' @param createJournalDocument Do you want to create a template journal document populated with results? +#' @param analysisIdDocument Which Analysis_id do you want to create the document for? +#' @param verbosity Sets the level of the verbosity. If the log level is at or higher in priority than the logger threshold, a message will print. The levels are: +#' \itemize{ +#' \item{DEBUG}{Highest verbosity showing all debug statements} +#' \item{TRACE}{Showing information about start and end of steps} +#' \item{INFO}{Show informative information (Default)} +#' \item{WARN}{Show warning messages} +#' \item{ERROR}{Show error messages} +#' \item{FATAL}{Be silent except for fatal errors} +#' } +#' @param cdmVersion The version of the common data model +#' +#' @examples +#' \dontrun{ +#' connectionDetails <- createConnectionDetails(dbms = ""postgresql"", +#' user = ""joe"", +#' password = ""secret"", +#' server = ""myserver"") +#' +#' execute(connectionDetails, +#' cdmDatabaseSchema = ""cdm_data"", +#' cdmDatabaseName = 'shareable name of the database' +#' cohortDatabaseSchema = ""study_results"", +#' cohortTable = ""cohort"", +#' oracleTempSchema = NULL, +#' outputFolder = ""c:/temp/study_results"", +#' createProtocol = T, +#' createCohorts = T, +#' runAnalyses = T, +#' createResultsDoc = T, +#' createValidationPackage = T, +#' packageResults = F, +#' minCellCount = 5, +#' createShiny = F, +#' verbosity = ""INFO"", +#' cdmVersion = 5) +#' } +#' +#' @export +execute <- function(connectionDetails, + cdmDatabaseSchema, + cdmDatabaseName = 'friendly database name', + cohortDatabaseSchema = cdmDatabaseSchema, + cohortTable = ""cohort"", + oracleTempSchema = cohortDatabaseSchema, + outputFolder, + createProtocol = F, + createCohorts = F, + runAnalyses = F, + createResultsDoc = F, + createValidationPackage = F, + analysesToValidate = NULL, + packageResults = F, + minCellCount= 5, + createShiny = F, + createJournalDocument = F, + analysisIdDocument = 1, + verbosity = ""INFO"", + cdmVersion = 5) { + if (!file.exists(outputFolder)) + dir.create(outputFolder, recursive = TRUE) + + ParallelLogger::addDefaultFileLogger(file.path(outputFolder, ""log.txt"")) + + if(createProtocol){ + createPlpProtocol(outputFolder) + } + + if (createCohorts) { + ParallelLogger::logInfo(""Creating cohorts"") + createCohorts(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder) + } + + if(runAnalyses){ + ParallelLogger::logInfo(""Running predictions"") + predictionAnalysisListFile <- system.file(""settings"", + ""predictionAnalysisList.json"", + package = ""finalWoo"") + predictionAnalysisList <- PatientLevelPrediction::loadPredictionAnalysisList(predictionAnalysisListFile) + predictionAnalysisList$connectionDetails = connectionDetails + predictionAnalysisList$cdmDatabaseSchema = cdmDatabaseSchema + predictionAnalysisList$cdmDatabaseName = cdmDatabaseName + predictionAnalysisList$oracleTempSchema = oracleTempSchema + predictionAnalysisList$cohortDatabaseSchema = cohortDatabaseSchema + predictionAnalysisList$cohortTable = cohortTable + predictionAnalysisList$outcomeDatabaseSchema = cohortDatabaseSchema + predictionAnalysisList$outcomeTable = cohortTable + predictionAnalysisList$cdmVersion = cdmVersion + predictionAnalysisList$outputFolder = outputFolder + predictionAnalysisList$verbosity = verbosity + + result <- do.call(PatientLevelPrediction::runPlpAnalyses, predictionAnalysisList) + } + + if (packageResults) { + ParallelLogger::logInfo(""Packaging results"") + packageResults(outputFolder = outputFolder, + minCellCount = minCellCount) + } + + if(createResultsDoc){ + createMultiPlpReport(analysisLocation=outputFolder, + protocolLocation = file.path(outputFolder,'protocol.docx'), + includeModels = F) + } + + if(createValidationPackage){ + predictionAnalysisListFile <- system.file(""settings"", + ""predictionAnalysisList.json"", + package = ""finalWoo"") + jsonSettings <- tryCatch({Hydra::loadSpecifications(file=predictionAnalysisListFile)}, + error=function(cond) { + stop('Issue with json file...') + }) + pn <- jsonlite::fromJSON(jsonSettings)$packageName + jsonSettings <- gsub(pn,paste0(pn,'Validation'),jsonSettings) + jsonSettings <- gsub('PatientLevelPredictionStudy','PatientLevelPredictionValidationStudy',jsonSettings) + + + createValidationPackage(modelFolder = outputFolder, + outputFolder = file.path(outputFolder, paste0(pn,'Validation')), + minCellCount = minCellCount, + databaseName = cdmDatabaseName, + jsonSettings = jsonSettings, + analysisIds = analysesToValidate) + } + + if (createShiny) { + populateShinyApp(resultDirectory = outputFolder, + minCellCount = minCellCount, + databaseName = cdmDatabaseName) + } + + if(createJournalDocument){ + predictionAnalysisListFile <- system.file(""settings"", + ""predictionAnalysisList.json"", + package = ""finalWoo"") + jsonSettings <- tryCatch({Hydra::loadSpecifications(file=predictionAnalysisListFile)}, + error=function(cond) { + stop('Issue with json file...') + }) + pn <- jsonlite::fromJSON(jsonSettings) + createJournalDocument(resultDirectory = outputFolder, + analysisId = analysisIdDocument, + includeValidation = T, + cohortIds = pn$cohortDefinitions$id, + cohortNames = pn$cohortDefinitions$name) + } + + + invisible(NULL) +} + + + + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","finalWoo/R/CreateCohorts.R",".R","2749","53","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of finalWoo +# +# 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. + +.createCohorts <- function(connection, + cdmDatabaseSchema, + vocabularyDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable, + oracleTempSchema, + outputFolder) { + + # Create study cohort table structure: + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""CreateCohortTable.sql"", + packageName = ""finalWoo"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + cohort_database_schema = cohortDatabaseSchema, + cohort_table = cohortTable) + DatabaseConnector::executeSql(connection, sql, progressBar = FALSE, reportOverallTime = FALSE) + + + + # Instantiate cohorts: + pathToCsv <- system.file(""settings"", ""CohortsToCreate.csv"", package = ""finalWoo"") + cohortsToCreate <- utils::read.csv(pathToCsv) + for (i in 1:nrow(cohortsToCreate)) { + writeLines(paste(""Creating cohort:"", cohortsToCreate$name[i])) + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = paste0(cohortsToCreate$name[i], "".sql""), + packageName = ""finalWoo"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + vocabulary_database_schema = vocabularyDatabaseSchema, + + target_database_schema = cohortDatabaseSchema, + target_cohort_table = cohortTable, + target_cohort_id = cohortsToCreate$cohortId[i]) + DatabaseConnector::executeSql(connection, sql) + } +}","R" +"Pharmacogenetics","OHDSI/StudyProtocols","finalWoo/R/finalWoo.R",".R","787","25","# @file finalWoo.R +# +# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of finalWoo +# +# 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. + +#' finalWoo +#' +#' @docType package +#' @name finalWoo +#' @import DatabaseConnector +#' @importFrom magrittr %>% +NULL","R" +"Pharmacogenetics","OHDSI/StudyProtocols","finalWoo/R/CreateAllCohorts.R",".R","4657","93","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of SkeletonCompartiveEffectStudy +# +# 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. + +#' Create the exposure and outcome cohorts +#' +#' @details +#' This function will create the exposure and outcome cohorts following the definitions included in +#' this package. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param cohortDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param cohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' +#' @export +createCohorts <- function(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema, + cohortTable = ""cohort"", + oracleTempSchema, + outputFolder) { + if (!file.exists(outputFolder)) + dir.create(outputFolder) + + conn <- DatabaseConnector::connect(connectionDetails) + + .createCohorts(connection = conn, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder) + + # Check number of subjects per cohort: + ParallelLogger::logInfo(""Counting cohorts"") + sql <- SqlRender::loadRenderTranslateSql(""GetCounts.sql"", + ""finalWoo"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + work_database_schema = cohortDatabaseSchema, + study_cohort_table = cohortTable) + counts <- DatabaseConnector::querySql(conn, sql) + colnames(counts) <- SqlRender::snakeCaseToCamelCase(colnames(counts)) + counts <- addCohortNames(counts) + utils::write.csv(counts, file.path(outputFolder, ""CohortCounts.csv""), row.names = FALSE) + + DatabaseConnector::disconnect(conn) +} + +addCohortNames <- function(data, IdColumnName = ""cohortDefinitionId"", nameColumnName = ""cohortName"") { + pathToCsv <- system.file(""settings"", ""CohortsToCreate.csv"", package = ""finalWoo"") + cohortsToCreate <- utils::read.csv(pathToCsv) + + idToName <- data.frame(cohortId = c(cohortsToCreate$cohortId), + cohortName = c(as.character(cohortsToCreate$name))) + idToName <- idToName[order(idToName$cohortId), ] + idToName <- idToName[!duplicated(idToName$cohortId), ] + names(idToName)[1] <- IdColumnName + names(idToName)[2] <- nameColumnName + data <- merge(data, idToName, all.x = TRUE) + # Change order of columns: + idCol <- which(colnames(data) == IdColumnName) + if (idCol < ncol(data) - 1) { + data <- data[, c(1:idCol, ncol(data) , (idCol+1):(ncol(data)-1))] + } + return(data) +}","R" +"Pharmacogenetics","OHDSI/StudyProtocols","finalWoo/R/SubmitResults.R",".R","2002","49","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of finalWoo +# +# 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. + +#' Submit the study results to the study coordinating center +#' +#' @details +#' This will upload the file \code{StudyResults.zip} to the study coordinating center using Amazon S3. +#' This requires an active internet connection. +#' +#' @param outputFolder Name of local folder where the results were generated; make sure to use forward slashes +#' (/). Do not use a folder on a network drive since this greatly impacts +#' performance. +#' @param key The key string as provided by the study coordinator +#' @param secret The secret string as provided by the study coordinator +#' +#' @return +#' TRUE if the upload was successful. +#' +#' @export +submitResults <- function(outputFolder, key, secret) { + zipName <- file.path(outputFolder, ""StudyResults.zip"") + if (!file.exists(zipName)) { + stop(paste(""Cannot find file"", zipName)) + } + writeLines(paste0(""Uploading file '"", zipName, ""' to study coordinating center"")) + result <- OhdsiSharing::putS3File(file = zipName, + bucket = ""ohdsi-study-skeleton"", + key = key, + secret = secret) + if (result) { + writeLines(""Upload complete"") + } else { + writeLines(""Upload failed. Please contact the study coordinator"") + } + invisible(result) +}","R" +"Pharmacogenetics","OHDSI/StudyProtocols","finalWoo/R/PackageResults.R",".R","3535","83","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of finalWoo +# +# 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. + +#' Package the results for sharing with OHDSI researchers +#' +#' @details +#' This function packages the results. +#' +#' @param outputFolder Name of folder containing the study analysis results +#' (/) +#' @param minCellCount The minimum number of subjects contributing to a count before it can be included in the results. +#' +#' @export +packageResults <- function(outputFolder, + minCellCount = 5) { + if(missing(outputFolder)){ + stop('Missing outputFolder...') + } + + # for each analysis copy the requested files... + folders <- list.dirs(path = outputFolder, recursive = F, full.names = F) + folders <- folders[grep('Analysis_', folders)] + + #create export subfolder in workFolder + exportFolder <- file.path(outputFolder, ""export"") + dir.create(exportFolder, recursive = T) + + for(folder in folders){ + #copy all plots across + if (!file.exists(file.path(exportFolder,folder))){ + dir.create(file.path(exportFolder,folder), recursive = T) + } + + # loads analysis results + if(dir.exists(file.path(outputFolder,folder, 'plpResult'))){ + plpResult <- PatientLevelPrediction::loadPlpResult(file.path(outputFolder,folder, 'plpResult')) + + if(minCellCount!=0){ + PatientLevelPrediction::transportPlp(plpResult, + outputFolder=file.path(exportFolder,folder, 'plpResult'), + n=minCellCount, + includeEvaluationStatistics=T, + includeThresholdSummary=T, + includeDemographicSummary=T, + includeCalibrationSummary =T, + includePredictionDistribution=T, + includeCovariateSummary=T) + } else { + PatientLevelPrediction::transportPlp(plpResult,outputFolder=file.path(exportFolder,folder, 'plpResult'), + n=NULL, + includeEvaluationStatistics=T, + includeThresholdSummary=T, + includeDemographicSummary=T, + includeCalibrationSummary =T, + includePredictionDistribution=T, + includeCovariateSummary=T) + } + } + } + + + ### Add all to zip file ### + zipName <- paste0(outputFolder, '.zip') + OhdsiSharing::compressFolder(exportFolder, zipName) + # delete temp folder + unlink(exportFolder, recursive = T) + + writeLines(paste(""\nStudy results are compressed and ready for sharing at:"", zipName)) + return(zipName) +}","R" +"Pharmacogenetics","OHDSI/StudyProtocols","finalWoo/R/createDocument.R",".R","3723","92","#' Create the exposure and outcome cohorts +#' +#' @details +#' This function will create the exposure and outcome cohorts following the definitions included in +#' this package. +#' +#' @param resultDirectory The directory containing the results (outputFolder) +#' @param analysisId An integer specifying the model Analysis_Id used to create the document +#' @param cohortIds A vector of cohort ids +#' @param cohortNames A vector of cohort names +#' @param includeValidation Whether to look in the validation folder and add any validation results +#' +#' @export +createJournalDocument <- function(resultDirectory, + analysisId = 1, + cohortIds, + cohortNames, + includeValidation = T){ + + if(missing(resultDirectory)){ + stop('resultDirectory not input') + } + + if(!includeValidation%in%c(T,F)){ + stop('includeValidation must be TRUE or FALSE') + } + + resLoc <- file.path(resultDirectory, paste0('Analysis_',analysisId),'plpResult') + if(!dir.exists(resLoc)){ + stop('Results are missing for specified analysisId') + } + + res <- PatientLevelPrediction::loadPlpResult(resLoc) + + exVal <- NULL + if(includeValidation){ + valFile <- dir(file.path(resultDirectory,'Validation'),recursive = T) + ind <- grep(paste0('Analysis_',analysisId), valFile) + if(length(ind)>0){ + vois <- valFile[ind] + databaseNames <- sapply(vois, function(x) strsplit(x,'/')[[1]][1]) + + results <- list() + length(results) <- length(vois) + for(i in 1:length(vois)){ + results[[i]] <- readRDS(file.path(resultDirectory,'Validation',vois[i])) + } + + #remove nulls + results = results[-which(unlist(lapply(results, function(x) is.null(x$performanceEvaluation))))] + + summary <- do.call(rbind, lapply(1:length(results), function(i) summariseVal(results[[i]], + database=databaseNames[[i]]))) + + summary$Value <- as.double(as.character(summary$Value )) + summary <- reshape2::dcast(summary, Database ~ Metric, value.var=""Value"", fun.aggregate = max) + + exVal <- list(summary=summary, + validation=results) + + class(exVal) <- 'validatePlp' + + } + } + + PatientLevelPrediction::createPlpJournalDocument(plpResult = res, + plpValidation = exVal, + targetName = cohortNames[cohortIds==res$model$cohortId][1], + outcomeName = cohortNames[cohortIds==res$model$outcomeId][1], + plpData = NULL, + table1 = F, connectionDetails = NULL, + includeTrain = T, + includeTest = T, + includePredictionPicture = F, + includeAttritionPlot = T, + outputLocation = file.path(resultDirectory,'plp_document.docx')) + + return(file.path(resultDirectory,'plp_document.docx')) + +} + + +summariseVal <- function(result, database){ + if(!is.null(result$performanceEvaluation$evaluationStatistics)){ + row.names(result$performanceEvaluation$evaluationStatistics) <- NULL + result <- as.data.frame(result$performanceEvaluation$evaluationStatistics) + result$Database <- database + return(result) + } else{ + return(NULL) + } +}","R" +"Pharmacogenetics","OHDSI/StudyProtocols","finalWoo/R/populateShinyApp.R",".R","3631","107","#' @export +populateShinyApp <- function(shinyDirectory, + resultDirectory, + minCellCount = 10, + databaseName = 'sharable name of development data'){ + + #check inputs + if(missing(shinyDirectory)){ + shinyDirectory <- system.file(""shiny"", ""PLPViewer"", package = ""finalWoo"") + } + if(missing(resultDirectory)){ + stop('Need to enter the resultDirectory') + } + if(!dir.exists(resultDirectory)){ + stop('resultDirectory does not exist') + } + + outputDirectory <- file.path(shinyDirectory,'data') + + # create the shiny data folder + if(!dir.exists(outputDirectory)){ + dir.create(outputDirectory, recursive = T) + } + + # copy the settings csv + file <- utils::read.csv(file.path(resultDirectory,'settings.csv')) + utils::write.csv(file, file.path(outputDirectory,'settings.csv'), row.names = F) + + # copy each analysis as a rds file and copy the log + files <- dir(resultDirectory, full.names = F) + files <- files[grep('Analysis', files)] + for(file in files){ + + if(!dir.exists(file.path(outputDirectory,file))){ + dir.create(file.path(outputDirectory,file)) + } + + if(dir.exists(file.path(resultDirectory,file, 'plpResult'))){ + res <- PatientLevelPrediction::loadPlpResult(file.path(resultDirectory,file, 'plpResult')) + res <- PatientLevelPrediction::transportPlp(res, n= minCellCount, + save = F, dataName = databaseName) + saveRDS(res, file.path(outputDirectory,file, 'plpResult.rds')) + } + if(file.exists(file.path(resultDirectory,file, 'plpLog.txt'))){ + file.copy(from = file.path(resultDirectory,file, 'plpLog.txt'), + to = file.path(outputDirectory,file, 'plpLog.txt')) + } + } + + # copy any validation results + if(dir.exists(file.path(resultDirectory,'Validation'))){ + valFolders <- dir(file.path(resultDirectory,'Validation'), full.names = F) + + if(length(valFolders)>0){ + # move each of the validation rds + for(valFolder in valFolders){ + + # get the analysisIds + valSubfolders <- dir(file.path(resultDirectory,'Validation',valFolder), full.names = F) + if(length(valSubfolders)!=0){ + for(valSubfolder in valSubfolders ){ + valOut <- file.path(valFolder,valSubfolder) + if(!dir.exists(file.path(outputDirectory,'Validation',valOut))){ + dir.create(file.path(outputDirectory,'Validation',valOut), recursive = T) + } + + + if(file.exists(file.path(resultDirectory,'Validation',valOut, 'validationResult.rds'))){ + res <- readRDS(file.path(resultDirectory,'Validation',valOut, 'validationResult.rds')) + res <- PatientLevelPrediction::transportPlp(res, n= minCellCount, + save = F, dataName = databaseName) + saveRDS(res, file.path(outputDirectory,'Validation',valOut, 'validationResult.rds')) + } + } + } + + } + + } + + } + + return(outputDirectory) + +} + +#' View shiny app +#' @details +#' This function will open an interactive shiny app for viewing the results +#' @param package The name of the package as a string +#' +#' @examples +#' \dontrun{ +#' viewShiny() +#' } +#' @export +viewShiny <- function(package = NULL){ + if(is.null(package)){ + appDir <- system.file(""shiny"", ""PLPViewer"", package = ""finalWoo"") + } + if(!is.null(package)){ + appDir <- system.file(""shiny"", ""PLPViewer"", package = package) + } + + shiny::shinyAppDir(appDir) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","finalWoo/R/createPlpProtocol.R",".R","52096","835","#' Create a protocol template for the study +#' +#' @details +#' This function will create a template protocol +#' +#' @param outputLocation Directory location where you want the protocol written to +#' @export +createPlpProtocol <- function(outputLocation = getwd()){ + + predictionAnalysisListFile <- system.file(""settings"", + ""predictionAnalysisList.json"", + package = ""finalWoo"") + + #figure1 <- 'vignettes/Figure1.png' + figure1 <- system.file(""doc"", + ""Figure1.png"", + package = ""PatientLevelPrediction"") + + #============== STYLES ======================================================= + style_title <- officer::shortcuts$fp_bold(font.size = 28) + style_title_italic <- officer::shortcuts$fp_bold(font.size = 30, italic = TRUE) + style_toc <- officer::shortcuts$fp_bold(font.size = 16) + style_helper_text <- officer::shortcuts$fp_italic(color = ""#FF8C00"") + style_citation <- officer::shortcuts$fp_italic(shading.color = ""grey"") + style_table_title <- officer::shortcuts$fp_bold(font.size = 14, italic = TRUE) + + style_hidden_text <- officer::shortcuts$fp_italic(color = ""#FFFFFF"") + + #============== VARIABLES ==================================================== + json <- tryCatch({ParallelLogger::loadSettingsFromJson(file=predictionAnalysisListFile)}, + error=function(cond) { + stop('Issue with json file...') + }) + + #analysis information + analysisList <- PatientLevelPrediction::loadPredictionAnalysisList(predictionAnalysisListFile) + + targetCohortNamesList <- paste(analysisList$cohortNames, collapse = ', ') + targetCohorts <- as.data.frame(cbind(analysisList$cohortIds,analysisList$cohortNames,rep(""TBD"",length(analysisList$cohortNames))), stringsAsFactors = FALSE) + names(targetCohorts) <- c(""Cohort ID"", ""Cohort Name"",""Description"") + targetCohorts <- targetCohorts[order(as.numeric(targetCohorts$`Cohort ID`)),] + + outcomeCohortNamesList <- paste(analysisList$outcomeNames, collapse = ', ') + outcomeCohorts <- as.data.frame(cbind(analysisList$outcomeIds,analysisList$outcomeNames,rep(""TBD"",length(analysisList$outcomeNames))), stringsAsFactors = FALSE) + names(outcomeCohorts) <- c(""Cohort ID"", ""Cohort Name"",""Description"") + outcomeCohorts <- outcomeCohorts[order(as.numeric(outcomeCohorts$`Cohort ID`)),] + + #time at risk + tar <- unique( + lapply(json$populationSettings, function(x) + paste0(""Risk Window Start: "",x$riskWindowStart, + ', Add Exposure Days to Start: ',x$addExposureDaysToStart, + ', Risk Window End: ', x$riskWindowEnd, + ', Add Exposure Days to End: ', x$addExposureDaysToEnd))) + tarDF <- as.data.frame(rep(times = length(tar),''), stringsAsFactors = FALSE) + names(tarDF) <- c(""Time at Risk"") + for(i in 1:length(tar)){ + tarDF[i,1] <- paste0(""[Time at Risk Settings #"", i, '] ', tar[[i]]) + } + tarList <- paste(tarDF$`Time at Risk`, collapse = ', ') + tarListDF <- as.data.frame(tarList) + + covSettings <- lapply(json$covariateSettings, function(x) cbind(names(x), unlist(lapply(x, function(x2) paste(x2, collapse=', '))))) + + popSettings <- lapply(json$populationSettings, function(x) cbind(names(x), unlist(lapply(x, function(x2) paste(x2, collapse=', '))))) + + + plpModelSettings <- PatientLevelPrediction::createPlpModelSettings(modelList = analysisList$modelAnalysisList$models, + covariateSettingList = json$covariateSettings, + populationSettingList = json$populationSettings) + m1 <-merge(targetCohorts$`Cohort Name`,outcomeCohorts$`Cohort Name`) + names(m1) <- c(""Target Cohort Name"",""Outcome Cohort Name"") + modelSettings <- unique(data.frame(plpModelSettings$settingLookupTable$modelSettingId,plpModelSettings$settingLookupTable$modelSettingName)) + names(modelSettings) <- c(""Model Settings Id"", ""Model Settings Description"") + m2 <- merge(m1,modelSettings) + covSet <- unique(data.frame(plpModelSettings$settingLookupTable$covariateSettingId)) + names(covSet) <- ""Covariate Settings ID"" + m3 <- merge(m2,covSet) + popSet <-unique(data.frame( plpModelSettings$settingLookupTable$populationSettingId)) + names(popSet) <- c(""Population Settings ID"") + completeAnalysisList <- merge(m3,popSet) + completeAnalysisList$ID <- seq.int(nrow(completeAnalysisList)) + + concepts <- formatConcepts(json) + #----------------------------------------------------------------------------- + + #============== CITATIONS ===================================================== + plpCitation <- paste0(""Citation: "", utils::citation(""PatientLevelPrediction"")$textVersion) + tripodCitation <- paste0(""Citation: Collins, G., et al. (2017.02.01). 'Transparent reporting of a multivariable prediction model for individual prognosis or diagnosis (TRIPOD): The TRIPOD statement.' from https://www.equator-network.org/reporting-guidelines/tripod-statement/ "") + progressCitation <- paste0(""Citation: Steyerberg EW, Moons KG, van der Windt DA, Hayden JA, Perel P, Schroter S, Riley RD, Hemingway H, Altman DG; PROGRESS Group. Prognosis Research Strategy (PROGRESS) 3: prognostic model research. PLoS Med. 2013;10(2):e1001381. doi: 10.1371/journal.pmed.1001381. Epub 2013 Feb 5. Review. PubMed PMID: 23393430; PubMed Central PMCID: PMC3564751."") + rCitation <- paste0(""Citation: R Core Team (2013). R: A language and environment for statistical computing. R Foundation for Statistical Computing, Vienna, Austria. URL http://www.R-project.org/."") + #----------------------------------------------------------------------------- + + #============== CREATE DOCUMENT ============================================== + # create new word document + doc = officer::read_docx() + #----------------------------------------------------------------------------- + + #============ TITLE PAGE ===================================================== + title <- officer::fpar( + officer::ftext(""Patient-Level Prediction: "", prop = style_title), + officer::ftext(json$packageName, prop = style_title_italic) + ) + + doc <- doc %>% + officer::body_add_par("""") %>% + officer::body_add_par("""") %>% + officer::body_add_par("""") %>% + officer::body_add_fpar(title) %>% + officer::body_add_par("""") %>% + officer::body_add_par("""") %>% + officer::body_add_par(paste0(""Prepared on: "", Sys.Date()), style = ""Normal"") %>% + officer::body_add_par(paste0(""Created by: "", json$createdBy$name, "" ("", json$createdBy$email,"")""), style = ""Normal"") %>% + officer::body_add_break() + #----------------------------------------------------------------------------- + + #============ TOC ============================================================ + toc <- officer::fpar( + officer::ftext(""Table of Contents"", prop = style_toc) + ) + + doc <- doc %>% + officer::body_add_fpar(toc) %>% + officer::body_add_toc(level = 2) %>% + officer::body_add_break() + #----------------------------------------------------------------------------- + + #============ LIST OF ABBREVIATIONS ========================================== + abb <- data.frame(rbind( + c(""AUC"", ""Area Under the Receiver Operating Characteristic Curve""), + c(""CDM"",""Common Data Model""), + c(""O"",""Outcome Cohort""), + c(""OHDSI"",""Observational Health Data Sciences & Informatics""), + c(""OMOP"",""Observational Medical Outcomes Partnership""), + c(""T"", ""Target Cohort""), + c(""TAR"", ""Time at Risk"") + )) + names(abb) <- c(""Abbreviation"",""Phrase"") + abb <- abb[order(abb$Abbreviation),] + + doc <- doc %>% + officer::body_add_par(""List of Abbreviations"", style = ""heading 1"") %>% + officer::body_add_par("""") %>% + officer::body_add_table(abb, header = TRUE) %>% + officer::body_add_par("""") %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(""<< Rest to be completed outside of ATLAS >>"", prop = style_helper_text) + )) + #----------------------------------------------------------------------------- + + + #============ RESPONSIBLE PARTIES ============================================ + doc <- doc %>% + officer::body_add_par(""Responsible Parties"", style = ""heading 1"") %>% + officer::body_add_par("""") %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(""<< To be completed outside of ATLAS "", prop = style_helper_text) + )) %>% + officer::body_add_par("""") %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(""Includes author, investigator, and reviewer names and sponsor information. >>"", prop = style_helper_text) + )) + #----------------------------------------------------------------------------- + + #============ Executive Summary ============================================== + doc <- doc %>% + officer::body_add_par(""Executive Summary"", style = ""heading 1"") %>% + officer::body_add_par("""") %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(""<< A few statements about the rational and background for this study. >>"", prop = style_helper_text) + )) %>% + officer::body_add_par("""") %>% + officer::body_add_par(paste0(""The objective of this study is to develop and validate patient-level prediction models for patients in "", + length(json$targetIds),"" target cohort(s) ("", + targetCohortNamesList,"") to predict "", + length(json$outcomeIds),"" outcome(s) ("", + outcomeCohortNamesList,"") for "", + length(tar),"" time at risk(s) ("", + tarList,"").""), + style = ""Normal"") %>% + officer::body_add_par("""") %>% + officer::body_add_par(paste0(""The prediction will be implemented using "", + length(json$modelSettings),"" algorithms ("", + paste(lapply(analysisList$modelAnalysisList$models, function(x) x$name), collapse = ', '),"").""), + style = ""Normal"") + #----------------------------------------------------------------------------- + + #============ RATIONAL & BACKGROUND ========================================== + doc <- doc %>% + officer::body_add_par(""Rational & Background"", style = ""heading 1"") %>% + officer::body_add_par("""") %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(""<< To be completed outside of ATLAS."", prop = style_helper_text) + )) %>% + officer::body_add_par("""") %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(""Provide a short description of the reason that led to the initiation of or need for the study and add a short critical review of available published and unpublished data to explain gaps in knowledge that the study is intended to fill. >>"", prop = style_helper_text) + )) + #----------------------------------------------------------------------------- + + #============ OBJECTIVE ====================================================== + prep_objective <- merge(analysisList$cohortNames, analysisList$outcomeNames) + objective <- merge(prep_objective, tarListDF ) + names(objective) <-c(""Target Cohorts"",""Outcome Cohorts"",""Time at Risk"") + + doc <- doc %>% + officer::body_add_par(""Objective"", style = ""heading 1"") %>% + officer::body_add_par("""") %>% + officer::body_add_par(paste0(""The objective is to develop and validate patient-level prediction models for the following prediction problems:""),style = ""Normal"") %>% + officer::body_add_par("""") %>% + officer::body_add_table(objective, header = TRUE, style = ""Table Professional"") + + #----------------------------------------------------------------------------- + + #============ METHODS ====================================================== + doc <- doc %>% + officer::body_add_par(""Methods"", style = ""heading 1"") %>% + #``````````````````````````````````````````````````````````````````````````` + officer::body_add_par(""Study Design"", style = ""heading 2"") %>% + officer::body_add_par(""This study will follow a retrospective, observational, patient-level prediction design. We define 'retrospective' to mean the study will be conducted using data already collected prior to the start of the study. We define 'observational' to mean there is no intervention or treatment assignment imposed by the study. We define 'patient-level prediction' as a modeling process wherein an outcome is predicted within a time at risk relative to the target cohort start and/or end date. Prediction is performed using a set of covariates derived using data prior to the start of the target cohort."",style = ""Normal"") %>% + officer::body_add_par("""") %>% + officer::body_add_par(""Figure 1, illustrates the prediction problem we will address. Among a population at risk, we aim to predict which patients at a defined moment in time (t = 0) will experience some outcome during a time-at-risk. Prediction is done using only information about the patients in an observation window prior to that moment in time."", style=""Normal"") %>% + officer::body_add_par("""") %>% + officer::body_add_img(src = figure1, width = 6.5, height = 2.01, style = ""centered"") %>% + officer::body_add_par(""Figure 1: The prediction problem"", style=""graphic title"") %>% + officer::body_add_par("""") %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(plpCitation, prop = style_citation) + )) %>% + officer::body_add_par("""") %>% + officer::body_add_par(""We follow the PROGRESS best practice recommendations for model development and the TRIPOD guidance for transparent reporting of the model results."", style=""Normal"") %>% + officer::body_add_par("""") %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(progressCitation, prop = style_citation) + )) %>% + officer::body_add_par("""") %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(tripodCitation, prop = style_citation) + )) %>% + #``````````````````````````````````````````````````````````````````````````` + officer::body_add_par(""Data Source(s)"", style = ""heading 2"") %>% + officer::body_add_par("""") %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(""<< To be completed outside of ATLAS."", prop = style_helper_text) + )) %>% + officer::body_add_par("""") %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(""For each database, provide database full name, version information (if applicable), the start and end dates of data capture, and a brief description of the data source. Also include information on data storage (e.g. software and IT environment, database maintenance and anti-fraud protection, archiving) and data protection."", prop = style_helper_text) + )) %>% + officer::body_add_par("""") %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(""Important Citations: OMOP Common Data Model: 'OMOP Common Data Model (CDM).' from https://github.com/OHDSI/CommonDataModel."", prop = style_helper_text) + )) %>% + #``````````````````````````````````````````````````````````````````````````` + officer::body_add_par(""Study Populations"", style = ""heading 2"") %>% + officer::body_add_par(""Target Cohort(s) [T]"", style = ""heading 3"") %>% + officer::body_add_par("""") %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(""<< Currently cohort definitions need to be grabbed from ATLAS, in a Cohort Definition, Export Tab, from Text View. >>"", prop = style_helper_text) + )) %>% + officer::body_add_par("""") %>% + officer::body_add_table(targetCohorts, header = TRUE, style = ""Table Professional"") %>% + officer::body_add_par("""") %>% + officer::body_add_par(""Outcome Cohorts(s) [O]"", style = ""heading 3"") %>% + officer::body_add_par("""") %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(""<< Currently cohort definitions need to be grabbed from ATLAS, in a Cohort Definition, Export Tab, from Text View. >>"", prop = style_helper_text) + )) %>% + officer::body_add_par("""") %>% + officer::body_add_table(outcomeCohorts, header = TRUE, style = ""Table Professional"") %>% + officer::body_add_par("""") %>% + officer::body_add_par(""Time at Risk"", style = ""heading 3"") %>% + officer::body_add_par("""") %>% + officer::body_add_table(tarDF, header = TRUE, style = ""Table Professional"") %>% + officer::body_add_par(""Additional Population Settings"", style = ""heading 3"") %>% + officer::body_add_par("""") + + for(i in 1:length(popSettings)){ + onePopSettings <- as.data.frame(popSettings[i]) + names(onePopSettings) <- c(""Item"",""Settings"") + + doc <- doc %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(paste0(""Population Settings #"",i), prop = style_table_title) + )) %>% + officer::body_add_table(onePopSettings, header = TRUE, style = ""Table Professional"") %>% + officer::body_add_par("""") + } + + #``````````````````````````````````````````````````````````````````````````` + algorithms <- data.frame(rbind( + c(""Lasso Logistic Regression"", ""Lasso logistic regression belongs to the family of generalized linear models, where a linear combination of the variables is learned and finally a logistic function maps the linear combination to a value between 0 and 1. The lasso regularization adds a cost based on model complexity to the objective function when training the model. This cost is the sum of the absolute values of the linear combination of the coefficients. The model automatically performs feature selection by minimizing this cost. We use the Cyclic coordinate descent for logistic, Poisson and survival analysis (Cyclops) package to perform large-scale regularized logistic regression: https://github.com/OHDSI/Cyclops""), + c(""Gradient boosting machine"", ""Gradient boosting machines is a boosting ensemble technique and in our framework it combines multiple decision trees. Boosting works by iteratively adding decision trees but adds more weight to the data-points that are misclassified by prior decision trees in the cost function when training the next tree. We use Extreme Gradient Boosting, which is an efficient implementation of the gradient boosting framework implemented in the xgboost R package available from CRAN.""), + c(""Random forest"", ""Random forest is a bagging ensemble technique that combines multiple decision trees. The idea behind bagging is to reduce the likelihood of overfitting, by using weak classifiers, but combining multiple diverse weak classifiers into a strong classifier. Random forest accomplishes this by training multiple decision trees but only using a subset of the variables in each tree and the subset of variables differ between trees. Our packages uses the sklearn learn implementation of Random Forest in python.""), + c(""KNN"", ""K-nearest neighbors (KNN) is an algorithm that uses some metric to find the K closest labelled data-points, given the specified metric, to a new unlabelled data-point. The prediction of the new data-points is then the most prevalent class of the K-nearest labelled data-points. There is a sharing limitation of KNN, as the model requires labelled data to perform the prediction on new data, and it is often not possible to share this data across data sites. We included the BigKnn classifier developed in OHDSI which is a large scale k-nearest neighbor classifier using the Lucene search engine: https://github.com/OHDSI/BigKnn""), + c(""AdaBoost"", ""AdaBoost is a boosting ensemble technique. Boosting works by iteratively adding decision trees but adds more weight to the data-points that are misclassified by prior decision trees in the cost function when training the next tree. We use the sklearn 'AdaboostClassifier' implementation in Python.""), + c(""DecisionTree"", ""A decision tree is a classifier that partitions the variable space using individual tests selected using a greedy approach. It aims to find partitions that have the highest information gain to separate the classes. The decision tree can easily overfit by enabling a large number of partitions (tree depth) and often needs some regularization (e.g., pruning or specifying hyper-parameters that limit the complexity of the model). We use the sklearn 'DecisionTreeClassifier' implementation in Python.""), + c(""Neural network"", ""Neural networks contain multiple layers that weight their inputs using an non-linear function. The first layer is the input layer, the last layer is the output layer the between are the hidden layers. Neural networks are generally trained using feed forward back-propagation. This is when you go through the network with a data-point and calculate the error between the true label and predicted label, then go backwards through the network and update the linear function weights based on the error. This can also be performed as a batch, where multiple data-points are feed through the network before being updated. We use the sklearn 'MLPClassifier' implementation in Python.""), + c(""Naive Bayes"",""The Naive Bayes algorithm applies the Bayes' theorem with the 'naive' assumption of conditional independence between every pair of features given the value of the class variable. Based on the likelihood of the data belong to a class and the prior distribution of the class, a posterior distribution is obtained."") + )) + names(algorithms) <- c(""Algorithm"",""Description"") + algorithms <- algorithms[order(algorithms$Algorithm),] + + modelIDs <- as.data.frame(sapply(analysisList$modelAnalysisList$models, function(x) x$name)) + names(modelIDs) <- c(""ID"") + algorithmsFiltered <- algorithms[algorithms$Algorithm %in% modelIDs$ID,] + + modelEvaluation <- data.frame(rbind( + c(""ROC Plot"", ""The ROC plot plots the sensitivity against 1-specificity on the test set. The plot shows how well the model is able to discriminate between the people with the outcome and those without. The dashed diagonal line is the performance of a model that randomly assigns predictions. The higher the area under the ROC plot the better the discrimination of the model.""), + c(""Calibration Plot"", ""The calibration plot shows how close the predicted risk is to the observed risk. The diagonal dashed line thus indicates a perfectly calibrated model. The ten (or fewer) dots represent the mean predicted values for each quantile plotted against the observed fraction of people in that quantile who had the outcome (observed fraction). The straight black line is the linear regression using these 10 plotted quantile mean predicted vs observed fraction points. The two blue straight lines represented the 95% lower and upper confidence intervals of the slope of the fitted line.""), + c(""Smooth Calibration Plot"", ""Similar to the traditional calibration shown above the Smooth Calibration plot shows the relationship between predicted and observed risk. the major difference is that the smooth fit allows for a more fine grained examination of this. Whereas the traditional plot will be heavily influenced by the areas with the highest density of data the smooth plot will provide the same information for this region as well as a more accurate interpretation of areas with lower density. the plot also contains information on the distribution of the outcomes relative to predicted risk. However the increased information game comes at a computational cost. It is recommended to use the traditional plot for examination and then to produce the smooth plot for final versions.""), + c(""Prediction Distribution Plots"", ""The preference distribution plots are the preference score distributions corresponding to i) people in the test set with the outcome (red) and ii) people in the test set without the outcome (blue).""), + c(""Box Plots"", ""The prediction distribution boxplots are box plots for the predicted risks of the people in the test set with the outcome (class 1: blue) and without the outcome (class 0: red).""), + c(""Test-Train Similarity Plot"", ""The test-train similarity is presented by plotting the mean covariate values in the train set against those in the test set for people with and without the outcome.""), + c(""Variable Scatter Plot"", ""The variable scatter plot shows the mean covariate value for the people with the outcome against the mean covariate value for the people without the outcome. The size and color of the dots correspond to the importance of the covariates in the trained model (size of beta) and its direction (sign of beta with green meaning positive and red meaning negative), respectively.""), + c(""Precision Recall Plot"", ""The precision-recall curve is valuable for dataset with a high imbalance between the size of the positive and negative class. It shows the tradeoff between precision and recall for different threshold. High precision relates to a low false positive rate, and high recall relates to a low false negative rate. High scores for both show that the classifier is returning accurate results (high precision), as well as returning a majority of all positive results (high recall). A high area under the curve represents both high recall and high precision.""), + c(""Demographic Summary Plot"", ""This plot shows for females and males the expected and observed risk in different age groups together with a confidence area."") + )) + names(modelEvaluation) <- c(""Evaluation"",""Description"") + modelEvaluation <- modelEvaluation[order(modelEvaluation$Evaluation),] + + doc <- doc %>% + officer::body_add_par(""Statistical Analysis Method(s)"", style = ""heading 2"") %>% + officer::body_add_par(""Algorithms"", style = ""heading 3"") %>% + officer::body_add_par("""") %>% + officer::body_add_table(algorithmsFiltered, header = TRUE, style = ""Table Professional"") %>% + officer::body_add_par("""") %>% + officer::body_add_par(""Model Evaluation"", style = ""heading 3"") %>% + officer::body_add_par("""") %>% + officer::body_add_par(""The following evaluations will be performed on the model:"", style = ""Normal"") %>% + officer::body_add_par("""") %>% + officer::body_add_table(modelEvaluation, header = TRUE, style = ""Table Professional"") %>% + officer::body_add_par("""") %>% + #``````````````````````````````````````````````````````````````````````````` + officer::body_add_par(""Quality Control"", style = ""heading 2"") %>% + officer::body_add_par("""") %>% + officer::body_add_par(""The PatientLevelPrediction package itself, as well as other OHDSI packages on which PatientLevelPrediction depends, use unit tests for validation."",style=""Normal"") %>% + officer::body_add_par("""") %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(plpCitation, prop = style_citation) + )) %>% + #``````````````````````````````````````````````````````````````````````````` + officer::body_add_par(""Tools"", style = ""heading 2"") %>% + officer::body_add_par("""") %>% + officer::body_add_par(""This study will be designed using OHDSI tools and run with R."",style=""Normal"") %>% + officer::body_add_par("""") %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(rCitation, prop = style_citation) + )) %>% + officer::body_add_par("""") %>% + officer::body_add_par(""More information about the tools can be found in the Appendix 'Study Generation Version Information'."", style = ""Normal"") + #----------------------------------------------------------------------------- + + #============ DIAGNOSTICS ==================================================== + doc <- doc %>% + officer::body_add_par(""Diagnostics"", style = ""heading 1"") %>% + officer::body_add_par("""") %>% + officer::body_add_par(""Reviewing the incidence rates of the outcomes in the target population prior to performing the analysis will allow us to assess its feasibility. The full table can be found in the 'Table and Figures' section under 'Incidence Rate of Target & Outcome'."",style=""Normal"") %>% + officer::body_add_par("""") %>% + officer::body_add_par(""Additionally, reviewing the characteristics of the cohorts provides insight into the cohorts being reviewed. The full table can be found below in the 'Table and Figures' section under 'Characterization'."",style=""Normal"") + #----------------------------------------------------------------------------- + + #============ DATA ANALYSIS PLAN ============================================= + + doc <- doc %>% + officer::body_add_par(""Data Analysis Plan"", style = ""heading 1"") %>% + #``````````````````````````````````````````````````````````````````````````` + officer::body_add_par(""Algorithm Settings"", style = ""heading 2"") %>% + officer::body_add_par("""") + + for(i in 1:length(json$modelSettings)){ + + modelSettingsTitle <- names(json$modelSettings[[i]]) + modelSettings <- lapply(json$modelSettings[[i]], function(x) cbind(names(x), unlist(lapply(x, function(x2) paste(x2, collapse=', '))))) + + oneModelSettings <- as.data.frame(modelSettings) + names(oneModelSettings) <- c(""Covariates"",""Settings"") + + doc <- doc %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(paste0(""Model Settings Settings #"",i, "" - "",modelSettingsTitle), prop = style_table_title) + )) %>% + officer::body_add_table(oneModelSettings, header = TRUE, style = ""Table Professional"") %>% + officer::body_add_par("""") + } + + #``````````````````````````````````````````````````````````````````````````` + covStatement1 <- paste0(""The covariates (constructed using records on or prior to the target cohort start date) are used within this prediction mode include the following."") + covStatement2 <- paste0("" Each covariate needs to contain at least "", + json$runPlpArgs$minCovariateFraction, + "" subjects to be considered for the model."") + + if(json$runPlpArgs$minCovariateFraction == 0){ + covStatement <- covStatement1 + }else { + covStatement <- paste0(covStatement1,covStatement2) + } + + doc <- doc %>% + officer::body_add_par(""Covariate Settings"", style = ""heading 2"") %>% + officer::body_add_par("""") %>% + officer::body_add_par(covStatement, + style=""Normal"") %>% + officer::body_add_par("""") + + for(i in 1:length(covSettings)){ + oneCovSettings <- as.data.frame(covSettings[i]) + names(oneCovSettings) <- c(""Covariates"",""Settings"") + + doc <- doc %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(paste0(""Covariate Settings #"",i), prop = style_table_title) + )) %>% + officer::body_add_table(oneCovSettings, header = TRUE, style = ""Table Professional"") %>% + officer::body_add_par("""") + } + #``````````````````````````````````````````````````````````````````````````` + doc <- doc %>% + officer::body_add_par(""Model Development & Evaluation"", style = ""heading 2"") %>% + officer::body_add_par("""") %>% + officer::body_add_par(paste0(""To build and internally validate the models, we will partition the labelled data into a train set ("", + (1-analysisList$testFraction)*100, + ""%) and a test set ("", + analysisList$testFraction*100, + ""%).""), + style = ""Normal"") %>% + officer::body_add_par("""") %>% + officer::body_add_par(paste0(""The hyper-parameters for the models will be assessed using "", + analysisList$nfold, + ""-fold cross validation on the train set and a final model will be trained using the full train set and optimal hyper-parameters.""), + style = ""Normal"") %>% + officer::body_add_par("""") %>% + officer::body_add_par(""The internal validity of the models will be assessed on the test set. We will use the area under the receiver operating characteristic curve (AUC) to evaluate the discriminative performance of the models and plot the predicted risk against the observed fraction to visualize the calibration. See 'Model Evaluation' section for more detailed information about additional model evaluation metrics."") %>% + officer::body_add_par("""") %>% + #``````````````````````````````````````````````````````````````````````````` + officer::body_add_par(""Analysis Execution Settings"", style = ""heading 2"") %>% + officer::body_add_par("""") %>% + officer::body_add_par(paste0(""There are "", + length(json$targetIds), + "" target cohorts evaluated for "", + length(json$outcomeIds), + "" outcomes over "", + length(json$modelSettings), + "" models over "", + length(covSettings), + "" covariates settings and over "", + length(popSettings), + "" population settings. In total there are "", + length(json$targetIds) * length(json$outcomeIds) * length(json$modelSettings) * length(covSettings) * length(popSettings), + "" analysis performed. For a full list refer to appendix 'Complete Analysis List'.""), + style = ""Normal"") %>% + officer::body_add_par("""") + #----------------------------------------------------------------------------- + + #============ STRENGTHS & LIMITATIONS ======================================== + doc <- doc %>% + officer::body_add_par(""Strengths & Limitations"", style = ""heading 1"") %>% + officer::body_add_par("""") %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(""<< To be completed outside of ATLAS."", prop = style_helper_text) + )) %>% + officer::body_add_par("""") %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(""Some limitations to consider:"", + prop = style_helper_text), + officer::ftext(""--It may not be possible to develop prediction models for rare outcomes. "", + prop = style_helper_text), + officer::ftext(""--Not all medical events are recorded into the observational datasets and some recordings can be incorrect. This could potentially lead to outcome misclassification."", + prop = style_helper_text), + officer::ftext(""--The prediction models are only applicable to the population of patients represented by the data used to train the model and may not be generalizable to the wider population. >>"", + prop = style_helper_text) + )) + + #----------------------------------------------------------------------------- + + #============ PROTECTION OF HUMAN SUBJECTS =================================== + doc <- doc %>% + officer::body_add_par(""Protection of Human Subjects"", style = ""heading 1"") %>% + officer::body_add_par("""") %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(""<< To be completed outside of ATLAS."", prop = style_helper_text) + )) %>% + officer::body_add_par("""") %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(""Describe any additional safeguards that are appropriate for the data being used."", + prop = style_helper_text) + )) %>% + officer::body_add_par("""") %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(""Here is an example statement:"", prop = style_helper_text), + officer::ftext(""Confidentiality of patient records will be maintained always. All study reports will contain aggregate data only and will not identify individual patients or physicians. At no time during the study will the sponsor receive patient identifying information except when it is required by regulations in case of reporting adverse events."", prop = style_helper_text), + officer::ftext("">>"", prop = style_helper_text) + )) + #----------------------------------------------------------------------------- + + #============ DISSEMINATING & COMMUNICATING ================================== + doc <- doc %>% + officer::body_add_par(""Plans for Disseminating & Communicating Study Results"", style = ""heading 1"") %>% + officer::body_add_par("""") %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(""<< To be completed outside of ATLAS."", prop = style_helper_text) + )) %>% + officer::body_add_par("""") %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(""List any plans for submission of progress reports, final reports, and publications."", + prop = style_helper_text), + officer::ftext("">>"", + prop = style_helper_text) + )) %>% + officer::body_add_break() + + #----------------------------------------------------------------------------- + + #============ TABLES & FIGURES =============================================== + doc <- doc %>% + officer::body_add_par(""Tables & Figures"", style = ""heading 1"") %>% + #``````````````````````````````````````````````````````````````````````````` + officer::body_add_par(""Incidence Rate of Target & Outcome"", style = ""heading 2"") %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(""<< add incidence here. >>"", prop = style_hidden_text) + )) %>% + officer::body_add_par("""") %>% + #``````````````````````````````````````````````````````````````````````````` + officer::body_add_par(""Characterization"", style = ""heading 2"") %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(""<< add characterization table here. >>"", prop = style_hidden_text) + )) %>% + officer::body_add_par("""") %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(""<< add results here. >>"", prop = style_hidden_text) + )) %>% + officer::body_add_break() + #----------------------------------------------------------------------------- + + #============ APPENDICES ===================================================== + doc <- doc %>% + officer::body_add_par(""Appendices"", style = ""heading 1"") %>% + #``````````````````````````````````````````````````````````````````````````` + officer::body_add_par(""Study Generation Version Information"", style = ""heading 2"") %>% + officer::body_add_par("""") %>% + officer::body_add_par(paste0(""Skeleton Version: "",json$skeletonType,"" - "", json$skeletonVersion),style=""Normal"") %>% + officer::body_add_par(paste0(""Identifier / Organization: "",json$organizationName),style=""Normal"") %>% + officer::body_add_break() %>% + officer::body_end_section_continuous() %>% + #``````````````````````````````````````````````````````````````````````````` + officer::body_add_par(""Code List"", style = ""heading 2"") %>% + officer::body_add_par("""") + + for(i in 1:length(concepts$uniqueConceptSets)){ + conceptSetId <- paste0(""Concept Set #"",concepts$uniqueConceptSets[[i]]$conceptId, + "" - "",concepts$uniqueConceptSets[[i]]$conceptName) + conceptSetTable <- as.data.frame(concepts$uniqueConceptSets[[i]]$conceptExpressionTable) + + id <- as.data.frame(concepts$conceptTableSummary[which(concepts$conceptTableSummary$newConceptId == i),]$cohortDefinitionId) + names(id) <- c(""ID"") + outcomeCohortsForConceptSet <- outcomeCohorts[outcomeCohorts$`Cohort ID` %in% id$ID,] + targetCohortsForConceptSet <- targetCohorts[targetCohorts$`Cohort ID` %in% id$ID,] + + cohortsForConceptSet <- rbind(outcomeCohortsForConceptSet,targetCohortsForConceptSet) + cohortsForConceptSet <- cohortsForConceptSet[,1:2] + + doc <- doc %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(conceptSetId, prop = style_table_title) + )) %>% + officer::body_add_table(conceptSetTable[,c(1,2,4,6,7,8,9,10,11,12)], header = TRUE, style = ""Table Professional"") %>% + officer::body_add_par("""") %>% + officer::body_add_par(""Cohorts that use this Concept Set:"", style = ""Normal"") %>% + officer::body_add_par("""") %>% + officer::body_add_table(cohortsForConceptSet, header = TRUE, style = ""Table Professional"") %>% + officer::body_add_par("""") + + } + + #``````````````````````````````````````````````````````````````````````````` + doc <- doc %>% + officer::body_add_break() %>% + officer::body_end_section_landscape() %>% + officer::body_add_par(""Complete Analysis List"", style = ""heading 2"") %>% + officer::body_add_par("""") %>% + officer::body_add_par(""Below is a complete list of analysis that will be performed. Definitions for the column 'Covariate Settings ID' can be found above in the 'Covariate Settings' section. Definitions for the 'Population Settings Id' can be found above in the 'Additional Population Settings' section."",style=""Normal"") %>% + officer::body_add_par("""") %>% + officer::body_add_table(completeAnalysisList[,c(7,1,2,3,4,5,6)], header = TRUE, style = ""Table Professional"") %>% + officer::body_add_break() + + + doc <- doc %>% officer::body_add_fpar( + officer::fpar( + officer::ftext(""<< add models here >>"", prop = style_hidden_text) + )) %>% officer::body_add_par("""") + #----------------------------------------------------------------------------- + + #============ REFERNCES ====================================================== + doc <- doc %>% + officer::body_add_par(""References"", style = ""heading 1"") %>% + officer::body_add_par("""") %>% + officer::body_add_fpar( + officer::fpar( + officer::ftext(""<< To be completed outside of ATLAS. >>"", prop = style_helper_text) + )) + #----------------------------------------------------------------------------- + + if(!dir.exists(outputLocation)){ + dir.create(outputLocation, recursive = T) + } + print(doc, target = file.path(outputLocation,'protocol.docx')) +} + + +#' createMultiPlpReport +#' +#' @description +#' Creates a word document report of the prediction +#' @details +#' The function creates a word document containing the analysis details, data summary and prediction model results. +#' @param analysisLocation The location of the multiple patient-level prediction study +#' @param protocolLocation The location of the auto generated patient-level prediction protocol +#' @param includeModels Whether to include the models into the results document +#' +#' @return +#' A work document containing the results of the study is saved into the doc directory in the analysisLocation +#' @export +createMultiPlpReport <- function(analysisLocation, + protocolLocation = file.path(analysisLocation,'doc','protocol.docx'), + includeModels = F){ + + if(!dir.exists(analysisLocation)){ + stop('Directory input for analysisLocation does not exists') + } + + # this fucntion creates a lsit for analysis with + # internal validation table, internal validation plots + # external validation table, external validation plots + modelsExtraction <- getModelInfo(analysisLocation) + + # add checks for suitable files expected - protocol/summary + if(!file.exists(protocolLocation)){ + stop('Protocol location invalid') + } + + #================ Check for protocol ========================= + # if exists load it and add results section - else return error + doc = tryCatch(officer::read_docx(path=protocolLocation), + error = function(e) stop(e)) + + heading1 <- 'heading 1' + heading2 <- 'heading 2' + heading3 <- 'heading 3' + tableStyle <- ""Table Professional"" + + # Find the sections to add the results to (results + appendix) + + doc %>% + officer::cursor_reach(keyword = ""<< add results here. >>"") %>% officer::cursor_forward() %>% + officer::body_add_par(""Results"", style = heading1) + + for(model in modelsExtraction){ + if(!is.null(model$internalPerformance)){ + doc %>% officer::body_add_par(paste('Analysis',model$analysisId), style = heading2) %>% + officer::body_add_par('Description', style = heading3) %>% + officer::body_add_par(paste0(""The predicton model within "", model$T, + "" predict "", model$O, "" during "", model$tar, + "" developed using database "", model$D), + style = ""Normal"") %>% + officer::body_add_par("""") %>% + officer::body_add_par(""Internal Performance"", style = heading3) %>% + officer::body_add_table(model$internalPerformance, style = tableStyle) %>% + officer::body_add_gg(model$scatterPlot) + if(!is.null(model$internalPlots[[7]])){ + doc %>% rvg::body_add_vg(code = do.call(gridExtra::grid.arrange, c(model$internalPlots, list(layout_matrix=rbind(c(1,2), + c(3,4), + c(5,6), + c(7,7), + c(7,7), + c(8,8), + c(9,9) + )))))} else{ + model$internalPlots[[7]] <- NULL + doc %>% rvg::body_add_vg(code = do.call(gridExtra::grid.arrange, c(model$internalPlots, list(layout_matrix=rbind(c(1,2), + c(3,4), + c(5,6), + c(7,7), + c(8,8) + ))))) + } + } + + if(!is.null(model$externalPerformance)){ + doc %>% officer::body_add_par("""") %>% + officer::body_add_par(""External Performance"", style = heading3) %>% + officer::body_add_table(model$externalPerformance, style = tableStyle) %>% + rvg::body_add_vg(code = do.call(gridExtra::grid.arrange, model$externalRocPlots)) %>% + rvg::body_add_vg(code = do.call(gridExtra::grid.arrange, model$externalCalPlots)) + } + + doc %>% officer::body_add_break() + + } + + + + if(includeModels){ + # move the cursor at the end of the document + doc %>% + officer::cursor_reach(keyword = ""<< add models here >>"") %>% officer::cursor_forward() %>% + officer::body_add_par(""Developed Models"", style = heading2) + + for(model in modelsExtraction){ + if(!is.null(model$modelTable)){ + doc %>% officer::body_add_par(paste('Analysis',model$analysisId), style = heading3) %>% + officer::body_add_table(model$modelTable, style = tableStyle) %>% + officer::body_add_break() + } + } + } + + # print the document to the doc directory: + if(!dir.exists(file.path(analysisLocation,'doc'))){ + dir.create(file.path(analysisLocation,'doc'), recursive = T) + } + print(doc, target = file.path(analysisLocation,'doc','plpMultiReport.docx')) + return(TRUE) +} + +getModelInfo <- function(analysisLocation){ + settings <- utils::read.csv(file.path(analysisLocation, ""settings.csv"")) + + modelSettings <- lapply((1:nrow(settings))[order(settings$analysisId)], function(i) {getModelFromSettings(analysisLocation,settings[i,])}) + return(modelSettings) +} + +getModelFromSettings <- function(analysisLocation,x){ + result <- list(analysisId = x$analysisId, T = x$cohortName, + D = x$devDatabase, O = x$outcomeName, + tar = paste0(x$riskWindowStart, ' days after ', + ifelse(x$addExposureDaysToStart==1, 'cohort end','cohort start'), + ' to ', x$riskWindowEnd, ' days after ', + ifelse(x$addExposureDaysToEnd==1, 'cohort end','cohort start')), + model = x$modelSettingName) + + if(!dir.exists(file.path(as.character(x$plpResultFolder),'plpResult'))){ + return(NULL) + } + + plpResult <- PatientLevelPrediction::loadPlpResult(file.path(as.character(x$plpResultFolder),'plpResult')) + modelTable <- plpResult$model$varImp + result$modelTable <- modelTable[modelTable$covariateValue!=0,] + + if(!is.null(plpResult$performanceEvaluation)){ + internalPerformance <- plpResult$performanceEvaluation$evaluationStatistics + internalPerformance <- as.data.frame(internalPerformance) + internalPerformance$Value <- format(as.double(as.character(internalPerformance$Value)), digits = 2, nsmall = 0, scientific = F) + class(internalPerformance$Value) <- 'double' + result$internalPerformance <- reshape2::dcast(internalPerformance, Metric ~ Eval, value.var = 'Value', fun.aggregate = mean) + + result$internalPlots <- list( + PatientLevelPrediction::plotSparseRoc(plpResult$performanceEvaluation), + PatientLevelPrediction::plotPrecisionRecall(plpResult$performanceEvaluation), + PatientLevelPrediction::plotF1Measure(plpResult$performanceEvaluation), + PatientLevelPrediction::plotPredictionDistribution(plpResult$performanceEvaluation), + + PatientLevelPrediction::plotSparseCalibration( plpResult$performanceEvaluation), + PatientLevelPrediction::plotSparseCalibration2( plpResult$performanceEvaluation), + + PatientLevelPrediction::plotDemographicSummary( plpResult$performanceEvaluation), + PatientLevelPrediction::plotPreferencePDF(plpResult$performanceEvaluation), + PatientLevelPrediction::plotPredictedPDF(plpResult$performanceEvaluation) + + )} else{ + result$internalPlots <- NULL + } + + result$scatterPlot <- PatientLevelPrediction::plotVariableScatterplot(plpResult$covariateSummary) + + # get external results if they exist + externalPerformance <- c() + ind <- grep(paste0('Analysis_', x$analysisId,'/'), + dir(file.path(analysisLocation,'Validation'), recursive = T)) + if(length(ind)>0){ + vals <- dir(file.path(analysisLocation,'Validation'), recursive = T)[ind] + externalRocPlots <- list() + externalCalPlots <- list() + length(externalRocPlots) <- length(vals) + length(externalCalPlots) <- length(vals) + for(k in 1:length(vals)){ + val <- vals[k] + nameDat <- strsplit(val, '\\/')[[1]][1] + val <- readRDS(file.path(analysisLocation,'Validation',val)) + sum <- as.data.frame(val[[1]]$performanceEvaluation$evaluationStatistics) + sum$database <- nameDat + externalPerformance <- rbind(externalPerformance, sum) + externalCalPlots[[k]] <- PatientLevelPrediction::plotSparseCalibration2(val[[1]]$performanceEvaluation, type='validation') + ggplot2::labs(title=paste(nameDat)) + externalRocPlots[[k]] <- PatientLevelPrediction::plotSparseRoc(val[[1]]$performanceEvaluation, type='validation')+ ggplot2::labs(title=paste(nameDat)) + } + externalPerformance <- as.data.frame(externalPerformance) + externalPerformance$Value <- format(as.double(as.character(externalPerformance$Value)), digits = 2, nsmall = 0, scientific = F) + class(externalPerformance$Value) <- 'double' + result$externalPerformance <- reshape2::dcast(externalPerformance, Metric ~ database, value.var = 'Value', fun.aggregate = mean) + result$externalCalPlots <- externalCalPlots + result$externalRocPlots <- externalRocPlots + } + + + return(result) +}","R" +"Pharmacogenetics","OHDSI/StudyProtocols","finalWoo/R/readJson.R",".R","2777","64","getCohortConceptExpression <- function(cohortDefinitions){ + lapply(cohortDefinitions$expression$ConceptSets, function(x) + list(originalConceptId = x$id, + originalConceptName = x$name, + conceptTable =do.call(rbind, lapply(x$expression$items, function(y) c(unlist(y$concept), + isExcluded = y$isExcluded, + includeDescendants = y$includeDescendants, + includeMapped = y$includeMapped))))) +} + +getAllConceptExpression <- function(json){ + res <- do.call(c,lapply(json$cohortDefinitions, function(x){ + lapply(getCohortConceptExpression(x), function(x) x$conceptTable)} + )) + + names(res) <- unlist(lapply(json$cohortDefinitions, function(x){ + + if(length(x$expression$ConceptSets)!=0){ + + paste0(x$id,'_',lapply(getCohortConceptExpression(x), function(x) x$originalConceptId ))}} + )) + res +} + +getConceptSum <- function(json){ + do.call(rbind,lapply(json$cohortDefinitions, function(x){ + res <- data.frame( + originalConceptId = unlist(lapply(x$expression$ConceptSets, function(y) y$id)), + originalConceptName = unlist(lapply(x$expression$ConceptSets, function(y) y$name)) + ) + if(ncol(res)!=0){ + res$cohortDefinitionId <- x$id + } + return(res) + })) +} + +formatConcepts <- function(json){ + + conceptTableSummary <- getConceptSum(json) + conceptTableSummary$ref <- paste0(conceptTableSummary$cohortDefinitionId,'_', conceptTableSummary$originalConceptId) + formattedConceptSets <- getAllConceptExpression(json) + conceptNames <- names(formattedConceptSets) + names(formattedConceptSets) <- NULL + uniqueConceptSets <- unique(formattedConceptSets) + names(formattedConceptSets) <- conceptNames + + uniqueRef <- lapply(lapply(uniqueConceptSets, function(y) unlist(lapply(formattedConceptSets, function(x) + identical(y,x)))), function(l) names(l)[which(l)]) + + uniqueConceptSets <- lapply(1:length(uniqueConceptSets), function(i) + list(conceptId = i, + conceptName = unique(conceptTableSummary$originalConceptName[conceptTableSummary$ref%in%uniqueRef[[i]]])[1], + conceptExpressionTable =uniqueConceptSets[[i]])) + + newConceptId <- apply(do.call(cbind, lapply(1:length(uniqueRef), + function(i) {x <- rep(0,nrow(conceptTableSummary)); + x[conceptTableSummary$ref%in%uniqueRef[[i]]] <- i; x} + )),1, sum) + conceptTableSummary$newConceptId <- newConceptId + + return(list(conceptTableSummary=conceptTableSummary, + uniqueConceptSets=uniqueConceptSets)) +}","R" +"Pharmacogenetics","OHDSI/StudyProtocols","finalWoo/R/createValidationPackage.R",".R","2230","54","createValidationPackage <- function(modelFolder, + outputFolder, + minCellCount = 5, + databaseName = 'sharable name of development data', + jsonSettings, + analysisIds = NULL){ + + # json needs to contain the cohort details and packagename + + Hydra::hydrate(specifications = jsonSettings, + outputFolder=outputFolder) + + transportPlpModels(analysesDir = modelFolder, + minCellCount = minCellCount, + databaseName = databaseName, + outputDir = file.path(outputFolder,""inst/plp_models""), + analysisIds = analysisIds) + + return(TRUE) + +} + +transportPlpModels <- function(analysesDir, + minCellCount = 5, + databaseName = 'sharable name of development data', + outputDir = ""./inst/plp_models"", + analysisIds = NULL){ + + files <- dir(analysesDir, recursive = F, full.names = F) + files <- files[grep('Analysis_', files)] + + if(!is.null(analysisIds)){ + #restricting to analysisIds + files <- files[gsub('Analysis_','',files)%in%analysisIds] + } + + filesIn <- file.path(analysesDir, files , 'plpResult') + filesOut <- file.path(outputDir, files, 'plpResult') + + for(i in 1:length(filesIn)){ + if(file.exists(filesIn[i])){ + plpResult <- PatientLevelPrediction::loadPlpResult(filesIn[i]) + PatientLevelPrediction::transportPlp(plpResult, + modelName= files[i], dataName=databaseName, + outputFolder = filesOut[i], + n=minCellCount, + includeEvaluationStatistics=T, + includeThresholdSummary=T, includeDemographicSummary=T, + includeCalibrationSummary =T, includePredictionDistribution=T, + includeCovariateSummary=T, save=T) + } + + } +}","R" +"Pharmacogenetics","OHDSI/StudyProtocols","finalWoo/extras/PackageMaintenance.R",".R","2318","48","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of SkeletonCompartiveEffectStudy +# +# 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. + +# Format and check code --------------------------------------------------- +OhdsiRTools::formatRFolder() +OhdsiRTools::checkUsagePackage(""finalWoo"") +OhdsiRTools::updateCopyrightYearFolder() + +# Create manual ----------------------------------------------------------- +shell(""rm extras/finalWoo.pdf"") +shell(""R CMD Rd2pdf ./ --output=extras/finalWoo.pdf"") + +# Create vignette --------------------------------------------------------- +rmarkdown::render(""vignettes/UsingSkeletonPackage.Rmd"", + output_file = ""../inst/doc/UsingSkeletonPackage.pdf"", + rmarkdown::pdf_document(latex_engine = ""pdflatex"", + toc = TRUE, + number_sections = TRUE)) + +# Create analysis details ------------------------------------------------- +# Insert cohort definitions from ATLAS into package ----------------------- +OhdsiRTools::insertCohortDefinitionSetInPackage(fileName = ""CohortsToCreate.csv"", + baseUrl = ""webapi"", + insertTableSql = TRUE, + insertCohortCreationR = TRUE, + generateStats = FALSE, + packageName = ""finalWoo"") + +# Create analysis details ------------------------------------------------- +source(""extras/CreatePredictionAnalysisDetails.R"") +createAnalysesDetails(""inst/settings"") + +# Store environment in which the study was executed ----------------------- +OhdsiRTools::insertEnvironmentSnapshotInPackage(""finalWoo"") +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","finalWoo/extras/CodeToRun.R",".R","2014","56","library(finalWoo) +# USER INPUTS +#======================= +# The folder where the study intermediate and result files will be written: +outputFolder <- ""./finalWooResults"" + +# Specify where the temporary files (used by the ff package) will be created: +options(fftempdir = ""location with space to save big data"") + +# Details for connecting to the server: +dbms <- ""you dbms"" +user <- 'your username' +pw <- 'your password' +server <- 'your server' +port <- 'your port' + +connectionDetails <- DatabaseConnector::createConnectionDetails(dbms = dbms, + server = server, + user = user, + password = pw, + port = port) + +# Add the database containing the OMOP CDM data +cdmDatabaseSchema <- 'cdm database schema' +# Add a sharebale name for the database containing the OMOP CDM data +cdmDatabaseName <- 'a friendly shareable name for your database' +# Add a database with read/write access as this is where the cohorts will be generated +cohortDatabaseSchema <- 'work database schema' + +oracleTempSchema <- NULL + +# table name where the cohorts will be generated +cohortTable <- 'finalWooCohort' +#======================= + +execute(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cdmDatabaseName = cdmDatabaseName, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + outputFolder = outputFolder, + createProtocol = F, + createCohorts = T, + runAnalyses = T, + createResultsDoc = F, + packageResults = T, + createValidationPackage = F, + minCellCount= 5, + createShiny = F, + createJournalDocument = F, + analysisIdDocument = 1) + +# if you ran execute with: createShiny = T +# Uncomment and run the next line to see the shiny app: +# viewShiny() +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","finalWoo/extras/CreatePredictionAnalysisDetails.R",".R","6724","120","# Copyright 2018 Observational Health Data Sciences and Informatics +# +# 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. + +#' Create the analyses details +#' +#' @details +#' This function creates files specifying the analyses that will be performed. +#' +#' @param workFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' +#' @export +#' +#' +#' + +createAnalysesDetails <- function(workFolder) { + # 1) ADD MODELS you want + modelSettingList <- list(setAdaBoost(nEstimators = c(10,50,100), learningRate = c(0.5,0.9,1)), + setLassoLogisticRegression(), + setGradientBoostingMachine(), + setCIReNN(), + setCNNTorch(), + setCovNN(), + setCovNN2(), + setDecisionTree(), + setDeepNN(), + setKNN(), + setLRTorch(), + setMLP(), + setMLPTorch(), + setNaiveBayes(), + setRandomForest(), + setRNNTorch()) + + # 2) ADD POPULATIONS you want + pop1 <- createStudyPopulationSettings(riskWindowStart = 1, + riskWindowEnd = 365, + requireTimeAtRisk = T, + minTimeAtRisk = 364, + includeAllOutcomes = T) + pop2 <- createStudyPopulationSettings(riskWindowStart = 1, + riskWindowEnd = 365, + requireTimeAtRisk = T, + minTimeAtRisk = 364, + includeAllOutcomes = F) + populationSettingList <- list(pop1, pop2) + + # 3) ADD COVARIATES settings you want + covariateSettings1 <- FeatureExtraction::createCovariateSettings(useDemographicsGender = TRUE, + useDemographicsAgeGroup = TRUE, + useDemographicsRace = TRUE, + useConditionOccurrenceAnyTimePrior = T, + useConditionEraAnyTimePrior = TRUE, + useConditionGroupEraAnyTimePrior = TRUE, #FALSE, + useDrugExposureAnyTimePrior = T, + useDrugEraAnyTimePrior = TRUE, + useDrugGroupEraAnyTimePrior = TRUE, #FALSE, + useProcedureOccurrenceAnyTimePrior = T, + useDeviceExposureAnyTimePrior = T, + useMeasurementAnyTimePrior =T, + useObservationAnyTimePrior = T, + useCharlsonIndex = TRUE, + useDcsi = TRUE, + useChads2 = TRUE, + longTermStartDays = -365, + mediumTermStartDays = -180, + shortTermStartDays = -30, + endDays = 0) + + covariateSettings2 <- FeatureExtraction::createCovariateSettings(useDemographicsGender = TRUE, + useDemographicsAgeGroup = TRUE, + useDemographicsRace = TRUE, + useConditionOccurrenceAnyTimePrior = T, + useConditionEraAnyTimePrior = TRUE, + useConditionGroupEraAnyTimePrior = TRUE, + longTermStartDays = -365, + mediumTermStartDays = -180, + shortTermStartDays = -30, + endDays = 0) + + covariateSettingList <- list(covariateSettings1, covariateSettings2) + + # ADD COHORTS + cohortIds <- c(1,2,3) # add all your Target cohorts here + outcomeIds <- c(2,3) # add all your outcome cohorts here + + + # this will then generate and save the json specification for the analysis + savePredictionAnalysisList(workFolder=workFolder, + cohortIds, + outcomeIds, + cohortSettingCsv =file.path(workFolder, 'CohortsToCreate.csv'), + + covariateSettingList, + populationSettingList, + modelSettingList, + + maxSampleSize= 100000, + washoutPeriod=0, + minCovariateFraction=0, + normalizeData=T, + testSplit='person', + testFraction=0.25, + splitSeed=1, + nfold=3, + verbosity=""INFO"") + + }","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/generateCohort/R/exportTwoPlusNonSGLT2i.R",".R","2916","57","exportTwoPlusNonSGLT2i <- function(connectionDetails, + packageName, + target_database_schema, + target_table_1, + target_table_2, + cdm_database_schema, + dbID, + cohort_table, + code_list, + cohort_universe, + i, + last){ + + conn <- DatabaseConnector::connect(connectionDetails = connectionDetails) + + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""exportTwoPlusNonSGLT2i.sql"", + packageName = packageName, + dbms = attr(conn, ""dbms""), + oracleTempSchema = NULL, + target_database_schema = target_database_schema, + target_table_1 = target_table_1, + target_table_2 = target_table_2, + cdm_database_schema = cdm_database_schema, + dbID = dbID, + cohort_table = cohort_table, + code_list = code_list, + cohort_universe = cohort_universe, + i = i) + + DatabaseConnector::executeSql(conn=conn,sql) + + if(i == last){ + file = paste0(study,""_Results_Two_Plus_Non_SGLT2i_"",Sys.Date(),"".xlsx"") + if(file.exists(file)){ + file.remove(file) + } + + #Table 1 + sql <- paste0(""SELECT * FROM "",Sys.getenv(""writeTo""),""."",target_table_1, "" ORDER BY DB, COHORT_DEFINITION_ID, PERSON_COUNT DESC"") + renderedSql = SqlRender::renderSql(sql=sql) + translatedSql <- SqlRender::translateSql(renderedSql$sql, + targetDialect=Sys.getenv(""dbms"")) + potentialRiskFactors <- DatabaseConnector::querySql(conn=conn,translatedSql$sql) + xlsx::write.xlsx(potentialRiskFactors,file,sheetName=""Summary"", append=TRUE) + + #Table 2 + sql <- paste0(""SELECT * FROM "",Sys.getenv(""writeTo""),""."",target_table_2, "" ORDER BY DB, COHORT_DEFINITION_ID, PERSON_COUNT DESC, INGREDIENT_CONCEPT_NAME_1, INGREDIENT_CONCEPT_NAME_2"") + renderedSql = SqlRender::renderSql(sql=sql) + translatedSql <- SqlRender::translateSql(renderedSql$sql, + targetDialect=Sys.getenv(""dbms"")) + potentialRiskFactors <- DatabaseConnector::querySql(conn=conn,translatedSql$sql) + xlsx::write.xlsx(potentialRiskFactors,file,sheetName=""Details"", append=TRUE) + } + + DatabaseConnector::disconnect(conn) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/generateCohort/R/main.R",".R","20627","435","execute <- function(connectionDetails, study, datasources, + createCodeList, createUniverse, + createCohortTables, #This drops all cohort data + buildTheCohorts, + buildOutcomeCohorts, + buildNegativeControlCohorts, + buildTheCohortsDose, + combinedDbData, + exportResults, + exportPotentialRiskFactors, + exportPotentialRiskFactorsScores, + exportMeanAge, + exportTwoPlusNonSGLT2i, + exportReviewDKAEvents, + exportInitislSGLT2iDosage, + exportDKAFatal, + exportRelevantLabs, + formatPotentialRiskFactors, + formatPaticipantsTxInfo, + formatFatalDka){ + + # VARIABLES ################################################################## + ptm <- proc.time() + numOfDBs <- length(datasources) + packageName <- ""generateCohort"" + tableCodeList <- paste0(study,""_CODE_LIST"") + tableCohorts <- paste0(study,""_COHORTS"") + vocabulary_database_schema <- ""VOCABULARY_20171201.dbo"" + tableCohortUniverse <- paste0(study,""_COHORT_UNIVERSE"") + tabelCohortUniverseDose <- paste0(tableCohortUniverse, ""_DOSE"") + tableCohortAttrition <- paste0(study,""_TABLE_COHORT_ATTRITION"") + tablePotentialRiskFactors <- paste0(study,""_TABLE_POTENTIAL_RISK_FACTORS"") + tableMeanAge <- paste0(study,""_TABLE_MEAN_AGE"") + tableTwoPlusNonSGLT2i_table1 <- paste0(study,""_TABLE_TWO_PLUS_NON_SGLT2I"") + tableTwoPlusNonSGLT2i_table2 <- paste0(study,""_TABLE_TWO_PLUS_NON_SGLT2I_DETAILS"") + tableReviewDKAEvents <- paste0(study,""_TABLE_REVIEW_DKA_EVENTS"") + tableInitialSGLT2iDosage <- paste0(study,""_TABLE_INITIAL_SGLT2i_DOSAGE"") + tableDSCI <- paste0(study,""_DCSI"") + tableChads2 <- paste0(study,""_CHADS2"") + tableCharlson <- paste0(study,""_CHARLSON"") + tableDKAFatal <- paste0(study,""_DKA_FATAL"") + tableRelevantLabs <- paste0(study,""_RELEVANT_LABS"") + tablePotentialRiskFactorsFormatted <- paste0(tablePotentialRiskFactors,""_FORMATTED"") + tableParticipantsAndTreatmentInfo <- paste0(study,""_TABLE_PARTICIPANTS_AND_TX_INFO_FORMATTED"") + + # RUN ######################################################################## + if(createCodeList){ + writeLines(""### Create Code List ###########################################"") + codeList(connectionDetails=connectionDetails, + packageName = packageName, + target_database_schema = Sys.getenv(""writeTo""), + target_table = tableCodeList, + vocabulary_schema = Sys.getenv(""vocabulary"")) + } + + if(createUniverse){ + writeLines(""### Create Cohort Universe #####################################"") + createUniverse(connectionDetails=connectionDetails, + packageName = packageName, + target_database_schema = Sys.getenv(""writeTo""), + target_table = tableCohortUniverse, + target_table_dose = tabelCohortUniverseDose, + codeList = tableCodeList) + + conn <- DatabaseConnector::connect(connectionDetails = connectionDetails) + sql <- paste0(""SELECT * FROM "",Sys.getenv(""writeTo""),""."",tableCohortUniverse,"" WHERE TARGET_COHORT = 1 OR COMPARATOR_COHORT = 1 ORDER BY 1;"") + cohortUniverse <- DatabaseConnector::querySql(conn=conn,sql) + } + + if(combinedDbData){ + writeLines(""### Prep to Combo Data #########################################"") + createCohortTable(connectionDetails=connectionDetails, + packageName = packageName, + target_database_schema = Sys.getenv(""writeTo""), + target_table = tableCohorts) + } + + for(i in 1:numOfDBs){ + writeLines("""") + writeLines("""") + writeLines(""##################################################################"") + print(paste0(datasources[[i]]$db.name)) + writeLines(""##################################################################"") + + #VARIABLES ### + dbCohortTable <- paste0(tableCohorts,""_"",datasources[[i]]$db.name) + dbCohortTableDose <- paste0(dbCohortTable,""_DOSE"") + + if(createCohortTables){ + writeLines(""### Create DB Centric Table to write in"") + createDBCohortTables(connectionDetails=connectionDetails, + packageName = packageName, + target_database_schema = Sys.getenv(""writeTo""), + target_table = dbCohortTable) + } + + if(buildTheCohorts){ + for(z in 1:nrow(cohortUniverse)){ + writeLines("""") + writeLines(""############################################################"") + print(paste0(cohortUniverse[z,]$FULL_NAME)) + writeLines(""############################################################"") + writeLines(""### Create study Target/Comparator cohorts"") + buildCohorts(connectionDetails=connectionDetails, + packageName = packageName, + target_database_schema = Sys.getenv(""writeTo""), + target_table = dbCohortTable, + codeList = tableCodeList, + cdm_database_schema = datasources[[i]]$schema, + target_cohort_id = cohortUniverse[z,]$COHORT_DEFINITION_ID, + drugOfInterest = cohortUniverse[z,]$COHORT_OF_INTEREST, + t2dm = cohortUniverse[z,]$T2DM, + censor = cohortUniverse[z,]$CENSOR) + } + + } + + if(buildTheCohortsDose){ + writeLines(""### Create study Target/Comparator cohorts by Dose"") + buildCohortsDose( + connectionDetails=connectionDetails, + packageName = packageName, + target_database_schema = Sys.getenv(""writeTo""), + target_table = dbCohortTableDose, + codeList = tableCodeList, + cdm_database_schema = datasources[[i]]$schema, + cohort_universe = tableCohortUniverse, + db_cohorts = dbCohortTable) + } + + + + if(buildOutcomeCohorts){ + writeLines(""### Create Outcomes"") + #DKA (IP & ER) + buildOutcomeCohorts(connectionDetails=connectionDetails, + packageName = packageName, + target_database_schema = Sys.getenv(""writeTo""), + target_table = dbCohortTable, + target_cohort_id = 200, + codeList = tableCodeList, + cdm_database_schema = datasources[[i]]$schema, + gap_days = 30) + #DKA (IP) + buildOutcomeCohorts(connectionDetails=connectionDetails, + packageName = packageName, + target_database_schema = Sys.getenv(""writeTo""), + target_table = dbCohortTable, + target_cohort_id = 201, + codeList = tableCodeList, + cdm_database_schema = datasources[[i]]$schema, + gap_days = 30) + + #DKA (IP & ER) w/out gaps + buildOutcomeCohorts(connectionDetails=connectionDetails, + packageName = packageName, + target_database_schema = Sys.getenv(""writeTo""), + target_table = dbCohortTable, + target_cohort_id = 900, + codeList = tableCodeList, + cdm_database_schema = datasources[[i]]$schema, + gap_days = 0) + + #DKA (IP) w/out gaps + buildOutcomeCohorts(connectionDetails=connectionDetails, + packageName = packageName, + target_database_schema = Sys.getenv(""writeTo""), + target_table = dbCohortTable, + target_cohort_id = 901, + codeList = tableCodeList, + cdm_database_schema = datasources[[i]]$schema, + gap_days = 0) + } + + if(buildNegativeControlCohorts){ + writeLines(""### Create Negative Control cohorts"") + buildNegativeControlCohorts(connectionDetails=connectionDetails, + packageName = packageName, + target_database_schema = Sys.getenv(""writeTo""), + target_table = dbCohortTable, + codeList = tableCodeList, + cdm_database_schema = datasources[[i]]$schema) + } + + + + if(combinedDbData){ + writeLines(""### Combined DB"") #assumes DB tables exist + combinedDBData(connectionDetails=connectionDetails, + packageName = packageName, + target_database_schema = Sys.getenv(""writeTo""), + target_table = tableCohorts, + sourceTable = dbCohortTable, + dbID = datasources[[i]]$dbID, + i =i, + lastDb = numOfDBs) + } + } + + if(exportResults){ + writeLines(""### Export Results #############################################"") + export(connectionDetails=connectionDetails, + packageName = packageName, + codeList = tableCodeList, + target_database_schema = Sys.getenv(""writeTo""), + cohortUniverse = tableCohortUniverse, + cohortAttrition = tableCohortAttrition, + datasources = datasources) + } + + if(exportPotentialRiskFactors){ + writeLines(""### Export Results: Potential Risk Factors ####################"") + + if(exportPotentialRiskFactorsScores){ + # Create DCSI For each person + writeLines(""### DCSI Score"") + for(i in 1:length(datasources)){ + aggregatedScore(connectionDetails = connectionDetails, + packageName = packageName, + sql = 'dcsi.sql', + cdm_database_schema = datasources[[i]]$schema, + aggregated = FALSE, + temporal = FALSE, + covariate_table = paste0(Sys.getenv(""writeTo""),'.', tableDSCI,""_"",datasources[[i]]$db.name), + row_id_field = 'SUBJECT_ID', + cohort_table = paste0(Sys.getenv(""writeTo""),'.', tableCohorts,""_"",datasources[[i]]$db.name), + end_day = 0, + cohort_definition_id = 'COHORT_DEFINITION_ID', + analysis_id = 902, + included_cov_table = '', + analysis_name = 'DCSI', + domain_id = 'Condition') + } + + # Create CHADS2 For each person + writeLines(""### CHADS2 Score"") + for(i in 1:length(datasources)){ + aggregatedScore(connectionDetails = connectionDetails, + packageName = packageName, + sql = 'chads2.sql', + cdm_database_schema = datasources[[i]]$schema, + aggregated = FALSE, + temporal = FALSE, + covariate_table = paste0(Sys.getenv(""writeTo""),'.', tableChads2,""_"",datasources[[i]]$db.name), + row_id_field = 'SUBJECT_ID', + cohort_table = paste0(Sys.getenv(""writeTo""),'.', tableCohorts,""_"",datasources[[i]]$db.name), + end_day = 0, + cohort_definition_id = 'COHORT_DEFINITION_ID', + analysis_id = 903, + included_cov_table = '', + analysis_name = 'Chads2', + domain_id = 'Condition') + } + + + # Create Charlson For each person + writeLines(""### Charlson Score"") + for(i in 1:length(datasources)){ + aggregatedScore(connectionDetails = connectionDetails, + packageName = packageName, + sql = 'charlsonIndex.sql', + cdm_database_schema = datasources[[i]]$schema, + aggregated = FALSE, + temporal = FALSE, + covariate_table = paste0(Sys.getenv(""writeTo""),'.', tableCharlson,""_"",datasources[[i]]$db.name), + row_id_field = 'SUBJECT_ID', + cohort_table = paste0(Sys.getenv(""writeTo""),'.', tableCohorts,""_"",datasources[[i]]$db.name), + end_day = 0, + cohort_definition_id = 'COHORT_DEFINITION_ID', + analysis_id = 901, + included_cov_table = '', + analysis_name = 'CharlsonIndex', + domain_id = 'Condition') + } + } + + for(i in 1:length(datasources)){ + exportPotentialRiskFactors(connectionDetails = connectionDetails, + packageName = packageName, + target_database_schema = Sys.getenv(""writeTo""), + target_table = tablePotentialRiskFactors, + cdm_database_schema = datasources[[i]]$schema, + dbID = datasources[[i]]$db.name, + cohort_table = paste0(tableCohorts,""_"",datasources[[i]]$db.name), + code_list = tableCodeList, + cohort_universe = tableCohortUniverse, + i = i, + last = length(datasources), + study = study) + } + } + + if(exportRelevantLabs){ + writeLines(""### Export Results: Relevant Labs #############################"") + + for(i in 1:length(datasources)){ + exportRelevantLabs(connectionDetails = connectionDetails, + packageName = packageName, + target_database_schema = Sys.getenv(""writeTo""), + target_table = tableRelevantLabs, + cdm_database_schema = datasources[[i]]$schema, + dbID = datasources[[i]]$db.name, + cohort_table = paste0(tableCohorts,""_"",datasources[[i]]$db.name), + code_list = tableCodeList, + cohort_universe = tableCohortUniverse, + i = i, + last = length(datasources)) + } + } + + if(exportMeanAge){ + writeLines(""### Export Results: Mean Age ##################################"") + + for(i in 1:length(datasources)){ + exportMeanAge(connectionDetails = connectionDetails, + packageName = packageName, + target_database_schema = Sys.getenv(""writeTo""), + target_table = tableMeanAge, + cdm_database_schema = datasources[[i]]$schema, + dbID = datasources[[i]]$db.name, + cohort_table = paste0(tableCohorts,""_"",datasources[[i]]$db.name), + cohort_universe = tableCohortUniverse, + i = i, + last = length(datasources)) + } + } + + if(exportTwoPlusNonSGLT2i){ + writeLines(""### Export Results: Two Plus Non SGLT2is ######################"") + for(i in 1:length(datasources)){ + exportTwoPlusNonSGLT2i(connectionDetails = connectionDetails, + packageName = packageName, + target_database_schema = Sys.getenv(""writeTo""), + target_table_1 = tableTwoPlusNonSGLT2i_table1, + target_table_2 = tableTwoPlusNonSGLT2i_table2, + cdm_database_schema = datasources[[i]]$schema, + dbID = datasources[[i]]$db.name, + cohort_table = paste0(tableCohorts,""_"",datasources[[i]]$db.name), + code_list = tableCodeList, + cohort_universe = tableCohortUniverse, + i = i, + last = length(datasources)) + } + } + + if(exportReviewDKAEvents){ + writeLines(""### Export Results: Review DKA Events #########################"") + for(i in 1:length(datasources)){ + exportReviewDKAEvents (connectionDetails = connectionDetails, + packageName = packageName, + target_database_schema = Sys.getenv(""writeTo""), + target_table = tableReviewDKAEvents, + dbID = datasources[[i]]$db.name, + cohort_table = paste0(tableCohorts,""_"",datasources[[i]]$db.name), + cohort_universe = tableCohortUniverse, + i = i, + last = length(datasources)) + } + } + + if(exportInitislSGLT2iDosage){ + writeLines(""### Export Results: Export Initial SGLT2i Dosage ##############"") + for(i in 1:length(datasources)){ + exportInitialSGLT2iDosage(connectionDetails = connectionDetails, + packageName = packageName, + target_database_schema = Sys.getenv(""writeTo""), + target_table = tableInitialSGLT2iDosage, + cdm_database_schema = datasources[[i]]$schema, + dbID = datasources[[i]]$db.name, + cohort_table = paste0(tableCohorts,""_"",datasources[[i]]$db.name), + code_list = tableCodeList, + cohort_universe = tableCohortUniverse, + i = i, + last = length(datasources)) + } + } + + if(exportDKAFatal){ + writeLines(""### Export Results: DKA Fatal #################################"") + for(i in 1:length(datasources)){ + exportDKAFatal(connectionDetails = connectionDetails, + packageName = packageName, + target_database_schema = Sys.getenv(""writeTo""), + target_table = tableDKAFatal, + cdm_database_schema = datasources[[i]]$schema, + dbID = datasources[[i]]$db.name, + cohort_table = paste0(tableCohorts,""_"",datasources[[i]]$db.name), + code_list = tableCodeList, + cohort_universe = tableCohortUniverse, + i = i, + last = length(datasources)) + } + } + + if(formatPotentialRiskFactors){ + writeLines(""### Format Results: Potential Risk Factors ####################"") + + formatPotentialRiskFactors(connectionDetails = connectionDetails, + packageName = packageName, + target_database_schema = Sys.getenv(""writeTo""), + target_table = tablePotentialRiskFactorsFormatted , + cohort_universe = tableCohortUniverse, + tablePotentialRiskFactors = tablePotentialRiskFactors) + + } + + if(formatPaticipantsTxInfo){ + writeLines(""### Format Results: Participants and Treatment Info ###########"") + + formatParticipantsAndTxInfo(connectionDetails = connectionDetails, + packageName = packageName, + target_database_schema = Sys.getenv(""writeTo""), + target_table = tableParticipantsAndTreatmentInfo, + cohort_universe = tableCohortUniverse, + tablePotentialRiskFactors = tablePotentialRiskFactors, + tableMeanAge = tableMeanAge) + } + + if(formatFatalDka){ + writeLines(""### Format Results: Fatal DKA #################################"") + + formatFatalDka(connectionDetails = connectionDetails, + packageName = packageName, + target_database_schema = Sys.getenv(""writeTo""), + target_table = tableParticipantsAndTreatmentInfo, + cohort_universe = tableCohortUniverse, + tablePotentialRiskFactors = tablePotentialRiskFactors, + tableDKAFatal = tableDKAFatal) + } + + runTime <- proc.time() - ptm + writeLines(""### Program Run Time"") + print(runTime) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/generateCohort/R/export.R",".R","4838","94","export <- function(connectionDetails, packageName, codeList, cohortUniverse, + target_database_schema, + cohortAttrition, + datasources){ + tableCodeList <- codeList + tableCohortUniverse <- cohortUniverse + + conn <- DatabaseConnector::connect(connectionDetails = connectionDetails) + + writeLines(""### Code List & Cohort Descriptions"") + + file = paste0(study,""_Results_"",Sys.Date(),"".xlsx"") + if(file.exists(file)){ + file.remove(file) + } + + #Concept Set + sql <- paste0(""SELECT * FROM "",Sys.getenv(""writeTo""),""."",tableCodeList, "" ORDER BY CODE_LIST_NAME, CODE_LIST_DESCRIPTION, CONCEPT_NAME"") + renderedSql = SqlRender::renderSql(sql=sql) + translatedSql <- SqlRender::translateSql(renderedSql$sql, + targetDialect=Sys.getenv(""dbms"")) + conceptSet <- DatabaseConnector::querySql(conn=conn,translatedSql$sql) + xlsx::write.xlsx(conceptSet,file,sheetName=""Code List"", append=TRUE) + + #Ingredient List + sql <- paste0(""SELECT DISTINCT cl.* FROM "",Sys.getenv(""writeTo""),""."",tableCodeList, "" cl JOIN "", Sys.getenv(""vocabulary""),"".CONCEPT c ON c.CONCEPT_ID = cl.CONCEPT_ID AND CONCEPT_CLASS_ID = 'Ingredient' ORDER BY cl.CODE_LIST_NAME, cl.CONCEPT_NAME"") + renderedSql = SqlRender::renderSql(sql=sql) + translatedSql <- SqlRender::translateSql(renderedSql$sql, + targetDialect=Sys.getenv(""dbms"")) + conceptSet <- DatabaseConnector::querySql(conn=conn,translatedSql$sql) + xlsx::write.xlsx(conceptSet,file,sheetName=""Code List (Ingredients Only)"", append=TRUE) + + #Cohort List + sql <- paste0(""SELECT * FROM "",Sys.getenv(""writeTo""),""."",tableCohortUniverse, "" ORDER BY COHORT_DEFINITION_ID"") + renderedSql = SqlRender::renderSql(sql=sql) + translatedSql <- SqlRender::translateSql(renderedSql$sql, + targetDialect=Sys.getenv(""dbms"")) + cohorts <- DatabaseConnector::querySql(conn=conn,translatedSql$sql) + xlsx::write.xlsx(cohorts,file,sheetName=""Cohorts"", append=TRUE) + + ### Cohort Attrition ################################################################## + + #writeLines(""### Cohort Attrition"") + + fileCohortAttrition = paste0(study,""_Results_Cohort_Attrition_"",Sys.Date(),"".xlsx"") + if(file.exists(fileCohortAttrition)){ + file.remove(fileCohortAttrition) + } + + # Cohorts for Attrition List + sql <- paste0(""SELECT * FROM "",Sys.getenv(""writeTo""),""."",tableCohortUniverse, "" WHERE EXPOSURE_COHORT = 1 AND FU_STRAT_ITT_PP0DAY = 1 ORDER BY COHORT_DEFINITION_ID"") + renderedSql = SqlRender::renderSql(sql=sql) + translatedSql <- SqlRender::translateSql(renderedSql$sql, + targetDialect=Sys.getenv(""dbms"")) + cohorts <- DatabaseConnector::querySql(conn=conn,translatedSql$sql) + + for(z in 1:length(datasources)){ + + writeLines(""##################################################################"") + print(paste0(datasources[[z]]$db.name)) + writeLines(""##################################################################"") + + for(i in 1:nrow(cohorts)){ + print(paste0('I: ',i, ' COHORT_DEF_ID: ',cohorts$COHORT_DEFINITION_ID[i], ' FULL_NAME: ', cohorts$FULL_NAME[i])) + + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""exportCohortAttrition.sql"", + packageName = packageName, + dbms = attr(conn, ""dbms""), + oracleTempSchema = NULL, + i = i, + z = z, + cdm_database_schema = datasources[[z]]$schema, + db.name = datasources[[z]]$db.name, + cohortID = cohorts$COHORT_DEFINITION_ID[i], + target_database_schema = target_database_schema, + target_table = cohortAttrition, + t2dm = cohorts$T2DM[i], + drugOfInterest = cohorts$COHORT_OF_INTEREST[i]) + + DatabaseConnector::executeSql(conn=conn,sql) + } + } + + #Cohort Attrition List + sql <- paste0(""SELECT * FROM "",Sys.getenv(""writeTo""),""."",cohortAttrition, "" ORDER BY DB, COHORT_ID"") + renderedSql = SqlRender::renderSql(sql=sql) + translatedSql <- SqlRender::translateSql(renderedSql$sql, + targetDialect=Sys.getenv(""dbms"")) + cohortAttrition <- DatabaseConnector::querySql(conn=conn,translatedSql$sql) + xlsx::write.xlsx(cohortAttrition,fileCohortAttrition,sheetName=""Cohort Attrition"", append=TRUE) + + DatabaseConnector::disconnect(conn) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/generateCohort/R/createCohortTable.R",".R","756","17","createCohortTable <- function(connectionDetails,packageName, + target_database_schema,target_table){ + + conn <- DatabaseConnector::connect(connectionDetails = connectionDetails) + + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""createCohortTable.sql"", + packageName = packageName, + dbms = attr(conn, ""dbms""), + oracleTempSchema = NULL, + target_database_schema=target_database_schema, + target_cohort_table=target_table) + + DatabaseConnector::executeSql(conn=conn,sql) + + DatabaseConnector::disconnect(conn) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/generateCohort/R/formatFatalDka.R",".R","1887","42","formatFatalDka <- function(connectionDetails, + packageName, + target_database_schema, + target_table, + cohort_universe, + tablePotentialRiskFactors, + tableDKAFatal){ + + + conn <- DatabaseConnector::connect(connectionDetails = connectionDetails) + + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""formatFatalDka.sql"", + packageName = packageName, + dbms = attr(conn, ""dbms""), + oracleTempSchema = NULL, + target_database_schema = target_database_schema, + target_table = target_table, + cohort_universe = cohort_universe, + tablePotentialRiskFactors = tablePotentialRiskFactors, + tableDKAFatal = tableDKAFatal) + + DatabaseConnector::executeSql(conn=conn,sql) + + + file = paste0(study,""_Results_DKA_Fatal_Formatted_"",Sys.Date(),"".xlsx"") + if(file.exists(file)){ + file.remove(file) + } + + #Cohort Attrition List + sql <- paste0(""SELECT * FROM "",Sys.getenv(""writeTo""),""."",target_table, "" ORDER BY STAT_ORDER_NUMBER_0, COHORT_OF_INTEREST, DB "") + renderedSql = SqlRender::renderSql(sql=sql) + translatedSql <- SqlRender::translateSql(renderedSql$sql, + targetDialect=Sys.getenv(""dbms"")) + potentialRiskFactors <- DatabaseConnector::querySql(conn=conn,translatedSql$sql) + xlsx::write.xlsx(potentialRiskFactors,file,sheetName=""Fatal DKA"", append=TRUE) + + + + DatabaseConnector::disconnect(conn) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/generateCohort/R/formatPotentialRiskFactors.R",".R","1971","40","formatPotentialRiskFactors <- function(connectionDetails, + packageName, + target_database_schema, + target_table, + cohort_universe, + tablePotentialRiskFactors){ + + + conn <- DatabaseConnector::connect(connectionDetails = connectionDetails) + + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""formatPotentialRiskFactors.sql"", + packageName = packageName, + dbms = attr(conn, ""dbms""), + oracleTempSchema = NULL, + target_database_schema = target_database_schema, + target_table = target_table, + cohort_universe = cohort_universe, + tablePotentialRiskFactors = tablePotentialRiskFactors) + + DatabaseConnector::executeSql(conn=conn,sql) + + + filePotentialRiskFactors = paste0(study,""_Results_Potential_Risk_Factors_Formated_"",Sys.Date(),"".xlsx"") + if(file.exists(filePotentialRiskFactors)){ + file.remove(filePotentialRiskFactors) + } + + #Cohort Attrition List + sql <- paste0(""SELECT * FROM "",Sys.getenv(""writeTo""),""."",target_table, "" ORDER BY DKA DESC, STAT_ORDER_NUMBER_0, COHORT_OF_INTEREST, STAT_ORDER_NUMBER_1_UPDATED, STAT_ORDER_NUMBER_2"") + renderedSql = SqlRender::renderSql(sql=sql) + translatedSql <- SqlRender::translateSql(renderedSql$sql, + targetDialect=Sys.getenv(""dbms"")) + potentialRiskFactors <- DatabaseConnector::querySql(conn=conn,translatedSql$sql) + xlsx::write.xlsx(potentialRiskFactors,filePotentialRiskFactors,sheetName=""Potential Risk Factors"", append=TRUE) + + + + DatabaseConnector::disconnect(conn) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/generateCohort/R/exportDKAFatal.R",".R","2221","49","exportDKAFatal <- function(connectionDetails, + packageName, + target_database_schema, + target_table, + cdm_database_schema, + dbID, + cohort_table, + code_list, + cohort_universe, + i, + last){ + + + conn <- DatabaseConnector::connect(connectionDetails = connectionDetails) + + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""exportDKAFatal.sql"", + packageName = packageName, + dbms = attr(conn, ""dbms""), + oracleTempSchema = NULL, + target_database_schema = target_database_schema, + target_table = target_table, + cdm_database_schema = cdm_database_schema, + dbID = dbID, + cohort_table = cohort_table, + code_list = code_list, + cohort_universe = cohort_universe, + i = i) + + DatabaseConnector::executeSql(conn=conn,sql) + + if(i == last){ + filePotentialRiskFactors = paste0(study,""_Results_DKA_FATAL_"",Sys.Date(),"".xlsx"") + if(file.exists(filePotentialRiskFactors)){ + file.remove(filePotentialRiskFactors) + } + + #Cohort Attrition List + sql <- paste0(""SELECT * FROM "",Sys.getenv(""writeTo""),""."",target_table, "" ORDER BY DB, COHORT_DEFINITION_ID, DKA, STAT_ORDER_NUMBER"") + renderedSql = SqlRender::renderSql(sql=sql) + translatedSql <- SqlRender::translateSql(renderedSql$sql, + targetDialect=Sys.getenv(""dbms"")) + potentialRiskFactors <- DatabaseConnector::querySql(conn=conn,translatedSql$sql) + xlsx::write.xlsx(potentialRiskFactors,filePotentialRiskFactors,sheetName=""Fatal DKA"", append=TRUE) + } + + + DatabaseConnector::disconnect(conn) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/generateCohort/R/getConnectionDetails.R",".R","633","23","getConnectionDetails <- function(configFile){ + config <- read.csv(configFile,as.is=TRUE)[1,] + + Sys.setenv(dbms = config$dbms) + Sys.setenv(user = config$user) + Sys.setenv(pw = config$pw) + Sys.setenv(server = config$server) + Sys.setenv(port = config$port) + Sys.setenv(writeTo = config$writeTo) + Sys.setenv(vocabulary = config$vocabulary) + rm(config) + + connectionDetails <- DatabaseConnector::createConnectionDetails( + dbms = Sys.getenv(""dbms""), + server = Sys.getenv(""server""), + port = as.numeric(Sys.getenv(""port"")) + #user = Sys.getenv(""user""), + #password = Sys.getenv(""pw"") + ) + + return(connectionDetails) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/generateCohort/R/createDBCohortTables.R",".R","759","17","createDBCohortTables <- function(connectionDetails,packageName, + target_database_schema,target_table){ + + conn <- DatabaseConnector::connect(connectionDetails = connectionDetails) + + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""createDBCohortTable.sql"", + packageName = packageName, + dbms = attr(conn, ""dbms""), + oracleTempSchema = NULL, + target_database_schema=target_database_schema, + target_cohort_table=target_table) + + DatabaseConnector::executeSql(conn=conn,sql) + + DatabaseConnector::disconnect(conn) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/generateCohort/R/createUniverse.R",".R","887","19","createUniverse <- function(connectionDetails,packageName,target_database_schema,target_table,target_table_dose,codeList){ + + conn <- DatabaseConnector::connect(connectionDetails = connectionDetails) + + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""createUniverse.sql"", + packageName = packageName, + dbms = attr(conn, ""dbms""), + oracleTempSchema = NULL, + target_database_schema = target_database_schema, + target_table = target_table, + target_table_dose = target_table_dose, + codeList = codeList) + + DatabaseConnector::executeSql(conn=conn,sql) + + DatabaseConnector::disconnect(conn) + +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/generateCohort/R/createDatabaseList.R",".R","601","32","createDatabaseList <- function(){ + #Generate DB Object + ccae = list ( + schema = ""CDM_TRUVEN_CCAE_V697.dbo"", + db.name = ""CCAE"", + dbID = 1000000000 + ) + + mdcr = list ( + schema = ""CDM_TRUVEN_MDCR_V698.dbo"", + db.name = ""MDCR"", + dbID = 2000000000 + ) + + mdcd = list ( + schema = ""CDM_TRUVEN_MDCD_V699.dbo"", + db.name = ""MDCD"", + dbID = 3000000000 + ) + + optum_ses = list ( + schema = ""CDM_OPTUM_EXTENDED_SES_V694.dbo"", + db.name = ""OPTUM_SES"", + dbID = 4000000000 + + ) + + datasources <- list(ccae,mdcr,mdcd,optum_ses) + rm(ccae,mdcr,mdcd,optum_ses) + return(datasources) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/generateCohort/R/exportMeanAge.R",".R","2091","46","exportMeanAge <- function(connectionDetails, + packageName, + target_database_schema, + target_table, + cdm_database_schema, + dbID, + cohort_table, + cohort_universe, + i, + last){ + + + conn <- DatabaseConnector::connect(connectionDetails = connectionDetails) + + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""exportMeanAge.sql"", + packageName = packageName, + dbms = attr(conn, ""dbms""), + oracleTempSchema = NULL, + target_database_schema = target_database_schema, + target_table = target_table, + cdm_database_schema = cdm_database_schema, + dbID = dbID, + cohort_table = cohort_table, + cohort_universe = cohort_universe, + i = i) + + DatabaseConnector::executeSql(conn=conn,sql) + + if(i == last){ + file = paste0(study,""_Results_Mean_Age_"",Sys.Date(),"".xlsx"") + if(file.exists(file)){ + file.remove(file) + } + + sql <- paste0(""SELECT * FROM "",Sys.getenv(""writeTo""),""."",target_table, "" ORDER BY DB, COHORT_DEFINITION_ID;"") + renderedSql = SqlRender::renderSql(sql=sql) + translatedSql <- SqlRender::translateSql(renderedSql$sql, + targetDialect=Sys.getenv(""dbms"")) + potentialRiskFactors <- DatabaseConnector::querySql(conn=conn,translatedSql$sql) + xlsx::write.xlsx(potentialRiskFactors,file,sheetName=""Mean Age"", append=TRUE) + } + + + DatabaseConnector::disconnect(conn) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/generateCohort/R/buildNegativeControlCohorts.R",".R","1003","20","buildNegativeControlCohorts <- function(connectionDetails,packageName,codeList, + target_database_schema,target_table, + cdm_database_schema){ + conn <- DatabaseConnector::connect(connectionDetails = connectionDetails) + + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""buildNegativeControlCohorts.sql"", + packageName = packageName, + dbms = attr(conn, ""dbms""), + oracleTempSchema = NULL, + target_database_schema=target_database_schema, + target_cohort_table=target_table, + cdm_database_schema = cdm_database_schema, + codeList = codeList) + + DatabaseConnector::executeSql(conn=conn,sql) + + DatabaseConnector::disconnect(conn) + +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/generateCohort/R/exportRelevantLab.R",".R","2332","48","exportRelevantLabs <- function(connectionDetails, + packageName, + target_database_schema, + target_table, + cdm_database_schema, + dbID, + cohort_table, + code_list, + cohort_universe, + i, + last){ + + + conn <- DatabaseConnector::connect(connectionDetails = connectionDetails) + + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""exportRelevantLabs.sql"", + packageName = packageName, + dbms = attr(conn, ""dbms""), + oracleTempSchema = NULL, + target_database_schema = target_database_schema, + target_table = target_table, + cdm_database_schema = cdm_database_schema, + dbID = dbID, + cohort_table = cohort_table, + code_list = code_list, + cohort_universe = cohort_universe, + i = i) + + DatabaseConnector::executeSql(conn=conn,sql) + + if(i == last){ + filePotentialRiskFactors = paste0(study,""_Results_Relevant_Labs_"",Sys.Date(),"".xlsx"") + if(file.exists(filePotentialRiskFactors)){ + file.remove(filePotentialRiskFactors) + } + + #Cohort Attrition List + sql <- paste0(""SELECT * FROM "",Sys.getenv(""writeTo""),""."",target_table, "" ORDER BY DB, COHORT_DEFINITION_ID"") + renderedSql = SqlRender::renderSql(sql=sql) + translatedSql <- SqlRender::translateSql(renderedSql$sql, + targetDialect=Sys.getenv(""dbms"")) + potentialRiskFactors <- DatabaseConnector::querySql(conn=conn,translatedSql$sql) + xlsx::write.xlsx(potentialRiskFactors,filePotentialRiskFactors,sheetName=""Relevant Labs"", append=TRUE) + } + + DatabaseConnector::disconnect(conn) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/generateCohort/R/exportReviewDKAEvents.R",".R","1970","44","exportReviewDKAEvents <- function(connectionDetails, + packageName, + target_database_schema, + target_table, + dbID, + cohort_table, + cohort_universe, + i, + last){ + + conn <- DatabaseConnector::connect(connectionDetails = connectionDetails) + + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""exportReviewDKAEvents.sql"", + packageName = packageName, + dbms = attr(conn, ""dbms""), + oracleTempSchema = NULL, + target_database_schema = target_database_schema, + target_table = target_table, + dbID = dbID, + cohort_table = cohort_table, + cohort_universe = cohort_universe, + i = i) + + DatabaseConnector::executeSql(conn=conn,sql) + + if(i == last){ + file = paste0(study,""_Results_Review_DKA_Events_"",Sys.Date(),"".xlsx"") + if(file.exists(file)){ + file.remove(file) + } + + #Table 1 + sql <- paste0(""SELECT * FROM "",Sys.getenv(""writeTo""),""."",target_table, "" ORDER BY DB, COHORT_DEFINITION_ID, STAT_ORDER_NUMBER"") + renderedSql = SqlRender::renderSql(sql=sql) + translatedSql <- SqlRender::translateSql(renderedSql$sql, + targetDialect=Sys.getenv(""dbms"")) + potentialRiskFactors <- DatabaseConnector::querySql(conn=conn,translatedSql$sql) + xlsx::write.xlsx(potentialRiskFactors,file,sheetName=""DKA Events"", append=TRUE) + + } + + DatabaseConnector::disconnect(conn) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/generateCohort/R/formatParticipantsAndTxInfo.R",".R","1938","42","formatParticipantsAndTxInfo <- function(connectionDetails, + packageName, + target_database_schema, + target_table, + cohort_universe, + tablePotentialRiskFactors, + tableMeanAge){ + + + conn <- DatabaseConnector::connect(connectionDetails = connectionDetails) + + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""formatParticipantsAndTxInfo.sql"", + packageName = packageName, + dbms = attr(conn, ""dbms""), + oracleTempSchema = NULL, + target_database_schema = target_database_schema, + target_table = target_table, + cohort_universe = cohort_universe, + tablePotentialRiskFactors = tablePotentialRiskFactors, + tableMeanAge = tableMeanAge) + + DatabaseConnector::executeSql(conn=conn,sql) + + + file = paste0(study,""_Results_Participants_And_TX_Info_Formated_"",Sys.Date(),"".xlsx"") + if(file.exists(file)){ + file.remove(file) + } + + #Cohort Attrition List + sql <- paste0(""SELECT * FROM "",Sys.getenv(""writeTo""),""."",target_table, "" ORDER BY COHORT_TYPE DESC,COHORT_OF_INTEREST,DB "") + renderedSql = SqlRender::renderSql(sql=sql) + translatedSql <- SqlRender::translateSql(renderedSql$sql, + targetDialect=Sys.getenv(""dbms"")) + potentialRiskFactors <- DatabaseConnector::querySql(conn=conn,translatedSql$sql) + xlsx::write.xlsx(potentialRiskFactors,file,sheetName=""Potential Risk Factors"", append=TRUE) + + + + DatabaseConnector::disconnect(conn) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/generateCohort/R/aggregatedScore.R",".R","1763","37","aggregatedScore <- function(connectionDetails, + packageName, + sql, + cdm_database_schema, + aggregated, + temporal, + covariate_table, + row_id_field, + cohort_table, + end_day, + cohort_definition_id, + analysis_id, + included_cov_table, + analysis_name, + domain_id){ + conn <- DatabaseConnector::connect(connectionDetails = connectionDetails) + + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = sql, + packageName = packageName, + dbms = attr(conn, ""dbms""), + oracleTempSchema = NULL, + cdm_database_schema = cdm_database_schema, + aggregated = aggregated, + temporal = temporal, + covariate_table = covariate_table, + row_id_field = row_id_field, + cohort_table = cohort_table, + end_day = end_day, + cohort_definition_id = cohort_definition_id, + analysis_id = analysis_id, + included_cov_table = included_cov_table, + analysis_name = analysis_name, + domain_id = domain_id) + + DatabaseConnector::executeSql(conn=conn,sql) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/generateCohort/R/exportPotentialRiskFactors.R",".R","2518","51","exportPotentialRiskFactors <- function(connectionDetails, + packageName, + target_database_schema, + target_table, + cdm_database_schema, + dbID, + cohort_table, + code_list, + cohort_universe, + i, + last, + study){ + + + conn <- DatabaseConnector::connect(connectionDetails = connectionDetails) + + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""exportPotentialRiskFactors.sql"", + packageName = packageName, + dbms = attr(conn, ""dbms""), + oracleTempSchema = NULL, + target_database_schema = target_database_schema, + target_table = target_table, + cdm_database_schema = cdm_database_schema, + dbID = dbID, + cohort_table = cohort_table, + code_list = code_list, + cohort_universe = cohort_universe, + i = i, + study = study) + + DatabaseConnector::executeSql(conn=conn,sql) + + if(i == last){ + filePotentialRiskFactors = paste0(study,""_Results_Potential_Risk_Factors_"",Sys.Date(),"".xlsx"") + if(file.exists(filePotentialRiskFactors)){ + file.remove(filePotentialRiskFactors) + } + + #Cohort Attrition List + sql <- paste0(""SELECT * FROM "",Sys.getenv(""writeTo""),""."",target_table, "" ORDER BY DB, COHORT_DEFINITION_ID, DKA, STAT_ORDER_NUMBER_1, STAT_ORDER_NUMBER_2"") + renderedSql = SqlRender::renderSql(sql=sql) + translatedSql <- SqlRender::translateSql(renderedSql$sql, + targetDialect=Sys.getenv(""dbms"")) + potentialRiskFactors <- DatabaseConnector::querySql(conn=conn,translatedSql$sql) + xlsx::write.xlsx(potentialRiskFactors,filePotentialRiskFactors,sheetName=""Potential Risk Factors"", append=TRUE) + } + + + DatabaseConnector::disconnect(conn) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/generateCohort/R/buildCohorts.R",".R","1289","25","buildCohortsDose <- function(connectionDetails,packageName, + target_database_schema,target_table,target_cohort_id, + codeList,cdm_database_schema, + drugOfInterest,t2dm,censor){ + + conn <- DatabaseConnector::connect(connectionDetails = connectionDetails) + + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""buildCohorts.sql"", + packageName = packageName, + dbms = attr(conn, ""dbms""), + oracleTempSchema = NULL, + target_database_schema=target_database_schema, + target_cohort_table=target_table, + target_cohort_id = target_cohort_id, + codeList = codeList, + cdm_database_schema = cdm_database_schema, + drugOfInterest = drugOfInterest, + t2dm = t2dm, + censor = censor) + + DatabaseConnector::executeSql(conn=conn,sql) + + DatabaseConnector::disconnect(conn) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/generateCohort/R/codeList.R",".R","801","17","codeList <- function(connectionDetails,packageName,target_database_schema,target_table,vocabulary_schema){ + + conn <- DatabaseConnector::connect(connectionDetails = connectionDetails) + + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""codeList.sql"", + packageName = packageName, + dbms = attr(conn, ""dbms""), + oracleTempSchema = NULL, + target_database_schema = target_database_schema, + target_table = target_table, + vocabulary_schema = vocabulary_schema) + DatabaseConnector::executeSql(conn=conn,sql) + + DatabaseConnector::disconnect(conn) + +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/generateCohort/R/combinedDBData.R",".R","1045","22","combinedDBData <- function(connectionDetails,packageName,dbID, + target_database_schema,target_table,sourceTable, + i, lastDb){ + + conn <- DatabaseConnector::connect(connectionDetails = connectionDetails) + + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""combinedDbData.sql"", + packageName = packageName, + dbms = attr(conn, ""dbms""), + oracleTempSchema = NULL, + target_database_schema=target_database_schema, + target_cohort_table=target_table, + sourceTable=sourceTable, + dbID = dbID, + i = i, + lastDb = lastDb) + + DatabaseConnector::executeSql(conn=conn,sql) + + DatabaseConnector::disconnect(conn) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/generateCohort/R/buildOutcomeCohorts.R",".R","1143","23","buildOutcomeCohorts <- function(connectionDetails,packageName, + target_database_schema,target_table,target_cohort_id, + codeList,cdm_database_schema, gap_days){ + + conn <- DatabaseConnector::connect(connectionDetails = connectionDetails) + + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""buildOutcomeCohorts.sql"", + packageName = packageName, + dbms = attr(conn, ""dbms""), + oracleTempSchema = NULL, + target_database_schema=target_database_schema, + target_cohort_table=target_table, + target_cohort_id = target_cohort_id, + codeList = codeList, + cdm_database_schema = cdm_database_schema, + gap_days = gap_days) + + DatabaseConnector::executeSql(conn=conn,sql) + + DatabaseConnector::disconnect(conn) + +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/generateCohort/R/exportInitialSGLT2iDosage.R",".R","2241","48","exportInitialSGLT2iDosage <- function(connectionDetails, + packageName, + target_database_schema, + target_table, + cdm_database_schema, + dbID, + cohort_table, + code_list, + cohort_universe, + i, + last){ + + conn <- DatabaseConnector::connect(connectionDetails = connectionDetails) + + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""exportInitialSGLT2iDosage.sql"", + packageName = packageName, + dbms = attr(conn, ""dbms""), + oracleTempSchema = NULL, + target_database_schema = target_database_schema, + target_table = target_table, + cdm_database_schema = cdm_database_schema, + dbID = dbID, + cohort_table = cohort_table, + code_list = code_list, + cohort_universe = cohort_universe, + i = i) + + DatabaseConnector::executeSql(conn=conn,sql) + + if(i == last){ + file = paste0(study,""_Results_Initial_SGLT2i_Dossage_"",Sys.Date(),"".xlsx"") + if(file.exists(file)){ + file.remove(file) + } + + #Table 1 + sql <- paste0(""SELECT * FROM "",Sys.getenv(""writeTo""),""."",target_table, "" ORDER BY DB, COHORT_DEFINITION_ID, DOSE_STRENGTH, STAT_TYPE"") + renderedSql = SqlRender::renderSql(sql=sql) + translatedSql <- SqlRender::translateSql(renderedSql$sql, + targetDialect=Sys.getenv(""dbms"")) + potentialRiskFactors <- DatabaseConnector::querySql(conn=conn,translatedSql$sql) + xlsx::write.xlsx(potentialRiskFactors,file,sheetName=""Summary"", append=TRUE) + + } + + DatabaseConnector::disconnect(conn) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/generateCohort/R/buildCohortsDose.R",".R","1221","26","buildCohortsDose <- function(connectionDetails,packageName, + target_database_schema, + target_table, + codeList, + cdm_database_schema, + cohort_universe, + db_cohorts){ + + conn <- DatabaseConnector::connect(connectionDetails = connectionDetails) + + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""buildCohortsDose.sql"", + packageName = packageName, + dbms = attr(conn, ""dbms""), + oracleTempSchema = NULL, + target_database_schema=target_database_schema, + target_table=target_table, + codeList = codeList, + cdm_database_schema = cdm_database_schema, + cohort_universe = cohort_universe, + db_cohorts = db_cohorts) + + DatabaseConnector::executeSql(conn=conn,sql) + + DatabaseConnector::disconnect(conn) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/generateCohort/extras/codeToRun.R",".R","1776","47","################################################################################ +# CONFIG +################################################################################ +options(java.parameters = ""- Xmx1024m"") +library(generateCohort) + +################################################################################ +# VARIABLES +################################################################################ +configFile <- ""extras/config.csv"" +connectionDetails <- getConnectionDetails(configFile) +study = ""EPI535"" + +################################################################################ +# DATABASES +################################################################################ +datasources <- createDatabaseList() + +################################################################################ +# RUN +################################################################################ +execute(connectionDetails = connectionDetails, + study = study, + datasources = datasources, + createCodeList = FALSE, + createUniverse = FALSE, + createCohortTables = FALSE, #This drops all cohort data + buildTheCohorts = FALSE, + buildOutcomeCohorts = FALSE, + buildNegativeControlCohorts = FALSE, + buildTheCohortsDose = FALSE, + combinedDbData = FALSE, + exportResults = FALSE, + exportPotentialRiskFactors = FALSE, + exportPotentialRiskFactorsScores = FALSE, + exportMeanAge = FALSE, + exportTwoPlusNonSGLT2i = FALSE, + exportReviewDKAEvents = FALSE, + exportInitislSGLT2iDosage = FALSE, + exportDKAFatal = FALSE, + exportRelevantLabs = FALSE, + formatPotentialRiskFactors = FALSE, + formatPaticipantsTxInfo = FALSE, + formatFatalDka = TRUE) + + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/R/Main.R",".R","10778","188","#' @export +execute <- function(connectionDetails, + cdmDatabaseSchema, + cohortDatabaseSchema = cdmDatabaseSchema, + cohortTable = ""cohort"", + oracleTempSchema = cohortDatabaseSchema, + outputFolder, + codeListSchema, + codeListTable, + vocabularyDatabaseSchema, + databaseName, + runAnalyses = FALSE, + getMultiTherapyData = FALSE, + runDiagnostics = FALSE, + packageResults = FALSE, + runIrSensitivity = FALSE, + packageIrSensitivityResults = FALSE, + runIrDose = FALSE, + packageIrDose = FALSE, + maxCores = 4, + minCellCount= 5) { + + start <- Sys.time() + + if (!file.exists(outputFolder)) + dir.create(outputFolder, recursive = TRUE) + + OhdsiRTools::addDefaultFileLogger(file.path(outputFolder, ""log.txt"")) + + if (runAnalyses) { + OhdsiRTools::logInfo(""Running analyses"") + cmOutputFolder <- file.path(outputFolder, ""cmOutput"") + if (!file.exists(cmOutputFolder)) + dir.create(cmOutputFolder) + + # analysis Settings + cmAnalysisListFile <- system.file(""settings"", ""cmAnalysisList.json"", package = ""sglt2iDka"") + cmAnalysisList <- CohortMethod::loadCmAnalysisList(cmAnalysisListFile) + cmAnalysisList <- sglt2iDka::setOutcomeDatabaseSchemaAndTable(settings = cmAnalysisList, + outcomeDatabaseSchema = cohortDatabaseSchema, + outcomeTable = cohortTable) + cmAnalysisList <- sglt2iDka::setExposureDatabaseSchemaAndIds(settings = cmAnalysisList, + exposureDatabaseSchema = cdmDatabaseSchema, + codeListSchema = codeListSchema, + codeListTable = codeListTable, + vocabularyDatabaseSchema = vocabularyDatabaseSchema) + + # tcos + tcoList <- sglt2iDka::createTcos() # 62 TCs * 45 main and NC outcomes * 2 analyses = 5580 estimates + results <- CohortMethod::runCmAnalyses(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + exposureDatabaseSchema = cohortDatabaseSchema, + exposureTable = cohortTable, + outcomeDatabaseSchema = cohortDatabaseSchema, + outcomeTable = cohortTable, + outputFolder = cmOutputFolder, + oracleTempSchema = oracleTempSchema, + cmAnalysisList = cmAnalysisList, + drugComparatorOutcomesList = tcoList, + getDbCohortMethodDataThreads = min(3, maxCores), + createStudyPopThreads = min(3, maxCores), + createPsThreads = max(1, round(maxCores/10)), + psCvThreads = min(10, maxCores), + computeCovarBalThreads = min(3, maxCores), + trimMatchStratifyThreads = min(10, maxCores), + fitOutcomeModelThreads = max(1, round(maxCores/4)), + outcomeCvThreads = min(4, maxCores), + refitPsForEveryOutcome = FALSE) + } + + if (getMultiTherapyData) { + OhdsiRTools::logInfo(""Getting multi-therapy data from server"") + sglt2iDka::getMultiTherapyData(connectionDetails = connectionDetails, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortDefinitionTable = cohortDefinitionTable, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortTable = cohortTable, + codeListTable = codeListTable, + oracleTempSchema = oracleTempSchema, + outputFolder = outputFolder) + } + + + if (runDiagnostics) { + OhdsiRTools::logInfo(""Running diagnostics"") + sglt2iDka::generateDiagnostics(outputFolder = outputFolder, + databaseName = databaseName) + sglt2iDka::hrHeterogeneity(outputFolder = outputFolder, + databaseName = databaseName, + primaryOnly = FALSE) + } + + if (packageResults) { + OhdsiRTools::logInfo(""Packaging results"") + sglt2iDka::prepareResultsForAnalysis(outputFolder = outputFolder, + databaseName = databaseName, + maxCores = maxCores) + } + + if (runIrSensitivity) { + OhdsiRTools::logInfo(""Running IR sensitivity analysis"") + cmIrSensitivityFolder <- file.path(outputFolder, ""cmIrSensitivityOutput"") + if (!file.exists(cmIrSensitivityFolder)) + dir.create(cmIrSensitivityFolder) + + # analysis settings + cmIrSensitivityListFile <- system.file(""settings"", ""cmIrSensitivityAnalysisList.json"", package = ""sglt2iDka"") + cmIrSensitivityList <- CohortMethod::loadCmAnalysisList(cmIrSensitivityListFile) + cmIrSensitivityList <- sglt2iDka::setOutcomeDatabaseSchemaAndTable(settings = cmIrSensitivityList, + outcomeDatabaseSchema = cohortDatabaseSchema, + outcomeTable = cohortTable) + cmIrSensitivityList <- sglt2iDka::setExposureDatabaseSchemaAndIds(settings = cmIrSensitivityList, + exposureDatabaseSchema = cdmDatabaseSchema, + codeListSchema = codeListSchema, + codeListTable = codeListTable, + vocabularyDatabaseSchema = vocabularyDatabaseSchema) + + # tcos + tcoIrSensitivityList <- sglt2iDka::createIrSensitivityTcos() + results <- CohortMethod::runCmAnalyses(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + exposureDatabaseSchema = cohortDatabaseSchema, + exposureTable = cohortTable, + outcomeDatabaseSchema = cohortDatabaseSchema, + outcomeTable = cohortTable, + outputFolder = cmIrSensitivityFolder, + oracleTempSchema = oracleTempSchema, + cmAnalysisList = cmIrSensitivityList, + drugComparatorOutcomesList = tcoIrSensitivityList, + getDbCohortMethodDataThreads = min(3, maxCores), + createStudyPopThreads = min(3, maxCores)) + } + + if (packageIrSensitivityResults) { + OhdsiRTools::logInfo(""Packaging IR sensitivity results"") + sglt2iDka::prepareIrSensitivityResultsForAnalysis(outputFolder = outputFolder, + databaseName = databaseName, + maxCores = maxCores) + } + + if (runIrDose) { + OhdsiRTools::logInfo(""Running IR dose analysis"") + cmIrDoseFolder <- file.path(outputFolder, ""cmIrDoseOutput"") + if (!file.exists(cmIrDoseFolder)) + dir.create(cmIrDoseFolder) + + cohortDoseTable <- paste(cohortTable, ""dose"", sep = ""_"") + + # analysis settings + cmIrDoseListFile <- system.file(""settings"", ""cmIrDoseAnalysisList.json"", package = ""sglt2iDka"") + cmIrDoseList <- CohortMethod::loadCmAnalysisList(cmIrDoseListFile) + cmIrDoseList <- sglt2iDka::setOutcomeDatabaseSchemaAndTable(settings = cmIrDoseList, + outcomeDatabaseSchema = cohortDatabaseSchema, + outcomeTable = cohortTable) + cmIrDoseList <- sglt2iDka::setExposureDatabaseSchemaAndIds(settings = cmIrDoseList, + exposureDatabaseSchema = cdmDatabaseSchema, + codeListSchema = codeListSchema, + codeListTable = codeListTable, + vocabularyDatabaseSchema = vocabularyDatabaseSchema) + + # tcos + tcoIrDoseList <- sglt2iDka::createIrDoseTcos() + results <- CohortMethod::runCmAnalyses(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + exposureDatabaseSchema = cohortDatabaseSchema, + exposureTable = cohortDoseTable, + outcomeDatabaseSchema = cohortDatabaseSchema, + outcomeTable = cohortTable, + outputFolder = cmIrDoseFolder, + oracleTempSchema = oracleTempSchema, + cmAnalysisList = cmIrDoseList, + drugComparatorOutcomesList = tcoIrDoseList, + getDbCohortMethodDataThreads = min(3, maxCores), + createStudyPopThreads = min(3, maxCores)) + } + + if (packageIrDose) { + OhdsiRTools::logInfo(""Packaging IR dose results"") + sglt2iDka::prepareIrDoseResultsForAnalysis(outputFolder = outputFolder, + databaseName = databaseName, + maxCores = maxCores) + } + + delta <- Sys.time() - start + writeLines(paste(""Completed analyses in"", signif(delta, 3), attr(delta, ""units""))) + invisible(NULL) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/R/SummarizeOneAnalysis.R",".R","1677","44","#' @export +summarizeOneAnalysis <- function(outcomeModel) { + + result <- data.frame(rr = 0, + ci95lb = 0, + ci95ub = 0, + p = 1, + treated = 0, + comparator = 0, + treatedDays = NA, + comparatorDays = NA, + eventsTreated = 0, + eventsComparator = 0, + logRr = 0, + seLogRr = 0) + + result$rr <- if (is.null(coef(outcomeModel))) + NA else exp(coef(outcomeModel)) + result$ci95lb <- if (is.null(coef(outcomeModel))) + NA else exp(confint(outcomeModel)[1]) + result$ci95ub <- if (is.null(coef(outcomeModel))) + NA else exp(confint(outcomeModel)[2]) + if (is.null(coef(outcomeModel))) { + result$p <- NA + } else { + z <- coef(outcomeModel)/outcomeModel$outcomeModelTreatmentEstimate$seLogRr + result$p <- 2 * pmin(pnorm(z), 1 - pnorm(z)) + } + result$treated <- outcomeModel$populationCounts$treatedPersons + result$comparator <- outcomeModel$populationCounts$comparatorPersons + if (outcomeModel$outcomeModelType %in% c(""cox"", ""poisson"")) { + result$treatedDays <- outcomeModel$timeAtRisk$treatedDays + result$comparatorDays <- outcomeModel$timeAtRisk$comparatorDays + } + result$eventsTreated <- outcomeModel$outcomeCounts$treatedOutcomes + result$eventsComparator <- outcomeModel$outcomeCounts$comparatorOutcomes + result$logRr <- if (is.null(coef(outcomeModel))) + NA else coef(outcomeModel) + result$seLogRr <- if (is.null(coef(outcomeModel))) + NA else outcomeModel$outcomeModelTreatmentEstimate$seLogRr + + return(result) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/R/getMultiTherapyData.R",".R","1911","34","#' @export +getMultiTherapyData <- function(connectionDetails, + cohortDatabaseSchema, + cohortDefinitionTable, + cdmDatabaseSchema, + cohortTable, + codeListTable, + oracleTempSchema = NULL, + outputFolder) { + if (!file.exists(outputFolder)) + dir.create(outputFolder, recursive = TRUE) + + connection <- DatabaseConnector::connect(connectionDetails) + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""getMultiTherapyCovariates.sql"", + packageName = ""sglt2iDka"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cohort_database_schema = cohortDatabaseSchema, + cohort_definition_table = cohortDefinitionTable, + cohort_table = cohortTable, + code_list_table = codeListTable, + cdm_database_schema = cdmDatabaseSchema) + covariates <- DatabaseConnector::querySql.ffdf(connection, sql) + colnames(covariates) <- SqlRender::snakeCaseToCamelCase(colnames(covariates)) + + covariateRef <- data.frame(covariateId = c(500001, 500002, 500003), + covariateName = c(""AHA monotherapy"", ""AHA dual therapy"", ""AHA >= triple therapy""), + analysisId = c(996, 996, 996), + conceptId = NA) + covariateRef <- ff::as.ffdf(covariateRef) + DatabaseConnector::disconnect(connection) + ffbase::save.ffdf(covariates, covariateRef, dir = file.path(outputFolder, ""multiTherapyData"")) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/R/createIrTableFormatted.R",".R","10633","192","#' @export +createIrTableFormatted <- function(outputFolders, + databaseNames, + reportFolder, + sensitivity) { + if (sensitivity == FALSE) { + loadResultsHois <- function(outputFolder, + fileName) { + shinyDataFolder <- file.path(outputFolder, ""results"", ""shinyData"") + file <- list.files(shinyDataFolder, pattern = ""resultsHois_.*.rds"", full.names = TRUE) + x <- readRDS(file) + if (is.null(x$i2)) + x$i2 <- NA + return(x) + } + results <- lapply(outputFolders, loadResultsHois) + results <- do.call(rbind, results) + results$targetCohort <- sub(pattern = ""-90"", replacement = """", x = results$targetName) + results$comparatorCohort <- sub(pattern = ""-90"", replacement = """", x = results$comparatorName) + results$timeAtRisk[results$analysisDescription == ""Time to First Post Index Event Intent to Treat Matching""] <- ""ITT"" + results$timeAtRisk[results$analysisDescription == ""Time to First Post Index Event Per Protocol Matching""] <- ""PP"" + fileName <- file.path(reportFolder, paste0(""IRsFormatted.xlsx"")) + unlink(fileName) + } + + if (sensitivity == TRUE) { + loadIrSensitivityResults <- function(outputFolder) { + shinyDataFolder <- file.path(outputFolder, ""results"", ""irSensitivityData"") + file <- list.files(shinyDataFolder, pattern = ""irSensitivityData_.*.rds"", full.names = TRUE) + x <- readRDS(file) + return(x) + } + results <- lapply(outputFolders, loadIrSensitivityResults) + results <- do.call(rbind, results) + results$timeAtRisk <- """" + results[grep(""-60"", results$targetName), ""timeAtRisk""] <- ""PP-60"" + results[grep(""-120"", results$targetName), ""timeAtRisk""] <- ""PP-120"" + results$targetCohort <- sub(pattern = ""-60"", replacement = """", x = results$targetName) + results$targetCohort <- sub(pattern = ""-120"", replacement = """", x = results$targetCohort) + results$comparatorCohort <- sub(pattern = ""-60"", replacement = """", x = results$comparatorName) + results$comparatorCohort <- sub(pattern = ""-120"", replacement = """", x = results$comparatorCohort) + fileName <- file.path(reportFolder, paste0(""IRsSensitivityFormatted.xlsx"")) + unlink(fileName) + } + + outcomeNames <- unique(results$outcomeName) + timeAtRisks <- unique(results$timeAtRisk) + wb <- XLConnect::loadWorkbook(fileName, create = TRUE) + + subgroups <- list( + Overall = c( + ""bmTreated"", ""bmTreatedDays"", ""bmEventsTreated"", + ""bmTarTargetMean"", ""bmTarTargetSd"", ""bmTarTargetMin"", ""bmTarTargetMedian"", ""bmTarTargetMax"", + ""bmComparator"", ""bmComparatorDays"", ""bmEventsComparator"", + ""bmTarComparatorMean"", ""bmTarComparatorSd"", ""bmTarComparatorMin"", ""bmTarComparatorMedian"", ""bmTarComparatorMax"")) + + for (i in 1:length(subgroups)) { # i=1 + mainTable <- data.frame() + cols <- subgroups[[i]] + subgroup <- names(subgroups)[i] + for (database in databaseNames) { # database <- ""CCAE"" + dbTable <- data.frame() + for (outcomeName in outcomeNames[[2]]) { # outcomeName <- outcomeNames[2], only DKA IP/ER + for (timeAtRisk in timeAtRisks[[1]]) { # timeAtRisk <- timeAtRisks[[1]], only ITT + subset <- results[results$database == database & + results$outcomeName == outcomeName & + results$timeAtRisk == timeAtRisk, ] + + # Ts broad + sglt2iBroad <- subset[subset$targetCohort == ""SGLT2i-BROAD"", ][1, cols] + canaBroad <- subset[subset$targetCohort == ""Canagliflozin-BROAD"", ][1, cols] + dapaBroad <- subset[subset$targetCohort == ""Dapagliflozin-BROAD"", ][1, cols] + empaBroad <- subset[subset$targetCohort == ""Empagliflozin-BROAD"", ][1, cols] + + # Cs broad + dpp4Broad <- subset[subset$comparatorCohort == ""DPP-4i-BROAD"", ][1, cols] + glp1Broad <- subset[subset$comparatorCohort == ""GLP-1a-BROAD"", ][1, cols] + suBroad <- subset[subset$comparatorCohort == ""SU-BROAD"", ][1, cols] + tzdBroad <- subset[subset$comparatorCohort == ""TZDs-BROAD"", ][1, cols] + insulinBroad <- subset[subset$comparatorCohort == ""Insulin-BROAD"", ][1, cols] + metforminBroad <- subset[subset$comparatorCohort == ""Metformin-BROAD"", ][1, cols] + insAhasBroad <- subset[subset$comparatorCohort == ""Insulinotropic AHAs-BROAD"", ][1, cols] + otherAhasBroad <- subset[subset$comparatorCohort == ""Other AHAs-BROAD"", ][1, cols] + + # Ts narrow + sglt2iNarrow <- subset[subset$targetCohort == ""SGLT2i-NARROW"", ][1, cols] + canaNarrow <- subset[subset$targetCohort == ""Canagliflozin-NARROW"", ][1, cols] + empaNarrow <- subset[subset$targetCohort == ""Empagliflozin-NARROW"", ][1, cols] + dapaNarrow <- subset[subset$targetCohort == ""Dapagliflozin-NARROW"", ][1, cols] + + # Cs narrow + dpp4Narrow <- subset[subset$comparatorCohort == ""DPP-4i-NARROW"", ][1, cols] + glp1Narrow <- subset[subset$comparatorCohort == ""GLP-1a-NARROW"", ][1, cols] + suNarrow <- subset[subset$comparatorCohort == ""SU-NARROW"", ][1, cols] + tzdNarrow <- subset[subset$comparatorCohort == ""TZDs-NARROW"", ][1, cols] + insulinNarrow <- subset[subset$comparatorCohort == ""Insulin-NARROW"", ][1, cols] + metforminNarrow <- subset[subset$comparatorCohort == ""Metformin-NARROW"", ][1, cols] + insAhasNarrow <- subset[subset$comparatorCohort == ""Insulinotropic AHAs-NARROW"", ][1, cols] + otherAhasNarrow <- subset[subset$comparatorCohort == ""Other AHAs-NARROW"", ][1, cols] + + subTable <- data.frame(exposure = c( + ""SGLT2i-BROAD"", ""Canagliflozin-BROAD"", ""Dapagliflozin-BROAD"", ""Empagliflozin-BROAD"", + ""DPP-4i-BROAD"", ""GLP-1a-BROAD"", ""SU-BROAD"", ""TZDs-BROAD"", + ""Insulin-BROAD"", ""Metformin-BROAD"", ""Insulinotropic AHAs-BROAD"", ""Other AHAs-BROAD"", + + ""SGLT2i-NARROW"", ""Canagliflozin-NARROW"", ""Dapagliflozin-NARROW"", ""Empagliflozin-NARROW"", + ""DPP-4i-NARROW"", ""GLP-1a-NARROW"", ""SU-NARROW"", ""TZDs-NARROW"", + ""Insulin-NARROW"", ""Metformin-NARROW"", ""Insulinotropic AHAs-NARROW"", ""Other AHAs-NARROW""), + + database = database, + + events = c( + sglt2iBroad[, 3], canaBroad[, 3], dapaBroad[, 3], empaBroad[, 3], + dpp4Broad[, 11], glp1Broad[, 11], suBroad[, 11], tzdBroad[, 11], + insulinBroad[, 11], metforminBroad[, 11], insAhasBroad[, 11], otherAhasBroad[, 11], + + sglt2iNarrow[, 3], canaNarrow[, 3], dapaNarrow[, 3], empaNarrow[, 3], + dpp4Narrow[, 11], glp1Narrow[, 11], suNarrow[, 11], tzdNarrow[, 11], + insulinNarrow[, 11], metforminNarrow[, 11], insAhasNarrow[, 11], otherAhasNarrow[, 11]), + + personTime = c( + sglt2iBroad[, 2], canaBroad[, 2], dapaBroad[, 2], empaBroad[, 2], + dpp4Broad[, 10], glp1Broad[, 10], suBroad[, 10], tzdBroad[, 10], + insulinBroad[, 10], metforminBroad[, 10], insAhasBroad[, 10], otherAhasBroad[, 10], + + sglt2iNarrow[, 2], canaNarrow[, 2], dapaNarrow[, 2], empaNarrow[, 2], + dpp4Narrow[, 10], glp1Narrow[, 10], suNarrow[, 10], tzdNarrow[, 10], + insulinNarrow[, 10], metforminNarrow[, 10], insAhasNarrow[, 10], otherAhasNarrow[, 10]) / 365.25) + + subTable$ir <- 1000 * subTable$events / subTable$personTime + + broadSubTable <- subTable[grep(""BROAD"", subTable$exposure), c(""exposure"", ""database"", ""events"", ""personTime"", ""ir"")] + narrowSubTable <- subTable[grep(""NARROW"", subTable$exposure), c(""events"", ""personTime"", ""ir"")] + + formattedSubTable <- cbind(broadSubTable, narrowSubTable) + formattedSubTable$exposure <- sub(""-BROAD"", """", formattedSubTable$exposure) + names(formattedSubTable) <- c(""exposure"", ""database"", ""eventsBroad"", ""personTimeBroad"", ""irBroad"", ""eventsNarrow"", ""personTimeNarrow"", ""irNarrow"") + + dbTable <- rbind(dbTable, formattedSubTable) + } + } + + if (ncol(mainTable) == 0) { + mainTable <- dbTable + } else { + mainTable <- rbind(mainTable, dbTable) + } + } + mainTable[, c(4, 7)] <- round(mainTable[, c(4, 7)], 0) # PYs + mainTable[, c(5, 8)] <- round(mainTable[, c(5, 8)], 2) # IRs + mainTable$exposureOrder <- match(mainTable$exposure, unique(mainTable$exposure)) + mainTable$dbOrder <- match(mainTable$database, c(""CCAE"", ""MDCD"", ""MDCR"", ""Optum"")) + mainTable <- mainTable[order(mainTable$exposureOrder, mainTable$dbOrder), ] + mainTable <- mainTable[, -c(9,10)] + + XLConnect::createSheet(wb, name = subgroup) + header0 <- c("""", """", rep(""Broad T2DM"", 3), rep(""Narrow T2DM"", 3)) + XLConnect::writeWorksheet(wb, + sheet = subgroup, + data = as.data.frame(t(header0)), + startRow = 1, + startCol = 1, + rownames = FALSE, + header = FALSE) + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""C1:E1"") + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""F1:H1"") + + header1 <- c(""Exposure"", + ""Database"", + rep(c(""Events"", ""Time-at-risk"", ""IR""), 2)) + XLConnect::writeWorksheet(wb, + sheet = subgroup, + data = as.data.frame(t(header1)), + startRow = 2, + startCol = 1, + rownames = FALSE, + header = FALSE) + XLConnect::writeWorksheet(wb, + sheet = subgroup, + data = mainTable, + startRow = 3, + startCol = 1, + rownames = FALSE, + header = FALSE) + cells <- paste0(""A"", seq(from = 3, to = 47, by = 4), "":A"", seq(from = 6, to = 50, by = 4)) + for (cell in cells) { + XLConnect::mergeCells(wb, sheet = subgroup, reference = cell) + } + } + XLConnect::saveWorkbook(wb) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/R/createHrTableFormatted.R",".R","9250","162","#' @export +createHrTableFormatted <- function(outputFolders, + databaseNames, + maOutputFolder, + reportFolder) { + loadResultsHois <- function(outputFolder, + fileName) { + shinyDataFolder <- file.path(outputFolder, ""results"", ""shinyData"") + file <- list.files(shinyDataFolder, pattern = ""resultsHois_.*.rds"", full.names = TRUE) + x <- readRDS(file) + if (is.null(x$i2)) + x$i2 <- NA + return(x) + } + results <- lapply(c(outputFolders, maOutputFolder), loadResultsHois) + results <- do.call(rbind, results) + results$targetCohort <- sub(pattern = ""-90"", replacement = """", x = results$targetName) + results$comparatorCohort <- sub(pattern = ""-90"", replacement = """", x = results$comparatorName) + results$comparison <- paste(results$targetCohort, results$comparatorCohort, sep = "" - "") + results$timeAtRisk[results$analysisDescription == ""Time to First Post Index Event Intent to Treat Matching""] <- ""ITT"" + results$timeAtRisk[results$analysisDescription == ""Time to First Post Index Event Per Protocol Matching""] <- ""PP"" + tcosAnalyses <- read.csv(system.file(""settings"", ""tcoAnalysisVariants.csv"", package = ""sglt2iDka""), stringsAsFactors = FALSE) # for correct ordering + tcosAnalyses$tOrder <- match(tcosAnalyses$targetCohortName, c(""SGLT2i-BROAD-90"", + ""SGLT2i-NARROW-90"", + ""Canagliflozin-BROAD-90"", + ""Canagliflozin-NARROW-90"", + ""Dapagliflozin-BROAD-90"", + ""Dapagliflozin-NARROW-90"", + ""Empagliflozin-BROAD-90"", + ""Empagliflozin-NARROW-90"")) + tcosAnalyses$cOrder <- match(tcosAnalyses$comparatorCohortName, c(""SU-BROAD-90"", + ""SU-NARROW-90"", + ""DPP-4i-BROAD-90"", + ""DPP-4i-NARROW-90"", + ""GLP-1a-BROAD-90"", + ""GLP-1a-NARROW-90"", + ""TZDs-BROAD-90"", + ""TZDs-NARROW-90"", + ""Insulin-BROAD-90"", + ""Insulin-NARROW-90"", + ""Metformin-BROAD-90"", + ""Metformin-NARROW-90"", + ""Insulinotropic AHAs-BROAD-90"", + ""Insulinotropic AHAs-NARROW-90"", + ""Other AHAs-BROAD-90"", + ""Other AHAs-NARROW-90"")) + tcosAnalyses <- tcosAnalyses[order(tcosAnalyses$tOrder, tcosAnalyses$cOrder), ] + tcosAnalyses$targetCohort <- sub(pattern = ""-90"", replacement = """", x = tcosAnalyses$targetCohortName) + tcosAnalyses$comparatorCohort <- sub(pattern = ""-90"", replacement = """", x = tcosAnalyses$comparatorCohortName) + comparisonsOfInterest <- unique(paste(tcosAnalyses$targetCohort, tcosAnalyses$comparatorCohort, sep = "" - "")) + outcomeNames <- unique(results$outcomeName) + timeAtRisks <- unique(results$timeAtRisk) + + fileName <- file.path(reportFolder, paste0(""HRsFormatted.xlsx"")) + unlink(fileName) + wb <- XLConnect::loadWorkbook(fileName, create = TRUE) + + for (outcomeName in outcomeNames) { # outcomeName <- outcomeNames[2] + for (timeAtRisk in timeAtRisks) { # timeAtRisk <- timeAtRisks[1] + + results$dbOrder <- match(results$database, c(""CCAE"", ""MDCD"", ""MDCR"", ""Optum"", ""Meta-analysis"")) + results$comparisonOrder <- match(results$comparison, comparisonsOfInterest) + results <- results[order(results$comparisonOrder, results$dbOrder), ] + + idx <- results$outcomeName == outcomeName & results$timeAtRisk == timeAtRisk # & results$comparison %in% comparisonsOfInterest + + results$rr[results$eventsTreated == 0 | results$eventsComparator == 0 | is.na(results$seLogRr) | is.infinite(results$seLogRr)] <- NA + results$ci95lb[results$eventsTreated == 0 | results$eventsComparator == 0 | is.na(results$seLogRr) | is.infinite(results$seLogRr)] <- NA + results$ci95ub[results$eventsTreated == 0 | results$eventsComparator == 0 | is.na(results$seLogRr) | is.infinite(results$seLogRr)] <- NA + drops <- names(results) %in% grep(""bm"", names(results), value = TRUE) + results <- results[!drops] + + outTarResults <- results[idx, ] + + outTarBroadResults <- outTarResults[grep(""BROAD"", outTarResults$targetName), ] + outTarBroadResults$comparison <- gsub(""-BROAD"", """", outTarBroadResults$comparison) + + outTarNarrowResults <- outTarResults[grep(""NARROW"", outTarResults$targetName), ] + outTarNarrowResults$comparison <- gsub(""-NARROW"", """", outTarNarrowResults$comparison) + + formatComparison <- function(x) { + result <- sub(pattern = "" - "", replacement = "" vs. "", x = x) + return(result) + } + + formatSampleSize <- function(subjects) { + paste(formatC(subjects, big.mark = "","", format=""d"")) + } + + formatEventCounts <- function(tEvents, cEvents) { + paste(tEvents, cEvents, sep = "" / "") + } + formatHr <- function(hr, lb, ub) { + sprintf(""%s (%s-%s)"", + formatC(hr, digits = 2, format = ""f""), + formatC(lb, digits = 2, format = ""f""), + formatC(ub, digits = 2, format = ""f"")) + } + + mainTable <- data.frame(question = formatComparison(outTarBroadResults$comparison), + source = outTarBroadResults$database, + broadPairs = formatSampleSize(outTarBroadResults$treated), + broadEvents = formatEventCounts(outTarBroadResults$eventsTreated, outTarBroadResults$eventsComparator), + broadHr = formatHr(outTarBroadResults$rr, outTarBroadResults$ci95lb, outTarBroadResults$ci95ub), + broadP = round(outTarBroadResults$p, 2), + broadCalP = round(outTarBroadResults$calP, 2), + + narrowPairs = formatSampleSize(outTarNarrowResults$treated), + narrowEvents = formatEventCounts(outTarNarrowResults$eventsTreated, outTarNarrowResults$eventsComparator), + narrowHr = formatHr(outTarNarrowResults$rr, outTarNarrowResults$ci95lb, outTarNarrowResults$ci95ub), + narrowP = round(outTarNarrowResults$p, 2), + narrowCalP = round(outTarNarrowResults$calP, 2)) + + sheet <- paste(outcomeName, timeAtRisk) + XLConnect::createSheet(wb, name = sheet) + header0 <- rep("""", 12) + header0[3] <- ""Broad T2DM"" + header0[8] <- ""Narrow T2DM"" + XLConnect::writeWorksheet(wb, + sheet = sheet, + data = as.data.frame(t(header0)), + startRow = 1, + startCol = 1, + rownames = FALSE, + header = FALSE) + XLConnect::mergeCells(wb, sheet = sheet, reference = ""C1:G1"") + XLConnect::mergeCells(wb, sheet = sheet, reference = ""H1:L1"") + header1 <- c(""Comparison"", + ""Database"", + ""N pairs"", + ""N events (T/C)"", + ""HR (95% CI)"", + ""p"", + ""Cal. p"", + ""N pairs"", + ""N events (T/C)"", + ""HR (95% CI)"", + ""p"", + ""Cal. p"") + XLConnect::writeWorksheet(wb, + sheet = sheet, + data = as.data.frame(t(header1)), + startRow = 2, + startCol = 1, + rownames = FALSE, + header = FALSE) + XLConnect::writeWorksheet(wb, + data = mainTable, + sheet = sheet, + startRow = 3, + startCol = 1, + header = FALSE, + rownames = FALSE) + cells <- paste0(""A"", seq(from = 3, to = 153, by = 5), "":A"", seq(from = 7, to = 157, by = 5)) + for (cell in cells) { + XLConnect::mergeCells(wb, sheet = sheet, reference = cell) + } + } + } + XLConnect::saveWorkbook(wb) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/R/prepareIrSensitivityResultsForAnalysis.R",".R","48767","532","#' @export +prepareIrSensitivityResultsForAnalysis <- function(outputFolder, + databaseName, + maxCores) { + packageName <- ""sglt2iDka"" + cmIrSensitivityOutputFolder <- file.path(outputFolder, ""cmIrSensitivityOutput"") + resultsFolder <- file.path(outputFolder, ""results"") + if (!file.exists(resultsFolder)) + dir.create(resultsFolder) + irSensitivityDataFolder <- file.path(resultsFolder, ""irSensitivityData"") + if (!file.exists(irSensitivityDataFolder)) + dir.create(irSensitivityDataFolder) + + # TCOs of interest + tcosOfInterest <- read.csv(system.file(""settings"", ""tcoIrSensitivityVariants.csv"", package = packageName), stringsAsFactors = FALSE) + tcosOfInterest <- unique(tcosOfInterest[, c(""targetCohortId"", ""targetDrugName"", ""targetCohortName"", ""comparatorCohortId"", ""comparatorDrugName"", ""comparatorCohortName"", + ""outcomeCohortId"", ""outcomeCohortName"")]) + names(tcosOfInterest) <- c(""targetId"", ""targetDrugName"", ""targetName"", ""comparatorId"", ""comparatorDrugName"", ""comparatorName"", + ""outcomeId"", ""outcomeName"") + reference <- readRDS(file.path(cmIrSensitivityOutputFolder, ""outcomeModelReference.rds"")) + analysisSummary <- CohortMethod::summarizeAnalyses(reference) + analysisSummary <- sglt2iDka::addCohortNames(analysisSummary, dose = FALSE, ""outcomeId"", ""outcomeName"") + analysisSummary <- sglt2iDka::addCohortNames(analysisSummary, dose = FALSE, ""comparatorId"", ""comparatorName"") + analysisSummary <- sglt2iDka::addCohortNames(analysisSummary, dose = FALSE, ""targetId"", ""targetName"") + cmAnalysisList <- CohortMethod::loadCmAnalysisList(system.file(""settings"", ""cmIrSensitivityAnalysisList.json"", package = packageName)) + analyses <- data.frame(analysisId = unique(reference$analysisId), + analysisDescription = """", + stringsAsFactors = FALSE) + for (i in 1:length(cmAnalysisList)) { + analyses$analysisDescription[analyses$analysisId == cmAnalysisList[[i]]$analysisId] <- cmAnalysisList[[i]]$description + } + analysisSummary <- merge(analysisSummary, analyses) + analysisSummary <- analysisSummary[, c(1,20,2:19)] + analysisSummary <- analysisSummary[, -which(names(analysisSummary) %in% c(""rr"", ""ci95lb"", ""ci95ub"", ""p"", ""logRr"", ""seLogRr""))] + analysisSummary$database <- databaseName + + #for dev + # comparison <- paste(analysisSummary$targetId, analysisSummary$comparatorId) + # chunks <- split(analysisSummary, comparison) + # chunk <- chunks[[1]] + #for dev + + runTc <- function(chunk, + tcosOfInterest, + reference) { + tcsOfInterest <- unique(tcosOfInterest[, c(""targetId"", ""comparatorId"")]) + targetId <- chunk$targetId[1] + comparatorId <- chunk$comparatorId[1] + outcomeIds <- unique(tcosOfInterest$outcomeId) + outcomeNames <- unique(tcosOfInterest$outcomeName) + OhdsiRTools::logTrace(""Preparing results for target ID "", targetId, "", comparator ID"", comparatorId) + + for (analysisId in unique(reference$analysisId)) { # only 1 analysis + # analysisId=1 + + OhdsiRTools::logTrace(""Analysis ID "", analysisId) + + for (outcomeId in outcomeIds) { + # outcomeId=200 + + OhdsiRTools::logTrace(""Outcome ID "", outcomeId) + outcomeName <- outcomeNames[outcomeIds == outcomeId] + idx <- chunk$analysisId == analysisId & + chunk$targetId == targetId & + chunk$comparatorId == comparatorId & + chunk$outcomeId == outcomeId + refRow <- reference[reference$analysisId == analysisId & + reference$targetId == targetId & + reference$comparatorId == comparatorId & + reference$outcomeId == outcomeId, ] + cmData <- CohortMethod::loadCohortMethodData(refRow$cohortMethodDataFolder) + + # IR stratification data + # covarRef <- as.data.frame(cmData$covariateRef) + # covarRef <- covarRef[order(covarRef$covariateId), ] + # covarRef[covarRef$analysisId==3, 1:2] + covariates <- as.data.frame(cmData$covariates) + covariates <- covariates[covariates$covariateId %in% c(8507001, 1998, 2998, 200999, 201999, # intentionally drop 8532001 as redundant + 2003, 3003, 4003, 5003, 6003, 7003, 8003, 9003, 10003, 11003, 12003, 13003, 14003, 15003, 16003, 17003, 18003, 19003, 20003, 21003), ] + covariates <- reshape(covariates, idvar = ""rowId"", timevar = ""covariateId"", direction = ""wide"") + names(covariates)[names(covariates) == ""covariateValue.8507001""] <- ""Male"" + names(covariates)[names(covariates) == ""covariateValue.1998""] <- ""PriorInsulin"" + names(covariates)[names(covariates) == ""covariateValue.2998""] <- ""PriorAha"" + names(covariates)[names(covariates) == ""covariateValue.200999""] <- ""PriorDkaIpEr"" + names(covariates)[names(covariates) == ""covariateValue.201999""] <- ""PriorDkaIp"" + if (is.null(covariates$covariateValue.2003)) covariates$Age10_14 <- 0 else covariates$Age10_14[covariates$covariateValue.2003 == 1] <- 1 + if (is.null(covariates$covariateValue.3003)) covariates$Age15_19 <- 0 else covariates$Age15_19[covariates$covariateValue.3003 == 1] <- 1 + if (is.null(covariates$covariateValue.4003)) covariates$Age20_24 <- 0 else covariates$Age20_24[covariates$covariateValue.4003 == 1] <- 1 + if (is.null(covariates$covariateValue.5003)) covariates$Age25_29 <- 0 else covariates$Age25_29[covariates$covariateValue.5003 == 1] <- 1 + if (is.null(covariates$covariateValue.6003)) covariates$Age30_34 <- 0 else covariates$Age30_34[covariates$covariateValue.6003 == 1] <- 1 + if (is.null(covariates$covariateValue.7003)) covariates$Age35_39 <- 0 else covariates$Age35_39[covariates$covariateValue.7003 == 1] <- 1 + if (is.null(covariates$covariateValue.8003)) covariates$Age40_44 <- 0 else covariates$Age40_44[covariates$covariateValue.8003 == 1] <- 1 + if (is.null(covariates$covariateValue.9003)) covariates$Age45_49 <- 0 else covariates$Age45_49[covariates$covariateValue.9003 == 1] <- 1 + if (is.null(covariates$covariateValue.10003)) covariates$Age50_54 <- 0 else covariates$Age50_54[covariates$covariateValue.10003 == 1] <- 1 + if (is.null(covariates$covariateValue.11003)) covariates$Age55_59 <- 0 else covariates$Age55_59[covariates$covariateValue.11003 == 1] <- 1 + if (is.null(covariates$covariateValue.12003)) covariates$Age60_64 <- 0 else covariates$Age60_64[covariates$covariateValue.12003 == 1] <- 1 + if (is.null(covariates$covariateValue.13003)) covariates$Age65_69 <- 0 else covariates$Age65_69[covariates$covariateValue.13003 == 1] <- 1 + if (is.null(covariates$covariateValue.14003)) covariates$Age70_74 <- 0 else covariates$Age70_74[covariates$covariateValue.14003 == 1] <- 1 + if (is.null(covariates$covariateValue.15003)) covariates$Age75_79 <- 0 else covariates$Age75_79[covariates$covariateValue.15003 == 1] <- 1 + if (is.null(covariates$covariateValue.16003)) covariates$Age80_84 <- 0 else covariates$Age80_84[covariates$covariateValue.16003 == 1] <- 1 + if (is.null(covariates$covariateValue.17003)) covariates$Age85_89 <- 0 else covariates$Age85_89[covariates$covariateValue.17003 == 1] <- 1 + if (is.null(covariates$covariateValue.18003)) covariates$Age90_94 <- 0 else covariates$Age90_94[covariates$covariateValue.18003 == 1] <- 1 + if (is.null(covariates$covariateValue.19003)) covariates$Age95_99 <- 0 else covariates$Age95_99[covariates$covariateValue.19003 == 1] <- 1 + if (is.null(covariates$covariateValue.20003)) covariates$Age100_104 <- 0 else covariates$Age100_104[covariates$covariateValue.20003 == 1] <- 1 + if (is.null(covariates$covariateValue.21003)) covariates$Age105_109 <- 0 else covariates$Age105_109[covariates$covariateValue.21003 == 1] <- 1 + covariates$Age10_19[covariates$Age10_14 == 1 | covariates$Age15_19 == 1] <- 1 + covariates$Age20_29[covariates$Age20_24 == 1 | covariates$Age25_29 == 1] <- 1 + covariates$Age30_39[covariates$Age30_34 == 1 | covariates$Age35_39 == 1] <- 1 + covariates$Age40_49[covariates$Age40_44 == 1 | covariates$Age45_49 == 1] <- 1 + covariates$Age50_59[covariates$Age50_54 == 1 | covariates$Age55_59 == 1] <- 1 + covariates$Age60_69[covariates$Age60_64 == 1 | covariates$Age65_69 == 1] <- 1 + covariates$Age70_79[covariates$Age70_74 == 1 | covariates$Age75_79 == 1] <- 1 + covariates$Age80_89[covariates$Age80_84 == 1 | covariates$Age85_89 == 1] <- 1 + covariates$Age90_99[covariates$Age90_94 == 1 | covariates$Age95_99 == 1] <- 1 + covariates$Age100_109[covariates$Age100_104 == 1 | covariates$Age105_109 == 1] <- 1 + + studyPop <- readRDS(refRow$studyPopFile) + studyPop <- merge(studyPop, covariates, by = ""rowId"", all.x = TRUE) + studyPop[is.na(studyPop)] <- 0 + + studyPop$outcomeCount[studyPop$outcomeCount != 0] <- 1 + studyPop$timeAtRisk <- studyPop$survivalTime + + # overall + bmDistTarget <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1], c(0, 0.5, 1)) + chunk$bmTreated[idx] <- sum(studyPop$treatment == 1) + chunk$bmTreatedDays[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1]) + chunk$bmEventsTreated[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1]) + chunk$bmTarTargetMean[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1]) + chunk$bmTarTargetSd[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1]) + chunk$bmTarTargetMin[idx] <- bmDistTarget[1] + chunk$bmTarTargetMedian[idx] <- bmDistTarget[2] + chunk$bmTarTargetMax[idx] <- bmDistTarget[3] + + bmDistComparator <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0], c(0, 0.5, 1)) + chunk$bmComparator[idx] <- sum(studyPop$treatment == 0) + chunk$bmComparatorDays[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0]) + chunk$bmEventsComparator[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0]) + chunk$bmTarComparatorMean[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0]) + chunk$bmTarComparatorSd[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0]) + chunk$bmTarComparatorMin[idx] <- bmDistComparator[1] + chunk$bmTarComparatorMedian[idx] <- bmDistComparator[2] + chunk$bmTarComparatorMax[idx] <- bmDistComparator[3] + + # getBmIrStats <- function(chunk, + # subgroupName, + # subgroupValue, + # subgroupLabel) { + # bmDistTargetSubgroup <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + # chunk$bmTreatedSubgroup[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + # chunk$bmTreatedDaysSubgroup[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + # chunk$bmEventsTreatedSubgroup[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + # chunk$bmTarTargetMeanSubgroup[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + # chunk$bmTarTargetSdSubgroup[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + # chunk$bmTarTargetMinSubgroup[idx] <- bmDistTargetSubgroup[1] + # chunk$bmTarTargetMedianSubgroup[idx] <- bmDistTargetSubgroup[2] + # chunk$bmTarTargetMaxSubgroup[idx] <- bmDistTargetSubgroup[3] + # bmDistComparatorSubgroup <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + # chunk$bmComparatorSubgroup[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + # chunk$bmComparatorDaysSubgroup[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + # chunk$bmEventsComparatorSubgroup[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + # chunk$bmTarComparatorMeanSubgroup[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + # chunk$bmTarComparatorSdSubgroup[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + # chunk$bmTarComparatorMinSubgroup[idx] <- bmDistComparatorSubgroup[1] + # chunk$bmTarComparatorMedianSubgroup[idx] <- bmDistComparatorSubgroup[2] + # chunk$bmTarComparatorMaxSubgroup[idx] <- bmDistComparatorSubgroup[3] + # colnames(chunk)[seq(length(chunk)-15, length(chunk))] <- sub(pattern = ""Subgroup"", replacement = subgroupLabel, x = colnames(chunk)[seq(length(chunk)-15, length(chunk))]) + # return(chunk) + # } + # + # chunk <- getBmIrStats(""Male"", 1, ""Male"") + # chunk <- getBmIrStats(""Male"", 0, ""Female"") + # chunk <- getBmIrStats(""PriorInsulin"", 1, ""PriorInsulin"") + # chunk <- getBmIrStats(""PriorInsulin"", 0, ""NoPriorInsulin"") + # chunk <- getBmIrStats(""PriorDkaIpEr"", 1, ""PriorDkaIpEr"") + # chunk <- getBmIrStats(""PriorDkaIpEr"", 0, ""NoPriorDkaIpEr"") + + subgroupName = ""Male"" + subgroupValue = 1 + bmDistTargetMale <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreatedMale[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDaysMale[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreatedMale[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMeanMale[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSdMale[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMinMale[idx] <- bmDistTargetMale[1] + chunk$bmTarTargetMedianMale[idx] <- bmDistTargetMale[2] + chunk$bmTarTargetMaxMale[idx] <- bmDistTargetMale[3] + bmDistComparatorMale <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparatorMale[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDaysMale[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparatorMale[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMeanMale[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSdMale[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMinMale[idx] <- bmDistComparatorMale[1] + chunk$bmTarComparatorMedianMale[idx] <- bmDistComparatorMale[2] + chunk$bmTarComparatorMaxMale[idx] <- bmDistComparatorMale[3] + + subgroupName = ""Male"" + subgroupValue = 0 + bmDistTargetFemale <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreatedFemale[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDaysFemale[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreatedFemale[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMeanFemale[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSdFemale[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMinFemale[idx] <- bmDistTargetFemale[1] + chunk$bmTarTargetMedianFemale[idx] <- bmDistTargetFemale[2] + chunk$bmTarTargetMaxFemale[idx] <- bmDistTargetFemale[3] + bmDistComparatorFemale <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparatorFemale[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDaysFemale[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparatorFemale[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMeanFemale[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSdFemale[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMinFemale[idx] <- bmDistComparatorFemale[1] + chunk$bmTarComparatorMedianFemale[idx] <- bmDistComparatorFemale[2] + chunk$bmTarComparatorMaxFemale[idx] <- bmDistComparatorFemale[3] + + subgroupName = ""PriorInsulin"" + subgroupValue = 1 + bmDistTargetPriorInsulin <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreatedPriorInsulin[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDaysPriorInsulin[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreatedPriorInsulin[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMeanPriorInsulin[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSdPriorInsulin[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMinPriorInsulin[idx] <- bmDistTargetPriorInsulin[1] + chunk$bmTarTargetMedianPriorInsulin[idx] <- bmDistTargetPriorInsulin[2] + chunk$bmTarTargetMaxPriorInsulin[idx] <- bmDistTargetPriorInsulin[3] + bmDistComparatorPriorInsulin <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparatorPriorInsulin[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDaysPriorInsulin[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparatorPriorInsulin[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMeanPriorInsulin[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSdPriorInsulin[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMinPriorInsulin[idx] <- bmDistComparatorPriorInsulin[1] + chunk$bmTarComparatorMedianPriorInsulin[idx] <- bmDistComparatorPriorInsulin[2] + chunk$bmTarComparatorMaxPriorInsulin[idx] <- bmDistComparatorPriorInsulin[3] + + subgroupName = ""PriorInsulin"" + subgroupValue = 0 + bmDistTargetNoPriorInsulin <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreatedNoPriorInsulin[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDaysNoPriorInsulin[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreatedNoPriorInsulin[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMeanNoPriorInsulin[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSdNoPriorInsulin[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMinNoPriorInsulin[idx] <- bmDistTargetNoPriorInsulin[1] + chunk$bmTarTargetMedianNoPriorInsulin[idx] <- bmDistTargetNoPriorInsulin[2] + chunk$bmTarTargetMaxNoPriorInsulin[idx] <- bmDistTargetNoPriorInsulin[3] + bmDistComparatorNoPriorInsulin <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparatorNoPriorInsulin[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDaysNoPriorInsulin[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparatorNoPriorInsulin[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMeanNoPriorInsulin[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSdNoPriorInsulin[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMinNoPriorInsulin[idx] <- bmDistComparatorNoPriorInsulin[1] + chunk$bmTarComparatorMedianNoPriorInsulin[idx] <- bmDistComparatorNoPriorInsulin[2] + chunk$bmTarComparatorMaxNoPriorInsulin[idx] <- bmDistComparatorNoPriorInsulin[3] + + subgroupName = ""PriorDkaIpEr"" + subgroupValue = 1 + bmDistTargetPriorDkaIpEr <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreatedPriorDkaIpEr[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDaysPriorDkaIpEr[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreatedPriorDkaIpEr[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMeanPriorDkaIpEr[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSdPriorDkaIpEr[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMinPriorDkaIpEr[idx] <- bmDistTargetPriorDkaIpEr[1] + chunk$bmTarTargetMedianPriorDkaIpEr[idx] <- bmDistTargetPriorDkaIpEr[2] + chunk$bmTarTargetMaxPriorDkaIpEr[idx] <- bmDistTargetPriorDkaIpEr[3] + bmDistComparatorPriorDkaIpEr <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparatorPriorDkaIpEr[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDaysPriorDkaIpEr[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparatorPriorDkaIpEr[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMeanPriorDkaIpEr[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSdPriorDkaIpEr[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMinPriorDkaIpEr[idx] <- bmDistComparatorPriorDkaIpEr[1] + chunk$bmTarComparatorMedianPriorDkaIpEr[idx] <- bmDistComparatorPriorDkaIpEr[2] + chunk$bmTarComparatorMaxPriorDkaIpEr[idx] <- bmDistComparatorPriorDkaIpEr[3] + + subgroupName = ""PriorDkaIpEr"" + subgroupValue = 0 + bmDistTargetNoPriorDkaIpEr <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreatedNoPriorDkaIpEr[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDaysNoPriorDkaIpEr[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreatedNoPriorDkaIpEr[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMeanNoPriorDkaIpEr[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSdNoPriorDkaIpEr[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMinNoPriorDkaIpEr[idx] <- bmDistTargetNoPriorDkaIpEr[1] + chunk$bmTarTargetMedianNoPriorDkaIpEr[idx] <- bmDistTargetNoPriorDkaIpEr[2] + chunk$bmTarTargetMaxNoPriorDkaIpEr[idx] <- bmDistTargetNoPriorDkaIpEr[3] + bmDistComparatorNoPriorDkaIpEr <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparatorNoPriorDkaIpEr[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDaysNoPriorDkaIpEr[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparatorNoPriorDkaIpEr[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMeanNoPriorDkaIpEr[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSdNoPriorDkaIpEr[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMinNoPriorDkaIpEr[idx] <- bmDistComparatorNoPriorDkaIpEr[1] + chunk$bmTarComparatorMedianNoPriorDkaIpEr[idx] <- bmDistComparatorNoPriorDkaIpEr[2] + chunk$bmTarComparatorMaxNoPriorDkaIpEr[idx] <- bmDistComparatorNoPriorDkaIpEr[3] + + subgroupName = ""Age10_19"" + subgroupValue = 1 + bmDistTarget1019 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreated1019[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDays1019[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreated1019[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMean1019[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSd1019[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMin1019[idx] <- bmDistTarget1019[1] + chunk$bmTarTargetMedian1019[idx] <- bmDistTarget1019[2] + chunk$bmTarTargetMax1019[idx] <- bmDistTarget1019[3] + bmDistComparator1019 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparator1019[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDays1019[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparator1019[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMean1019[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSd1019[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMin1019[idx] <- bmDistComparator1019[1] + chunk$bmTarComparatorMedian1019[idx] <- bmDistComparator1019[2] + chunk$bmTarComparatorMax1019[idx] <- bmDistComparator1019[3] + + subgroupName = ""Age20_29"" + subgroupValue = 1 + bmDistTarget2029 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreated2029[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDays2029[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreated2029[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMean2029[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSd2029[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMin2029[idx] <- bmDistTarget2029[1] + chunk$bmTarTargetMedian2029[idx] <- bmDistTarget2029[2] + chunk$bmTarTargetMax2029[idx] <- bmDistTarget2029[3] + bmDistComparator2029 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparator2029[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDays2029[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparator2029[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMean2029[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSd2029[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMin2029[idx] <- bmDistComparator2029[1] + chunk$bmTarComparatorMedian2029[idx] <- bmDistComparator2029[2] + chunk$bmTarComparatorMax2029[idx] <- bmDistComparator2029[3] + + subgroupName = ""Age30_39"" + subgroupValue = 1 + bmDistTarget3039 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreated3039[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDays3039[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreated3039[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMean3039[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSd3039[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMin3039[idx] <- bmDistTarget3039[1] + chunk$bmTarTargetMedian3039[idx] <- bmDistTarget3039[2] + chunk$bmTarTargetMax3039[idx] <- bmDistTarget3039[3] + bmDistComparator3039 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparator3039[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDays3039[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparator3039[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMean3039[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSd3039[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMin3039[idx] <- bmDistComparator3039[1] + chunk$bmTarComparatorMedian3039[idx] <- bmDistComparator3039[2] + chunk$bmTarComparatorMax3039[idx] <- bmDistComparator3039[3] + + subgroupName = ""Age40_49"" + subgroupValue = 1 + bmDistTarget4049 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreated4049[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDays4049[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreated4049[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMean4049[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSd4049[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMin4049[idx] <- bmDistTarget4049[1] + chunk$bmTarTargetMedian4049[idx] <- bmDistTarget4049[2] + chunk$bmTarTargetMax4049[idx] <- bmDistTarget4049[3] + bmDistComparator4049 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparator4049[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDays4049[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparator4049[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMean4049[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSd4049[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMin4049[idx] <- bmDistComparator4049[1] + chunk$bmTarComparatorMedian4049[idx] <- bmDistComparator4049[2] + chunk$bmTarComparatorMax4049[idx] <- bmDistComparator4049[3] + + subgroupName = ""Age50_59"" + subgroupValue = 1 + bmDistTarget5059 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreated5059[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDays5059[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreated5059[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMean5059[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSd5059[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMin5059[idx] <- bmDistTarget5059[1] + chunk$bmTarTargetMedian5059[idx] <- bmDistTarget5059[2] + chunk$bmTarTargetMax5059[idx] <- bmDistTarget5059[3] + bmDistComparator5059 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparator5059[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDays5059[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparator5059[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMean5059[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSd5059[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMin5059[idx] <- bmDistComparator5059[1] + chunk$bmTarComparatorMedian5059[idx] <- bmDistComparator5059[2] + chunk$bmTarComparatorMax5059[idx] <- bmDistComparator5059[3] + + subgroupName = ""Age60_69"" + subgroupValue = 1 + bmDistTarget6069 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreated6069[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDays6069[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreated6069[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMean6069[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSd6069[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMin6069[idx] <- bmDistTarget6069[1] + chunk$bmTarTargetMedian6069[idx] <- bmDistTarget6069[2] + chunk$bmTarTargetMax6069[idx] <- bmDistTarget6069[3] + bmDistComparator6069 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparator6069[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDays6069[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparator6069[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMean6069[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSd6069[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMin6069[idx] <- bmDistComparator6069[1] + chunk$bmTarComparatorMedian6069[idx] <- bmDistComparator6069[2] + chunk$bmTarComparatorMax6069[idx] <- bmDistComparator6069[3] + + subgroupName = ""Age70_79"" + subgroupValue = 1 + bmDistTarget7079 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreated7079[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDays7079[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreated7079[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMean7079[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSd7079[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMin7079[idx] <- bmDistTarget7079[1] + chunk$bmTarTargetMedian7079[idx] <- bmDistTarget7079[2] + chunk$bmTarTargetMax7079[idx] <- bmDistTarget7079[3] + bmDistComparator7079 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparator7079[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDays7079[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparator7079[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMean7079[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSd7079[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMin7079[idx] <- bmDistComparator7079[1] + chunk$bmTarComparatorMedian7079[idx] <- bmDistComparator7079[2] + chunk$bmTarComparatorMax7079[idx] <- bmDistComparator7079[3] + + subgroupName = ""Age80_89"" + subgroupValue = 1 + bmDistTarget8089 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreated8089[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDays8089[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreated8089[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMean8089[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSd8089[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMin8089[idx] <- bmDistTarget8089[1] + chunk$bmTarTargetMedian8089[idx] <- bmDistTarget8089[2] + chunk$bmTarTargetMax8089[idx] <- bmDistTarget8089[3] + bmDistComparator8089 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparator8089[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDays8089[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparator8089[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMean8089[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSd8089[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMin8089[idx] <- bmDistComparator8089[1] + chunk$bmTarComparatorMedian8089[idx] <- bmDistComparator8089[2] + chunk$bmTarComparatorMax8089[idx] <- bmDistComparator8089[3] + + subgroupName = ""Age90_99"" + subgroupValue = 1 + bmDistTarget9099 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreated9099[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDays9099[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreated9099[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMean9099[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSd9099[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMin9099[idx] <- bmDistTarget9099[1] + chunk$bmTarTargetMedian9099[idx] <- bmDistTarget9099[2] + chunk$bmTarTargetMax9099[idx] <- bmDistTarget9099[3] + bmDistComparator9099 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparator9099[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDays9099[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparator9099[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMean9099[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSd9099[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMin9099[idx] <- bmDistComparator9099[1] + chunk$bmTarComparatorMedian9099[idx] <- bmDistComparator9099[2] + chunk$bmTarComparatorMax9099[idx] <- bmDistComparator9099[3] + + subgroupName = ""Age100_109"" + subgroupValue = 1 + bmDistTarget100109 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreated100109[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDays100109[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreated100109[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMean100109[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSd100109[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMin100109[idx] <- bmDistTarget100109[1] + chunk$bmTarTargetMedian100109[idx] <- bmDistTarget100109[2] + chunk$bmTarTargetMax100109[idx] <- bmDistTarget100109[3] + bmDistComparator100109 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparator100109[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDays100109[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparator100109[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMean100109[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSd100109[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMin100109[idx] <- bmDistComparator100109[1] + chunk$bmTarComparatorMedian100109[idx] <- bmDistComparator100109[2] + chunk$bmTarComparatorMax100109[idx] <- bmDistComparator100109[3] + } + } + OhdsiRTools::logDebug(""Finished chunk with "", nrow(chunk), "" rows"") + return(chunk) + } + + cluster <- OhdsiRTools::makeCluster(min(maxCores, 10)) + comparison <- paste(analysisSummary$targetId, analysisSummary$comparatorId) + chunks <- split(analysisSummary, comparison) + analysisSummaries <- OhdsiRTools::clusterApply(cluster = cluster, + x = chunks, + fun = runTc, + tcosOfInterest = tcosOfInterest, + reference = reference) + OhdsiRTools::stopCluster(cluster) + analysisSummary <- do.call(rbind, analysisSummaries) + fileName <- file.path(irSensitivityDataFolder, paste0(""irSensitivityData_"", databaseName,"".rds"")) + saveRDS(analysisSummary, fileName) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/R/PrepareResultsForAnalysis.R",".R","59739","719","#' @export +prepareResultsForAnalysis <- function(outputFolder, + databaseName, + maxCores) { + packageName <- ""sglt2iDka"" + cmOutputFolder <- file.path(outputFolder, ""cmOutput"") + resultsFolder <- file.path(outputFolder, ""results"") + if (!file.exists(resultsFolder)) + dir.create(resultsFolder) + shinyDataFolder <- file.path(resultsFolder, ""shinyData"") + if (!file.exists(shinyDataFolder)) + dir.create(shinyDataFolder) + balanceDataFolder <- file.path(resultsFolder, ""balance"") + if (!file.exists(balanceDataFolder)) + dir.create(balanceDataFolder) + + # TCOs of interest + tcosAnalyses <- read.csv(system.file(""settings"", ""tcoAnalysisVariants.csv"", package = packageName), stringsAsFactors = FALSE) + tcosOfInterest <- unique(tcosAnalyses[, c(""targetCohortId"", ""targetDrugName"", ""targetCohortName"", ""comparatorCohortId"", ""comparatorDrugName"", ""comparatorCohortName"", + ""outcomeCohortId"", ""outcomeCohortName"")]) + names(tcosOfInterest) <- c(""targetId"", ""targetDrugName"", ""targetName"", ""comparatorId"", ""comparatorDrugName"", ""comparatorName"", + ""outcomeId"", ""outcomeName"") + negativeControls <- read.csv(system.file(""settings"", ""negativeControlOutcomeCohorts.csv"", package = ""sglt2iDka""), stringsAsFactors = FALSE) + names(negativeControls) <- c(""outcomeId"", ""outcomeName"") + reference <- readRDS(file.path(cmOutputFolder, ""outcomeModelReference.rds"")) + analysisSummary <- CohortMethod::summarizeAnalyses(reference) + analysisSummary <- sglt2iDka::addCohortNames(analysisSummary, dose = FALSE, ""outcomeId"", ""outcomeName"") + analysisSummary <- sglt2iDka::addCohortNames(analysisSummary, dose = FALSE, ""comparatorId"", ""comparatorName"") + analysisSummary <- sglt2iDka::addCohortNames(analysisSummary, dose = FALSE, ""targetId"", ""targetName"") + cmAnalysisList <- CohortMethod::loadCmAnalysisList(system.file(""settings"", ""cmAnalysisList.json"", package = packageName)) + analyses <- data.frame(analysisId = unique(reference$analysisId), + analysisDescription = """", + stringsAsFactors = FALSE) + for (i in 1:length(cmAnalysisList)) { + analyses$analysisDescription[analyses$analysisId == cmAnalysisList[[i]]$analysisId] <- cmAnalysisList[[i]]$description + } + analysisSummary <- merge(analysisSummary, analyses) + analysisSummary <- analysisSummary[, c(1,20,2:19)] + analysisSummary$type <- ""Outcome of interest"" + analysisSummary$type[analysisSummary$outcomeId %in% negativeControls$outcomeId] <- ""Negative control"" + analysisSummary$database <- databaseName + + #for dev + # comparison <- paste(analysisSummary$targetId, analysisSummary$comparatorId) + # chunks <- split(analysisSummary, comparison) + # chunk <- chunks[[17]] + #for dev + + runTc <- function(chunk, + tcosOfInterest, + negativeControls, + shinyDataFolder, + balanceDataFolder, + outputFolder, + databaseName, + reference) { + ffbase::load.ffdf(file.path(outputFolder, ""multiTherapyData"")) + tcsOfInterest <- unique(tcosOfInterest[, c(""targetId"", ""comparatorId"")]) + targetId <- chunk$targetId[1] + comparatorId <- chunk$comparatorId[1] + outcomeIds <- unique(tcosOfInterest$outcomeId) + outcomeNames <- unique(tcosOfInterest$outcomeName) + OhdsiRTools::logTrace(""Preparing results for target ID "", targetId, "", comparator ID"", comparatorId) + + for (analysisId in unique(reference$analysisId)) { + # analysisId=1 + + OhdsiRTools::logTrace(""Analysis ID "", analysisId) + negControlSubset <- chunk[chunk$targetId == targetId & + chunk$comparatorId == comparatorId & + chunk$outcomeId %in% negativeControls$outcomeId & + chunk$analysisId == analysisId, ] + + validNcs <- sum(!is.na(negControlSubset$seLogRr)) + + if (validNcs >= 5) { + fileName <- file.path(shinyDataFolder, paste0(""null_a"", analysisId, + ""_t"", targetId, + ""_c"", comparatorId, + ""_"", databaseName, + "".rds"")) + if (file.exists(fileName)) { + null <- readRDS(fileName) + } else { + null <- EmpiricalCalibration::fitMcmcNull(negControlSubset$logRr, negControlSubset$seLogRr) + saveRDS(null, fileName) + } + + idx <- chunk$targetId == targetId & chunk$comparatorId == comparatorId & chunk$analysisId == analysisId + calibratedP <- EmpiricalCalibration::calibrateP(null = null, + logRr = chunk$logRr[idx], + seLogRr = chunk$seLogRr[idx]) + chunk$calP[idx] <- calibratedP$p + chunk$calP_lb95ci[idx] <- calibratedP$lb95ci + chunk$calP_ub95ci[idx] <- calibratedP$ub95ci + mcmc <- attr(null, ""mcmc"") + chunk$null_mean <- mean(mcmc$chain[,1]) + chunk$null_sd <- 1/sqrt(mean(mcmc$chain[,2])) + } + + for (outcomeId in outcomeIds) { + # outcomeId=200 + + OhdsiRTools::logTrace(""Outcome ID "", outcomeId) + outcomeName <- outcomeNames[outcomeIds == outcomeId] + idx <- chunk$analysisId == analysisId & + chunk$targetId == targetId & + chunk$comparatorId == comparatorId & + chunk$outcomeId == outcomeId + + # Compute MDRR + strataFile <- reference$strataFile[reference$analysisId == analysisId & + reference$targetId == targetId & + reference$comparatorId == comparatorId & + reference$outcomeId == outcomeId] + population <- readRDS(strataFile) + mdrr <- CohortMethod::computeMdrr(population, alpha = 0.05, power = 0.8, twoSided = TRUE, modelType = ""cox"") + chunk$mdrr[idx] <- mdrr$mdrr + chunk$outcomeName[idx] <- outcomeName + + # Compute time-at-risk distribtion stats + distTarget <- quantile(population$timeAtRisk[population$treatment == 1], c(0, 0.5, 1)) + distComparator <- quantile(population$timeAtRisk[population$treatment == 0], c(0, 0.5, 1)) + chunk$tarTargetMean[idx] <- mean(population$timeAtRisk[population$treatment == 1]) + chunk$tarTargetSd[idx] <- sd(population$timeAtRisk[population$treatment == 1]) + chunk$tarTargetMin[idx] <- distTarget[1] + chunk$tarTargetMedian[idx] <- distTarget[2] + chunk$tarTargetMax[idx] <- distTarget[3] + chunk$tarComparatorMean[idx] <- mean(population$timeAtRisk[population$treatment == 0]) + chunk$tarComparatorSd[idx] <- sd(population$timeAtRisk[population$treatment == 0]) + chunk$tarComparatorMin[idx] <- distComparator[1] + chunk$tarComparatorMedian[idx] <- distComparator[2] + chunk$tarComparatorMax[idx] <- distComparator[3] + + # Compute covariate balance + refRow <- reference[reference$analysisId == analysisId & + reference$targetId == targetId & + reference$comparatorId == comparatorId & + reference$outcomeId == outcomeId, ] + psAfterMatching <- readRDS(refRow$strataFile) + cmData <- CohortMethod::loadCohortMethodData(refRow$cohortMethodDataFolder) + fileName <- file.path(balanceDataFolder, paste0(""bal_a"", analysisId, + ""_t"", targetId, + ""_c"", comparatorId, + ""_o"", outcomeId, + ""_"", databaseName, + "".rds"")) + if (!file.exists(fileName)) { + balance <- CohortMethod::computeCovariateBalance(psAfterMatching, cmData) + saveRDS(balance, fileName) + } + + # Compute balance for multitherapy at index covariates + fileName <- file.path(shinyDataFolder, paste0(""multiTherBal_a"", analysisId, + ""_t"", targetId, + ""_c"", comparatorId, + ""_o"", outcomeId, + ""_"", databaseName,"".rds"")) + if (!file.exists(fileName)) { + dummyCmData <- cmData + # idxff <- !is.na(ffbase::ffmatch(covariates$cohortDefinitionId, ff::as.ff(c(11,21)))) + # covarSubset <- covariates[ffbase::ffwhich(idxff, idxff == TRUE), ] + cmData$cohorts$cohortDefinitionId <- ifelse(cmData$cohorts$treatment == 1, targetId, comparatorId) + dummyCmData$covariates <- merge(covariates, + ff::as.ffdf(cmData$cohorts[, c(""rowId"", ""subjectId"", ""cohortDefinitionId"", ""cohortStartDate"")])) + dummyCmData$covariateRef <- covariateRef + balance <- CohortMethod::computeCovariateBalance(psAfterMatching, dummyCmData) + balance$conceptId <- NULL + balance$beforeMatchingSd <- NULL + balance$afterMatchingSd <- NULL + balance$beforeMatchingSumTreated <- NULL + balance$beforeMatchingSumComparator <- NULL + balance$afterMatchingSumTreated <- NULL + balance$afterMatchingSumComparator <- NULL + if (nrow(balance) > 0) + balance$analysisId <- as.integer(balance$analysisId) + saveRDS(balance, fileName) + } + + # Create KM plot + fileName <- file.path(shinyDataFolder, paste0(""km_a"", analysisId, + ""_t"", targetId, + ""_c"", comparatorId, + ""_o"", outcomeId, + ""_"", databaseName, + "".rds"")) + # if (!file.exists(fileName)) { + plot <- sglt2iDka::plotKaplanMeier(psAfterMatching, + targetLabel = sub(""-90"", """", chunk$targetName[chunk$targetId == targetId][1]), + comparatorLabel = sub(""-90"", """", chunk$comparatorName[chunk$comparatorId == comparatorId][1])) + saveRDS(plot, fileName) + # } + + # Add cohort sizes before matching/stratification + chunk$treatedBefore[idx] <- sum(cmData$cohorts$treatment == 1) + chunk$comparatorBefore[idx] <- sum(cmData$cohorts$treatment == 0) + + # before matching IR data + # covarRef <- as.data.frame(cmData$covariateRef) + # covarRef <- covarRef[order(covarRef$covariateId), ] + # covarRef[covarRef$analysisId==3, 1:2] + covariatesForStrat <- as.data.frame(cmData$covariates) + covariatesForStrat <- covariatesForStrat[covariatesForStrat$covariateId %in% c(8507001, 1998, 2998, 200999, 201999, # intentionally drop 8532001 as redundant + 2003, 3003, 4003, 5003, 6003, 7003, 8003, 9003, 10003, 11003, 12003, 13003, 14003, 15003, 16003, 17003, 18003, 19003, 20003, 21003), ] + covariatesForStrat <- reshape(covariatesForStrat, idvar = ""rowId"", timevar = ""covariateId"", direction = ""wide"") + names(covariatesForStrat)[names(covariatesForStrat) == ""covariateValue.8507001""] <- ""Male"" + names(covariatesForStrat)[names(covariatesForStrat) == ""covariateValue.1998""] <- ""PriorInsulin"" + names(covariatesForStrat)[names(covariatesForStrat) == ""covariateValue.2998""] <- ""PriorAha"" + names(covariatesForStrat)[names(covariatesForStrat) == ""covariateValue.200999""] <- ""PriorDkaIpEr"" + names(covariatesForStrat)[names(covariatesForStrat) == ""covariateValue.201999""] <- ""PriorDkaIp"" + if (is.null(covariatesForStrat$covariateValue.2003)) covariatesForStrat$Age10_14 <- 0 else covariatesForStrat$Age10_14[covariatesForStrat$covariateValue.2003 == 1] <- 1 + if (is.null(covariatesForStrat$covariateValue.3003)) covariatesForStrat$Age15_19 <- 0 else covariatesForStrat$Age15_19[covariatesForStrat$covariateValue.3003 == 1] <- 1 + if (is.null(covariatesForStrat$covariateValue.4003)) covariatesForStrat$Age20_24 <- 0 else covariatesForStrat$Age20_24[covariatesForStrat$covariateValue.4003 == 1] <- 1 + if (is.null(covariatesForStrat$covariateValue.5003)) covariatesForStrat$Age25_29 <- 0 else covariatesForStrat$Age25_29[covariatesForStrat$covariateValue.5003 == 1] <- 1 + if (is.null(covariatesForStrat$covariateValue.6003)) covariatesForStrat$Age30_34 <- 0 else covariatesForStrat$Age30_34[covariatesForStrat$covariateValue.6003 == 1] <- 1 + if (is.null(covariatesForStrat$covariateValue.7003)) covariatesForStrat$Age35_39 <- 0 else covariatesForStrat$Age35_39[covariatesForStrat$covariateValue.7003 == 1] <- 1 + if (is.null(covariatesForStrat$covariateValue.8003)) covariatesForStrat$Age40_44 <- 0 else covariatesForStrat$Age40_44[covariatesForStrat$covariateValue.8003 == 1] <- 1 + if (is.null(covariatesForStrat$covariateValue.9003)) covariatesForStrat$Age45_49 <- 0 else covariatesForStrat$Age45_49[covariatesForStrat$covariateValue.9003 == 1] <- 1 + if (is.null(covariatesForStrat$covariateValue.10003)) covariatesForStrat$Age50_54 <- 0 else covariatesForStrat$Age50_54[covariatesForStrat$covariateValue.10003 == 1] <- 1 + if (is.null(covariatesForStrat$covariateValue.11003)) covariatesForStrat$Age55_59 <- 0 else covariatesForStrat$Age55_59[covariatesForStrat$covariateValue.11003 == 1] <- 1 + if (is.null(covariatesForStrat$covariateValue.12003)) covariatesForStrat$Age60_64 <- 0 else covariatesForStrat$Age60_64[covariatesForStrat$covariateValue.12003 == 1] <- 1 + if (is.null(covariatesForStrat$covariateValue.13003)) covariatesForStrat$Age65_69 <- 0 else covariatesForStrat$Age65_69[covariatesForStrat$covariateValue.13003 == 1] <- 1 + if (is.null(covariatesForStrat$covariateValue.14003)) covariatesForStrat$Age70_74 <- 0 else covariatesForStrat$Age70_74[covariatesForStrat$covariateValue.14003 == 1] <- 1 + if (is.null(covariatesForStrat$covariateValue.15003)) covariatesForStrat$Age75_79 <- 0 else covariatesForStrat$Age75_79[covariatesForStrat$covariateValue.15003 == 1] <- 1 + if (is.null(covariatesForStrat$covariateValue.16003)) covariatesForStrat$Age80_84 <- 0 else covariatesForStrat$Age80_84[covariatesForStrat$covariateValue.16003 == 1] <- 1 + if (is.null(covariatesForStrat$covariateValue.17003)) covariatesForStrat$Age85_89 <- 0 else covariatesForStrat$Age85_89[covariatesForStrat$covariateValue.17003 == 1] <- 1 + if (is.null(covariatesForStrat$covariateValue.18003)) covariatesForStrat$Age90_94 <- 0 else covariatesForStrat$Age90_94[covariatesForStrat$covariateValue.18003 == 1] <- 1 + if (is.null(covariatesForStrat$covariateValue.19003)) covariatesForStrat$Age95_99 <- 0 else covariatesForStrat$Age95_99[covariatesForStrat$covariateValue.19003 == 1] <- 1 + if (is.null(covariatesForStrat$covariateValue.20003)) covariatesForStrat$Age100_104 <- 0 else covariatesForStrat$Age100_104[covariatesForStrat$covariateValue.20003 == 1] <- 1 + if (is.null(covariatesForStrat$covariateValue.21003)) covariatesForStrat$Age105_109 <- 0 else covariatesForStrat$Age105_109[covariatesForStrat$covariateValue.21003 == 1] <- 1 + covariatesForStrat$Age10_19[covariatesForStrat$Age10_14 == 1 | covariatesForStrat$Age15_19 == 1] <- 1 + covariatesForStrat$Age20_29[covariatesForStrat$Age20_24 == 1 | covariatesForStrat$Age25_29 == 1] <- 1 + covariatesForStrat$Age30_39[covariatesForStrat$Age30_34 == 1 | covariatesForStrat$Age35_39 == 1] <- 1 + covariatesForStrat$Age40_49[covariatesForStrat$Age40_44 == 1 | covariatesForStrat$Age45_49 == 1] <- 1 + covariatesForStrat$Age50_59[covariatesForStrat$Age50_54 == 1 | covariatesForStrat$Age55_59 == 1] <- 1 + covariatesForStrat$Age60_69[covariatesForStrat$Age60_64 == 1 | covariatesForStrat$Age65_69 == 1] <- 1 + covariatesForStrat$Age70_79[covariatesForStrat$Age70_74 == 1 | covariatesForStrat$Age75_79 == 1] <- 1 + covariatesForStrat$Age80_89[covariatesForStrat$Age80_84 == 1 | covariatesForStrat$Age85_89 == 1] <- 1 + covariatesForStrat$Age90_99[covariatesForStrat$Age90_94 == 1 | covariatesForStrat$Age95_99 == 1] <- 1 + covariatesForStrat$Age100_109[covariatesForStrat$Age100_104 == 1 | covariatesForStrat$Age105_109 == 1] <- 1 + + studyPop <- readRDS(refRow$studyPopFile) + studyPop <- merge(studyPop, covariatesForStrat, by = ""rowId"", all.x = TRUE) + studyPop[is.na(studyPop)] <- 0 + + studyPop$outcomeCount[studyPop$outcomeCount != 0] <- 1 + studyPop$timeAtRisk <- studyPop$survivalTime + + # overall + bmDistTarget <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1], c(0, 0.5, 1)) + chunk$bmTreated[idx] <- sum(studyPop$treatment == 1) + chunk$bmTreatedDays[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1]) + chunk$bmEventsTreated[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1]) + chunk$bmTarTargetMean[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1]) + chunk$bmTarTargetSd[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1]) + chunk$bmTarTargetMin[idx] <- bmDistTarget[1] + chunk$bmTarTargetMedian[idx] <- bmDistTarget[2] + chunk$bmTarTargetMax[idx] <- bmDistTarget[3] + + bmDistComparator <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0], c(0, 0.5, 1)) + chunk$bmComparator[idx] <- sum(studyPop$treatment == 0) + chunk$bmComparatorDays[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0]) + chunk$bmEventsComparator[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0]) + chunk$bmTarComparatorMean[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0]) + chunk$bmTarComparatorSd[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0]) + chunk$bmTarComparatorMin[idx] <- bmDistComparator[1] + chunk$bmTarComparatorMedian[idx] <- bmDistComparator[2] + chunk$bmTarComparatorMax[idx] <- bmDistComparator[3] + + # getBmIrStats <- function(chunk, + # subgroupName, + # subgroupValue, + # subgroupLabel) { + # bmDistTargetSubgroup <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + # chunk$bmTreatedSubgroup[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + # chunk$bmTreatedDaysSubgroup[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + # chunk$bmEventsTreatedSubgroup[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + # chunk$bmTarTargetMeanSubgroup[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + # chunk$bmTarTargetSdSubgroup[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + # chunk$bmTarTargetMinSubgroup[idx] <- bmDistTargetSubgroup[1] + # chunk$bmTarTargetMedianSubgroup[idx] <- bmDistTargetSubgroup[2] + # chunk$bmTarTargetMaxSubgroup[idx] <- bmDistTargetSubgroup[3] + # bmDistComparatorSubgroup <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + # chunk$bmComparatorSubgroup[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + # chunk$bmComparatorDaysSubgroup[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + # chunk$bmEventsComparatorSubgroup[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + # chunk$bmTarComparatorMeanSubgroup[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + # chunk$bmTarComparatorSdSubgroup[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + # chunk$bmTarComparatorMinSubgroup[idx] <- bmDistComparatorSubgroup[1] + # chunk$bmTarComparatorMedianSubgroup[idx] <- bmDistComparatorSubgroup[2] + # chunk$bmTarComparatorMaxSubgroup[idx] <- bmDistComparatorSubgroup[3] + # colnames(chunk)[seq(length(chunk)-15, length(chunk))] <- sub(pattern = ""Subgroup"", replacement = subgroupLabel, x = colnames(chunk)[seq(length(chunk)-15, length(chunk))]) + # return(chunk) + # } + # + # chunk <- getBmIrStats(""Male"", 1, ""Male"") + # chunk <- getBmIrStats(""Male"", 0, ""Female"") + # chunk <- getBmIrStats(""PriorInsulin"", 1, ""PriorInsulin"") + # chunk <- getBmIrStats(""PriorInsulin"", 0, ""NoPriorInsulin"") + # chunk <- getBmIrStats(""PriorDkaIpEr"", 1, ""PriorDkaIpEr"") + # chunk <- getBmIrStats(""PriorDkaIpEr"", 0, ""NoPriorDkaIpEr"") + + subgroupName = ""Male"" + subgroupValue = 1 + bmDistTargetMale <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreatedMale[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDaysMale[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreatedMale[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMeanMale[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSdMale[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMinMale[idx] <- bmDistTargetMale[1] + chunk$bmTarTargetMedianMale[idx] <- bmDistTargetMale[2] + chunk$bmTarTargetMaxMale[idx] <- bmDistTargetMale[3] + bmDistComparatorMale <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparatorMale[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDaysMale[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparatorMale[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMeanMale[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSdMale[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMinMale[idx] <- bmDistComparatorMale[1] + chunk$bmTarComparatorMedianMale[idx] <- bmDistComparatorMale[2] + chunk$bmTarComparatorMaxMale[idx] <- bmDistComparatorMale[3] + + subgroupName = ""Male"" + subgroupValue = 0 + bmDistTargetFemale <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreatedFemale[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDaysFemale[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreatedFemale[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMeanFemale[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSdFemale[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMinFemale[idx] <- bmDistTargetFemale[1] + chunk$bmTarTargetMedianFemale[idx] <- bmDistTargetFemale[2] + chunk$bmTarTargetMaxFemale[idx] <- bmDistTargetFemale[3] + bmDistComparatorFemale <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparatorFemale[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDaysFemale[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparatorFemale[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMeanFemale[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSdFemale[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMinFemale[idx] <- bmDistComparatorFemale[1] + chunk$bmTarComparatorMedianFemale[idx] <- bmDistComparatorFemale[2] + chunk$bmTarComparatorMaxFemale[idx] <- bmDistComparatorFemale[3] + + subgroupName = ""PriorInsulin"" + subgroupValue = 1 + bmDistTargetPriorInsulin <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreatedPriorInsulin[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDaysPriorInsulin[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreatedPriorInsulin[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMeanPriorInsulin[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSdPriorInsulin[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMinPriorInsulin[idx] <- bmDistTargetPriorInsulin[1] + chunk$bmTarTargetMedianPriorInsulin[idx] <- bmDistTargetPriorInsulin[2] + chunk$bmTarTargetMaxPriorInsulin[idx] <- bmDistTargetPriorInsulin[3] + bmDistComparatorPriorInsulin <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparatorPriorInsulin[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDaysPriorInsulin[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparatorPriorInsulin[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMeanPriorInsulin[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSdPriorInsulin[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMinPriorInsulin[idx] <- bmDistComparatorPriorInsulin[1] + chunk$bmTarComparatorMedianPriorInsulin[idx] <- bmDistComparatorPriorInsulin[2] + chunk$bmTarComparatorMaxPriorInsulin[idx] <- bmDistComparatorPriorInsulin[3] + + subgroupName = ""PriorInsulin"" + subgroupValue = 0 + bmDistTargetNoPriorInsulin <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreatedNoPriorInsulin[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDaysNoPriorInsulin[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreatedNoPriorInsulin[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMeanNoPriorInsulin[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSdNoPriorInsulin[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMinNoPriorInsulin[idx] <- bmDistTargetNoPriorInsulin[1] + chunk$bmTarTargetMedianNoPriorInsulin[idx] <- bmDistTargetNoPriorInsulin[2] + chunk$bmTarTargetMaxNoPriorInsulin[idx] <- bmDistTargetNoPriorInsulin[3] + bmDistComparatorNoPriorInsulin <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparatorNoPriorInsulin[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDaysNoPriorInsulin[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparatorNoPriorInsulin[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMeanNoPriorInsulin[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSdNoPriorInsulin[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMinNoPriorInsulin[idx] <- bmDistComparatorNoPriorInsulin[1] + chunk$bmTarComparatorMedianNoPriorInsulin[idx] <- bmDistComparatorNoPriorInsulin[2] + chunk$bmTarComparatorMaxNoPriorInsulin[idx] <- bmDistComparatorNoPriorInsulin[3] + + subgroupName = ""PriorDkaIpEr"" + subgroupValue = 1 + bmDistTargetPriorDkaIpEr <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreatedPriorDkaIpEr[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDaysPriorDkaIpEr[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreatedPriorDkaIpEr[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMeanPriorDkaIpEr[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSdPriorDkaIpEr[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMinPriorDkaIpEr[idx] <- bmDistTargetPriorDkaIpEr[1] + chunk$bmTarTargetMedianPriorDkaIpEr[idx] <- bmDistTargetPriorDkaIpEr[2] + chunk$bmTarTargetMaxPriorDkaIpEr[idx] <- bmDistTargetPriorDkaIpEr[3] + bmDistComparatorPriorDkaIpEr <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparatorPriorDkaIpEr[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDaysPriorDkaIpEr[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparatorPriorDkaIpEr[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMeanPriorDkaIpEr[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSdPriorDkaIpEr[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMinPriorDkaIpEr[idx] <- bmDistComparatorPriorDkaIpEr[1] + chunk$bmTarComparatorMedianPriorDkaIpEr[idx] <- bmDistComparatorPriorDkaIpEr[2] + chunk$bmTarComparatorMaxPriorDkaIpEr[idx] <- bmDistComparatorPriorDkaIpEr[3] + + subgroupName = ""PriorDkaIpEr"" + subgroupValue = 0 + bmDistTargetNoPriorDkaIpEr <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreatedNoPriorDkaIpEr[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDaysNoPriorDkaIpEr[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreatedNoPriorDkaIpEr[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMeanNoPriorDkaIpEr[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSdNoPriorDkaIpEr[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMinNoPriorDkaIpEr[idx] <- bmDistTargetNoPriorDkaIpEr[1] + chunk$bmTarTargetMedianNoPriorDkaIpEr[idx] <- bmDistTargetNoPriorDkaIpEr[2] + chunk$bmTarTargetMaxNoPriorDkaIpEr[idx] <- bmDistTargetNoPriorDkaIpEr[3] + bmDistComparatorNoPriorDkaIpEr <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparatorNoPriorDkaIpEr[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDaysNoPriorDkaIpEr[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparatorNoPriorDkaIpEr[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMeanNoPriorDkaIpEr[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSdNoPriorDkaIpEr[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMinNoPriorDkaIpEr[idx] <- bmDistComparatorNoPriorDkaIpEr[1] + chunk$bmTarComparatorMedianNoPriorDkaIpEr[idx] <- bmDistComparatorNoPriorDkaIpEr[2] + chunk$bmTarComparatorMaxNoPriorDkaIpEr[idx] <- bmDistComparatorNoPriorDkaIpEr[3] + + subgroupName = ""Age10_19"" + subgroupValue = 1 + bmDistTarget1019 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreated1019[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDays1019[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreated1019[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMean1019[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSd1019[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMin1019[idx] <- bmDistTarget1019[1] + chunk$bmTarTargetMedian1019[idx] <- bmDistTarget1019[2] + chunk$bmTarTargetMax1019[idx] <- bmDistTarget1019[3] + bmDistComparator1019 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparator1019[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDays1019[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparator1019[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMean1019[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSd1019[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMin1019[idx] <- bmDistComparator1019[1] + chunk$bmTarComparatorMedian1019[idx] <- bmDistComparator1019[2] + chunk$bmTarComparatorMax1019[idx] <- bmDistComparator1019[3] + + subgroupName = ""Age20_29"" + subgroupValue = 1 + bmDistTarget2029 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreated2029[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDays2029[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreated2029[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMean2029[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSd2029[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMin2029[idx] <- bmDistTarget2029[1] + chunk$bmTarTargetMedian2029[idx] <- bmDistTarget2029[2] + chunk$bmTarTargetMax2029[idx] <- bmDistTarget2029[3] + bmDistComparator2029 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparator2029[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDays2029[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparator2029[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMean2029[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSd2029[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMin2029[idx] <- bmDistComparator2029[1] + chunk$bmTarComparatorMedian2029[idx] <- bmDistComparator2029[2] + chunk$bmTarComparatorMax2029[idx] <- bmDistComparator2029[3] + + subgroupName = ""Age30_39"" + subgroupValue = 1 + bmDistTarget3039 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreated3039[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDays3039[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreated3039[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMean3039[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSd3039[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMin3039[idx] <- bmDistTarget3039[1] + chunk$bmTarTargetMedian3039[idx] <- bmDistTarget3039[2] + chunk$bmTarTargetMax3039[idx] <- bmDistTarget3039[3] + bmDistComparator3039 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparator3039[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDays3039[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparator3039[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMean3039[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSd3039[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMin3039[idx] <- bmDistComparator3039[1] + chunk$bmTarComparatorMedian3039[idx] <- bmDistComparator3039[2] + chunk$bmTarComparatorMax3039[idx] <- bmDistComparator3039[3] + + subgroupName = ""Age40_49"" + subgroupValue = 1 + bmDistTarget4049 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreated4049[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDays4049[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreated4049[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMean4049[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSd4049[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMin4049[idx] <- bmDistTarget4049[1] + chunk$bmTarTargetMedian4049[idx] <- bmDistTarget4049[2] + chunk$bmTarTargetMax4049[idx] <- bmDistTarget4049[3] + bmDistComparator4049 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparator4049[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDays4049[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparator4049[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMean4049[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSd4049[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMin4049[idx] <- bmDistComparator4049[1] + chunk$bmTarComparatorMedian4049[idx] <- bmDistComparator4049[2] + chunk$bmTarComparatorMax4049[idx] <- bmDistComparator4049[3] + + subgroupName = ""Age50_59"" + subgroupValue = 1 + bmDistTarget5059 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreated5059[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDays5059[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreated5059[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMean5059[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSd5059[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMin5059[idx] <- bmDistTarget5059[1] + chunk$bmTarTargetMedian5059[idx] <- bmDistTarget5059[2] + chunk$bmTarTargetMax5059[idx] <- bmDistTarget5059[3] + bmDistComparator5059 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparator5059[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDays5059[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparator5059[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMean5059[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSd5059[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMin5059[idx] <- bmDistComparator5059[1] + chunk$bmTarComparatorMedian5059[idx] <- bmDistComparator5059[2] + chunk$bmTarComparatorMax5059[idx] <- bmDistComparator5059[3] + + subgroupName = ""Age60_69"" + subgroupValue = 1 + bmDistTarget6069 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreated6069[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDays6069[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreated6069[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMean6069[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSd6069[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMin6069[idx] <- bmDistTarget6069[1] + chunk$bmTarTargetMedian6069[idx] <- bmDistTarget6069[2] + chunk$bmTarTargetMax6069[idx] <- bmDistTarget6069[3] + bmDistComparator6069 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparator6069[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDays6069[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparator6069[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMean6069[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSd6069[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMin6069[idx] <- bmDistComparator6069[1] + chunk$bmTarComparatorMedian6069[idx] <- bmDistComparator6069[2] + chunk$bmTarComparatorMax6069[idx] <- bmDistComparator6069[3] + + subgroupName = ""Age70_79"" + subgroupValue = 1 + bmDistTarget7079 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreated7079[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDays7079[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreated7079[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMean7079[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSd7079[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMin7079[idx] <- bmDistTarget7079[1] + chunk$bmTarTargetMedian7079[idx] <- bmDistTarget7079[2] + chunk$bmTarTargetMax7079[idx] <- bmDistTarget7079[3] + bmDistComparator7079 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparator7079[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDays7079[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparator7079[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMean7079[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSd7079[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMin7079[idx] <- bmDistComparator7079[1] + chunk$bmTarComparatorMedian7079[idx] <- bmDistComparator7079[2] + chunk$bmTarComparatorMax7079[idx] <- bmDistComparator7079[3] + + subgroupName = ""Age80_89"" + subgroupValue = 1 + bmDistTarget8089 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreated8089[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDays8089[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreated8089[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMean8089[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSd8089[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMin8089[idx] <- bmDistTarget8089[1] + chunk$bmTarTargetMedian8089[idx] <- bmDistTarget8089[2] + chunk$bmTarTargetMax8089[idx] <- bmDistTarget8089[3] + bmDistComparator8089 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparator8089[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDays8089[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparator8089[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMean8089[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSd8089[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMin8089[idx] <- bmDistComparator8089[1] + chunk$bmTarComparatorMedian8089[idx] <- bmDistComparator8089[2] + chunk$bmTarComparatorMax8089[idx] <- bmDistComparator8089[3] + + subgroupName = ""Age90_99"" + subgroupValue = 1 + bmDistTarget9099 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreated9099[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDays9099[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreated9099[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMean9099[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSd9099[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMin9099[idx] <- bmDistTarget9099[1] + chunk$bmTarTargetMedian9099[idx] <- bmDistTarget9099[2] + chunk$bmTarTargetMax9099[idx] <- bmDistTarget9099[3] + bmDistComparator9099 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparator9099[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDays9099[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparator9099[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMean9099[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSd9099[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMin9099[idx] <- bmDistComparator9099[1] + chunk$bmTarComparatorMedian9099[idx] <- bmDistComparator9099[2] + chunk$bmTarComparatorMax9099[idx] <- bmDistComparator9099[3] + + subgroupName = ""Age100_109"" + subgroupValue = 1 + bmDistTarget100109 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmTreated100109[idx] <- nrow(studyPop[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmTreatedDays100109[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsTreated100109[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMean100109[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetSd100109[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarTargetMin100109[idx] <- bmDistTarget100109[1] + chunk$bmTarTargetMedian100109[idx] <- bmDistTarget100109[2] + chunk$bmTarTargetMax100109[idx] <- bmDistTarget100109[3] + bmDistComparator100109 <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue], c(0, 0.5, 1)) + chunk$bmComparator100109[idx] <- nrow(studyPop[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue, ]) + chunk$bmComparatorDays100109[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmEventsComparator100109[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMean100109[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorSd100109[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0 & studyPop[[subgroupName]] == subgroupValue]) + chunk$bmTarComparatorMin100109[idx] <- bmDistComparator100109[1] + chunk$bmTarComparatorMedian100109[idx] <- bmDistComparator100109[2] + chunk$bmTarComparatorMax100109[idx] <- bmDistComparator100109[3] + } + + fileName <- file.path(shinyDataFolder, paste0(""ps_a"", analysisId, + ""_t"", targetId, + ""_c"", comparatorId, + ""_"", databaseName, + "".rds"")) + if (!file.exists(fileName)) { + exampleRef <- reference[reference$analysisId == analysisId & + reference$targetId == targetId & + reference$comparatorId == comparatorId & + reference$outcomeId == outcomeIds[1], ] + ps <- readRDS(exampleRef$sharedPsFile) + preparedPsPlot <- EvidenceSynthesis::preparePsPlot(ps) + saveRDS(preparedPsPlot, fileName) + } + } + OhdsiRTools::logDebug(""Finished chunk with "", nrow(chunk), "" rows"") + return(chunk) + } + # OhdsiRTools::addDefaultFileLogger(""s:/temp/log.log"") + + cluster <- OhdsiRTools::makeCluster(min(maxCores, 10)) + comparison <- paste(analysisSummary$targetId, analysisSummary$comparatorId) + chunks <- split(analysisSummary, comparison) + analysisSummaries <- OhdsiRTools::clusterApply(cluster = cluster, + x = chunks, + fun = runTc, + tcosOfInterest = tcosOfInterest, + negativeControls = negativeControls, + shinyDataFolder = shinyDataFolder, + balanceDataFolder = balanceDataFolder, + outputFolder = outputFolder, + databaseName = databaseName, + reference = reference) + OhdsiRTools::stopCluster(cluster) + analysisSummary <- do.call(rbind, analysisSummaries) + + fileName <- file.path(resultsFolder, paste0(""results_"", databaseName,"".csv"")) + write.csv(analysisSummary, fileName, row.names = FALSE) + + hois <- analysisSummary[analysisSummary$type == ""Outcome of interest"", ] + fileName <- file.path(shinyDataFolder, paste0(""resultsHois_"", databaseName,"".rds"")) + saveRDS(hois, fileName) + + ncs <- analysisSummary[analysisSummary$type == ""Negative control"", + c(""targetId"", ""comparatorId"", ""outcomeId"", ""analysisId"", ""database"", ""logRr"", ""seLogRr"")] + fileName <- file.path(shinyDataFolder, paste0(""resultsNcs_"", databaseName,"".rds"")) + saveRDS(ncs, fileName) + + OhdsiRTools::logInfo(""Minimizing balance files for Shiny app"") + allCovarNames <- data.frame() + balanceFiles <- list.files(balanceDataFolder, ""bal.*.rds"") + pb <- txtProgressBar(style = 3) + for (i in 1:length(balanceFiles)) { + fileName <- balanceFiles[i] + balance <- readRDS(file.path(balanceDataFolder, fileName)) + idx <- !(balance$covariateId %in% allCovarNames$covariateId) + if (any(idx)) { + allCovarNames <- rbind(allCovarNames, balance[idx, c(""covariateId"", ""covariateName"")]) + } + balance$covariateName <- NULL + balance$conceptId <- NULL + balance$beforeMatchingSd <- NULL + balance$afterMatchingSd <- NULL + balance$beforeMatchingSumTreated <- NULL + balance$beforeMatchingSumComparator <- NULL + balance$afterMatchingSumTreated <- NULL + balance$afterMatchingSumComparator <- NULL + balance$analysisId <- as.integer(balance$analysisId) + saveRDS(balance, file.path(shinyDataFolder, fileName)) + if (i %% 100 == 0) { + setTxtProgressBar(pb, i/length(balanceFiles)) + } + } + setTxtProgressBar(pb, 1) + close(pb) + fileName <- file.path(shinyDataFolder, paste0(""covarNames_"", databaseName,"".rds"")) + saveRDS(allCovarNames, fileName) +} + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/R/KaplanMeierFixed.R",".R","11420","231","# @file KaplanMeier.R +# +# Copyright 2018 Observational Health Data Sciences and Informatics +# +# This file is part of CohortMethod +# +# 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. + + +#' Plot the Kaplan-Meier curve +#' +#' @description +#' \code{plotKaplanMeier} creates the Kaplain-Meier (KM) survival plot. Based (partially) on recommendations +#' in Pocock et al (2002). +#' +#' When variable-sized strata are detected, an adjusted KM plot is computed to account for stratified data, +#' as described in Galimberti eta al (2002), using the closed form variance estimator described in Xie et al +#' (2005). +#' +#' @param population A population object generated by \code{createStudyPopulation}, +#' potentially filtered by other functions. +#' @param censorMarks Whether or not to include censor marks in the plot. +#' @param confidenceIntervals Plot 95 percent confidence intervals? Default is TRUE, as recommended by Pocock et al. +#' @param includeZero Should the y axis include zero, or only go down to the lowest observed +#' survival? The default is FALSE, as recommended by Pocock et al. +#' @param dataTable Should the numbers at risk be shown in a table? Default is TRUE, as recommended by Pocock et al. +#' @param dataCutoff Fraction of the data (number censored) after which the graph will not +#' be shown. The default is 90 percent as recommended by Pocock et al. +#' @param targetLabel A label to us for the target cohort. +#' @param comparatorLabel A label to us for the comparator cohort. +#' @param title The main title of the plot. +#' @param fileName Name of the file where the plot should be saved, for example +#' 'plot.png'. See the function \code{ggsave} in the ggplot2 package for +#' supported file formats. +#' +#' @return +#' A ggplot object. Use the \code{\link[ggplot2]{ggsave}} function to save to file in a different +#' format. +#' +#' @references +#' Pocock SJ, Clayton TC, Altman DG. (2002) Survival plots of time-to-event outcomes in clinical trials: +#' good practice and pitfalls, Lancet, 359:1686-89. +#' +#' Galimberti S, Sasieni P, Valsecchi MG (2002) A weighted Kaplan-Meier estimator for matched data with +#' application to the comparison of chemotherapy and bone-marrow transplant in leukaemia. Statistics in +#' Medicine, 21(24):3847-64. +#' +#' Xie J, Liu C. (2005) Adjusted Kaplan-Meier estimator and log-rank test with inverse probability of treatment +#' weighting for survival data. Statistics in Medicine, 26(10):2276. +#' +#' @export +plotKaplanMeier <- function(population, + censorMarks = FALSE, + confidenceIntervals = TRUE, + includeZero = FALSE, + dataTable = TRUE, + dataCutoff = 0.90, + targetLabel = ""Treated"", + comparatorLabel = ""Comparator"", + title, + fileName = NULL) { + population$y <- 0 + population$y[population$outcomeCount != 0] <- 1 + if (is.null(population$stratumId) || length(unique(population$stratumId)) == nrow(population)/2) { + sv <- survival::survfit(survival::Surv(survivalTime, y) ~ treatment, population, conf.int = TRUE) + data <- data.frame(time = sv$time, + n.censor = sv$n.censor, + s = sv$surv, + strata = summary(sv, censored = T)$strata, + upper = sv$upper, + lower = sv$lower) + levels(data$strata)[levels(data$strata) == ""treatment=0""] <- comparatorLabel + levels(data$strata)[levels(data$strata) == ""treatment=1""] <- targetLabel + } else { + ParallelLogger::logInfo(""Variable size strata detected so using adjusted KM for stratified data"") + population$stratumSizeT <- 1 + strataSizesT <- aggregate(stratumSizeT ~ stratumId, population[population$treatment == 1,], sum) + if (max(strataSizesT$stratumSizeT) == 1) { + # variable ratio matching: use propensity score to compute IPTW + if (is.null(population$propensityScore)) { + stop(""Variable ratio matching detected, but no propensity score found"") + } + weights <- aggregate(propensityScore ~ stratumId, population, mean) + weights$weight <- weights$propensityScore / (1 - weights$propensityScore) + } else { + # stratification: infer probability of treatment from subject counts + strataSizesC <- aggregate(stratumSizeT ~ stratumId, population[population$treatment == 0,], sum) + colnames(strataSizesC)[2] <- ""stratumSizeC"" + weights <- merge(strataSizesT, strataSizesC) + weights$weight <- weights$stratumSizeT / weights$stratumSizeC + } + strataSizesC <- aggregate(stratumSizeT ~ stratumId, population[population$treatment == 0,], sum) + colnames(strataSizesC)[2] <- ""stratumSizeC"" + weights <- merge(strataSizesT, strataSizesC) + weights$weight <- weights$stratumSizeT / weights$stratumSizeC + population <- merge(population, weights[, c(""stratumId"", ""weight"")]) + population$weight[population$treatment == 1] <- 1 + idx <- population$treatment == 1 + survTarget <- CohortMethod:::adjustedKm(weight = population$weight[idx], + time = population$survivalTime[idx], + y = population$y[idx]) + survTarget$strata <- targetLabel + idx <- population$treatment == 0 + survComparator <- CohortMethod:::adjustedKm(weight = population$weight[idx], + time = population$survivalTime[idx], + y = population$y[idx]) + survComparator$strata <- comparatorLabel + if (censorMarks) { + addCensorData <- function(surv, treatment) { + censorData <- aggregate(rowId ~ survivalTime, population[population$treatment == treatment, ], length) + colnames(censorData) <- c(""time"", ""censored"") + eventData <- aggregate(y ~ survivalTime, population, sum) + colnames(eventData) <- c(""time"", ""events"") + surv <- merge(surv, censorData) + surv <- merge(surv, eventData, all.x = TRUE) + surv$n.censor = surv$censored - surv$events + return(surv) + } + survTarget <- addCensorData(survTarget, 1) + survComparator <- addCensorData(survComparator, 0) + } + + data <- rbind(survTarget, survComparator) + data$upper <- data$s^exp(qnorm(1 - 0.025)/log(data$s)*sqrt(data$var)/data$s) + data$lower <- data$s^exp(qnorm(0.025)/log(data$s)*sqrt(data$var)/data$s) + data$lower[data$s > 0.9999] <- data$s[data$s > 0.9999] + } + data$strata <- factor(data$strata, levels = c(targetLabel, comparatorLabel)) + cutoff <- quantile(population$survivalTime, dataCutoff) + xLabel <- ""Time in days"" + yLabel <- ""Survival probability"" + xlims <- c(-cutoff/40, cutoff) + + if (cutoff <= 300) { + xBreaks <- seq(0, cutoff, by = 50) + } else if (cutoff <= 600) { + xBreaks <- seq(0, cutoff, by = 100) + } else { + xBreaks <- seq(0, cutoff, by = 250) + } + + data <- data[data$time <= cutoff, ] + if (includeZero) { + ylims <- c(0, 1) + } else if (confidenceIntervals) { + ylims <- c(min(data$lower), 1) + } else { + ylims <- c(min(data$surv), 1) + } + plot <- ggplot2::ggplot(data, ggplot2::aes(x = time, + y = s, + color = strata, + fill = strata, + ymin = lower, + ymax = upper)) + + if (confidenceIntervals) + plot <- plot + ggplot2::geom_ribbon(color = rgb(0, 0, 0, alpha = 0)) + + plot <- plot + + ggplot2::geom_step(size = 1) + + ggplot2::scale_color_manual(values = c(rgb(0.8, 0, 0, alpha = 0.8), + rgb(0, 0, 0.8, alpha = 0.8))) + + ggplot2::scale_fill_manual(values = c(rgb(0.8, 0, 0, alpha = 0.3), + rgb(0, 0, 0.8, alpha = 0.3))) + + ggplot2::scale_x_continuous(xLabel, limits = xlims, breaks = xBreaks) + + ggplot2::scale_y_continuous(yLabel, limits = ylims) + + ggplot2::theme(legend.title = ggplot2::element_blank(), + legend.position = ""top"", + plot.title = ggplot2::element_text(hjust = 0.5)) + + if (censorMarks == TRUE) { + plot <- plot + ggplot2::geom_point(data = subset(data, n.censor >= 1), + ggplot2::aes(x = time, y = s), + shape = ""|"", + size = 3) + } + if (!missing(title) && !is.null(title)) { + plot <- plot + ggplot2::ggtitle(title) + } + if (dataTable) { + targetAtRisk <- c() + comparatorAtRisk <- c() + for (xBreak in xBreaks) { + targetAtRisk <- c(targetAtRisk, sum(population$treatment == 1 & population$survivalTime >= xBreak)) + comparatorAtRisk <- c(comparatorAtRisk, sum(population$treatment == 0 & population$survivalTime >= xBreak)) + } + labels <- data.frame(x = c(0, xBreaks, xBreaks), + y = as.factor(c(""Number at risk"", rep(targetLabel, length(xBreaks)), rep(comparatorLabel, length(xBreaks)))), + label = c("""", formatC(targetAtRisk, big.mark = "",""), formatC(comparatorAtRisk, big.mark = "",""))) + labels$y <- factor(labels$y, levels = c(comparatorLabel, targetLabel, ""Number at risk"")) + dataTable <- ggplot2::ggplot(labels, ggplot2::aes(x = x, y = y, label = label)) + + ggplot2::geom_text(size = 3.5, vjust = 0.5) + + ggplot2::scale_x_continuous(xLabel, limits = xlims, breaks = xBreaks) + + ggplot2::theme(panel.grid.major = ggplot2::element_blank(), + panel.grid.minor = ggplot2::element_blank(), + legend.position = ""none"", + panel.border = ggplot2::element_blank(), + panel.background = ggplot2::element_blank(), + axis.text.x = ggplot2::element_text(color = ""white""), + axis.title.x = ggplot2::element_text(color = ""white""), + axis.title.y = ggplot2::element_blank(), + axis.ticks = ggplot2::element_line(color = ""white"")) + plots <- list(plot, dataTable) + grobs <- widths <- list() + for (i in 1:length(plots)) { + grobs[[i]] <- ggplot2::ggplotGrob(plots[[i]]) + widths[[i]] <- grobs[[i]]$widths[2:5] + } + maxwidth <- do.call(grid::unit.pmax, widths) + for (i in 1:length(grobs)) { + grobs[[i]]$widths[2:5] <- as.list(maxwidth) + } + plot <- gridExtra::grid.arrange(grobs[[1]], grobs[[2]], heights = c(400,100)) + } + + if (!is.null(fileName)) + ggplot2::ggsave(fileName, plot, width = 7, height = 5, dpi = 400) + return(plot) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/R/prepareIrDoseResultsForAnalysis.R",".R","10756","195","#' @export +prepareIrDoseResultsForAnalysis <- function(outputFolder, + databaseName, + maxCores) { + packageName <- ""sglt2iDka"" + cmIrDoseOutputFolder <- file.path(outputFolder, ""cmIrDoseOutput"") + resultsFolder <- file.path(outputFolder, ""results"") + if (!file.exists(resultsFolder)) + dir.create(resultsFolder) + irDoseDataFolder <- file.path(resultsFolder, ""irDoseData"") + if (!file.exists(irDoseDataFolder)) + dir.create(irDoseDataFolder) + + # TCOs of interest + tcosOfInterest <- read.csv(system.file(""settings"", ""tcoIrDoseVariants.csv"", package = packageName), stringsAsFactors = FALSE) + tcosOfInterest <- unique(tcosOfInterest[, c(""targetCohortId"", ""targetDrugName"", ""targetCohortName"", ""comparatorCohortId"", ""comparatorDrugName"", ""comparatorCohortName"", + ""outcomeCohortId"", ""outcomeCohortName"")]) + names(tcosOfInterest) <- c(""targetId"", ""targetDrugName"", ""targetName"", ""comparatorId"", ""comparatorDrugName"", ""comparatorName"", + ""outcomeId"", ""outcomeName"") + + reference <- readRDS(file.path(cmIrDoseOutputFolder, ""outcomeModelReference.rds"")) + analysisSummary <- CohortMethod::summarizeAnalyses(reference) + analysisSummary <- sglt2iDka::addCohortNames(analysisSummary, dose = TRUE, ""outcomeId"", ""outcomeName"") + analysisSummary <- sglt2iDka::addCohortNames(analysisSummary, dose = TRUE, ""comparatorId"", ""comparatorName"") + analysisSummary <- sglt2iDka::addCohortNames(analysisSummary, dose = TRUE, ""targetId"", ""targetName"") + cmAnalysisList <- CohortMethod::loadCmAnalysisList(system.file(""settings"", ""cmIrDoseAnalysisList.json"", package = packageName)) + analyses <- data.frame(analysisId = unique(reference$analysisId), + analysisDescription = """", + stringsAsFactors = FALSE) + for (i in 1:length(cmAnalysisList)) { + analyses$analysisDescription[analyses$analysisId == cmAnalysisList[[i]]$analysisId] <- cmAnalysisList[[i]]$description + } + analysisSummary <- merge(analysisSummary, analyses) + analysisSummary <- analysisSummary[, c(1,20,2:19)] + analysisSummary <- analysisSummary[, -which(names(analysisSummary) %in% c(""rr"", ""ci95lb"", ""ci95ub"", ""p"", ""logRr"", ""seLogRr""))] + analysisSummary$database <- databaseName + + # reference to full sglt2i aftermatching cohorts + fullCmOutputFolder <- file.path(outputFolder, ""cmOutput"") + fullReference <- readRDS(file.path(fullCmOutputFolder, ""outcomeModelReference.rds"")) + fullReference <- fullReference[fullReference$analysisId == 1 & + fullReference$targetId %in% c(101, 104, 111, 114, 121, 124) & + fullReference$outcomeId %in% c(200, 201), ] # sglt2i ingredients with censor=90 + + fullReference <- aggregate(.~ targetId + outcomeId, fullReference, FUN = head, 1) + facs <- sapply(fullReference, is.factor) + fullReference[facs] <- lapply(fullReference[facs], as.character) + fullReference$analysisId <- as.integer(fullReference$analysisId) + fullReference$comparatorId <- as.integer(fullReference$comparatorId) + + runTc <- function(chunk, + tcosOfInterest, + reference) { + targetId <- chunk$targetId[1] + comparatorId <- chunk$comparatorId[1] + outcomeIds <- unique(tcosOfInterest$outcomeId) + outcomeNames <- unique(tcosOfInterest$outcomeName) + OhdsiRTools::logTrace(""Preparing results for target ID "", targetId, "", comparator ID"", comparatorId) + + for (analysisId in unique(reference$analysisId)) { # only 1 analysis + # analysisId=1 + + OhdsiRTools::logTrace(""Analysis ID "", analysisId) + + for (outcomeId in outcomeIds) { + # outcomeId=200 + + OhdsiRTools::logTrace(""Outcome ID "", outcomeId) + outcomeName <- outcomeNames[outcomeIds == outcomeId] + idx <- chunk$analysisId == analysisId & + chunk$targetId == targetId & + chunk$comparatorId == comparatorId & + chunk$outcomeId == outcomeId + refRow <- reference[reference$analysisId == analysisId & + reference$targetId == targetId & + reference$comparatorId == comparatorId & + reference$outcomeId == outcomeId, ] + + # before matching + studyPop <- readRDS(refRow$studyPopFile) + studyPop$outcomeCount[studyPop$outcomeCount != 0] <- 1 # first event + studyPop$timeAtRisk <- studyPop$survivalTime # TAR ends at first event + + # overall + bmDistTarget <- quantile(studyPop$timeAtRisk[studyPop$treatment == 1], c(0, 0.5, 1)) + chunk$bmTreated[idx] <- sum(studyPop$treatment == 1) + chunk$bmTreatedDays[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 1]) + chunk$bmEventsTreated[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 1]) + chunk$bmTarTargetMean[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 1]) + chunk$bmTarTargetSd[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 1]) + chunk$bmTarTargetMin[idx] <- bmDistTarget[1] + chunk$bmTarTargetMedian[idx] <- bmDistTarget[2] + chunk$bmTarTargetMax[idx] <- bmDistTarget[3] + + bmDistComparator <- quantile(studyPop$timeAtRisk[studyPop$treatment == 0], c(0, 0.5, 1)) + chunk$bmComparator[idx] <- sum(studyPop$treatment == 0) + chunk$bmComparatorDays[idx] <- sum(studyPop$timeAtRisk[studyPop$treatment == 0]) + chunk$bmEventsComparator[idx] <- sum(studyPop$outcomeCount[studyPop$treatment == 0]) + chunk$bmTarComparatorMean[idx] <- mean(studyPop$timeAtRisk[studyPop$treatment == 0]) + chunk$bmTarComparatorSd[idx] <- sd(studyPop$timeAtRisk[studyPop$treatment == 0]) + chunk$bmTarComparatorMin[idx] <- bmDistComparator[1] + chunk$bmTarComparatorMedian[idx] <- bmDistComparator[2] + chunk$bmTarComparatorMax[idx] <- bmDistComparator[3] + + # after matching dose-specific IRs + # crosswalk between dose-specific cohort IDs and full cohort IDs; dose-specific cohorts are subset of full cohorts per ID link + crossWalk <- function(id) { + if (id %in% c(300, 302, 304)) { # cana broad + fullTargetId <- 101 + fullComparatorId <- 21 + } + if (id %in% c(301, 303, 305)) { # cana narrow + fullTargetId <- 104 + fullComparatorId <- 24 + } + if (id %in% c(310, 312, 314)) { # dapa broad + fullTargetId <- 111 + fullComparatorId <- 21 + } + if (id %in% c(311, 313, 315)) { # dapa narrow + fullTargetId <- 114 + fullComparatorId <- 24 + } + if (id %in% c(320, 322, 324)) { # empa broad + fullTargetId <- 121 + fullComparatorId <- 21 + } + if (id %in% c(321, 323, 325)) { # empa narrow + fullTargetId <- 124 + fullComparatorId <- 24 + } + return(list(fullTargetId = fullTargetId, fullComparatorId = fullComparatorId)) + } + tIds <- crossWalk(targetId) + cIds <- crossWalk(comparatorId) + + tFullRefRow <- fullReference[fullReference$analysisId == analysisId & + fullReference$targetId == tIds$fullTargetId & + fullReference$comparatorId == tIds$fullComparatorId & + fullReference$outcomeId == outcomeId, ] + tStrataPop <- readRDS(tFullRefRow$strataFile) + tStrataPop$outcomeCount[tStrataPop$outcomeCount != 0] <- 1 # first event + tStrataPop$timeAtRisk <- tStrataPop$survivalTime # TAR ends at first event + tStrataPop <- tStrataPop[tStrataPop$treatment == 1, ] + tStrataPopDose <- merge(studyPop[studyPop$treatment == 1, ], tStrataPop, by = ""subjectId"", suffixes = c(""Study"", ""Strata"")) + + cFullRefRow <- fullReference[fullReference$analysisId == analysisId & + fullReference$targetId == cIds$fullTargetId & + fullReference$comparatorId == cIds$fullComparatorId & + fullReference$outcomeId == outcomeId, ] + cStrataPop <- readRDS(cFullRefRow$strataFile) + cStrataPop$outcomeCount[cStrataPop$outcomeCount != 0] <- 1 # first event + cStrataPop$timeAtRisk <- cStrataPop$survivalTime # TAR ends at first event + cStrataPop <- cStrataPop[cStrataPop$treatment == 1, ] + cStrataPopDose <- merge(studyPop[studyPop$treatment == 0, ], cStrataPop, by = ""subjectId"", suffixes = c(""Study"", ""Strata"")) + + amDistTarget <- quantile(tStrataPopDose$timeAtRiskStrata, c(0, 0.5, 1)) + chunk$amTreated[idx] <- sum(tStrataPopDose$treatmentStrata == 1) + chunk$amTreatedDays[idx] <- sum(tStrataPopDose$timeAtRiskStrata) + chunk$amEventsTreated[idx] <- sum(tStrataPopDose$outcomeCountStrata) + chunk$amTarTargetMean[idx] <- mean(tStrataPopDose$timeAtRiskStrata) + chunk$amTarTargetSd[idx] <- sd(tStrataPopDose$timeAtRiskStrata) + chunk$amTarTargetMin[idx] <- amDistTarget[1] + chunk$amTarTargetMedian[idx] <- amDistTarget[2] + chunk$amTarTargetMax[idx] <- amDistTarget[3] + + amDistComparator <- quantile(cStrataPopDose$timeAtRiskStrata, c(0, 0.5, 1)) + chunk$amComparator[idx] <- sum(cStrataPopDose$treatmentStrata == 1) + chunk$amComparatorDays[idx] <- sum(cStrataPopDose$timeAtRiskStrata) + chunk$amEventsComparator[idx] <- sum(cStrataPopDose$outcomeCountStrata) + chunk$amTarComparatorMean[idx] <- mean(cStrataPopDose$timeAtRiskStrata) + chunk$amTarComparatorSd[idx] <- sd(cStrataPopDose$timeAtRiskStrata) + chunk$amTarComparatorMin[idx] <- amDistComparator[1] + chunk$amTarComparatorMedian[idx] <- amDistComparator[2] + chunk$amTarComparatorMax[idx] <- amDistComparator[3] + } + } + OhdsiRTools::logDebug(""Finished chunk with "", nrow(chunk), "" rows"") + return(chunk) + } + + cluster <- OhdsiRTools::makeCluster(min(maxCores, 10)) + comparison <- paste(analysisSummary$targetId, analysisSummary$comparatorId) + chunks <- split(analysisSummary, comparison) + analysisSummaries <- OhdsiRTools::clusterApply(cluster = cluster, + x = chunks, + fun = runTc, + tcosOfInterest = tcosOfInterest, + reference = reference) + OhdsiRTools::stopCluster(cluster) + analysisSummary <- do.call(rbind, analysisSummaries) + fileName <- file.path(irDoseDataFolder, paste0(""irDoseData_"", databaseName,"".rds"")) + saveRDS(analysisSummary, fileName) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/R/createPopCharTable.R",".R","13483","247"," #' @export +createPopCharTable <- function(outputFolders, + databaseNames, + reportFolder) { + primaryAnalysisId <- 1 # ITT + tcosAnalyses <- read.csv(system.file(""settings"", ""tcoAnalysisVariants.csv"", package = ""sglt2iDka""), stringsAsFactors = FALSE) + primaryTcos <- unique(tcosAnalyses[, c(""targetCohortId"", ""targetDrugName"", ""targetCohortName"", ""comparatorCohortId"", ""comparatorDrugName"", ""comparatorCohortName"", + ""outcomeCohortId"", ""outcomeCohortName"")]) + names(primaryTcos) <- c(""targetId"", ""targetDrugName"", ""targetName"", ""comparatorId"", ""comparatorDrugName"", ""comparatorName"", + ""outcomeId"", ""outcomeName"") + abbrevName <- function(x) { + x <- sub(""-90"", """", x) + x <- sub(""gliflozin"", """", x) + x <- sub(""BROAD"", ""BD"", x) + x <- sub(""NARROW"", ""NW"", x) + x <- sub(""inotropic"", """", x) + } + primaryTcos$abbrevTargetName <- abbrevName(primaryTcos$targetName) + primaryTcos$addrevComparatorName <- abbrevName(primaryTcos$comparatorName) + + addSheet <- function(mainTable, + sheetName) { + sheet <- xlsx::createSheet(workBook, sheetName = sheetName) + percentStyle <- xlsx::CellStyle(wb = workBook, dataFormat = xlsx::DataFormat(""#,##0.0"")) + diffStyle <- xlsx::CellStyle(wb = workBook, dataFormat = xlsx::DataFormat(""#,##0.00"")) + header0 <- rep("""", 1+6*length(databaseNames)) + header0[2-6+6*(1:length(databaseNames))] <- databaseNames + xlsx::addDataFrame(as.data.frame(t(header0)), + sheet = sheet, + startRow = 1, + startColumn = 1, + col.names = FALSE, + row.names = FALSE, + showNA = FALSE) + for (k in 1:length(databaseNames)) { + xlsx::addMergedRegion(sheet, + startRow = 1, + endRow = 1, + startColumn = (k-1)*6 + 2, + endColumn = (k-1)*6 + 7) + } + header1 <- c("""", rep(c(""Before matching"", """", """", ""After matching"", """", """"), length(databaseNames))) + xlsx::addDataFrame(as.data.frame(t(header1)), + sheet = sheet, + startRow = 2, + startColumn = 1, + col.names = FALSE, + row.names = FALSE, + showNA = FALSE) + for (k in 1:length(databaseNames)) { + xlsx::addMergedRegion(sheet, + startRow = 2, + endRow = 2, + startColumn = (k-1)*6 + 2, + endColumn = (k-1)*6 + 4) + xlsx::addMergedRegion(sheet, + startRow = 2, + endRow = 2, + startColumn = (k-1)*6 + 5, + endColumn = (k-1)*6 + 7) + } + header2 <- c("""", rep(c(""T"", ""C"", """"), 2*length(databaseNames))) + xlsx::addDataFrame(as.data.frame(t(header2)), + sheet = sheet, + startRow = 3, + startColumn = 1, + col.names = FALSE, + row.names = FALSE, + showNA = FALSE) + xlsx::addDataFrame(as.data.frame(t(header3)), + sheet = sheet, + startRow = 4, + startColumn = 1, + col.names = FALSE, + row.names = FALSE, + showNA = FALSE) + styles <- rep(list(percentStyle, percentStyle, diffStyle,percentStyle, percentStyle, diffStyle), length(databaseNames)) + names(styles) <- 1+(1:length(styles)) + xlsx::addDataFrame(mainTable, + sheet = sheet, + startRow = 5, + startColumn = 1, + col.names = FALSE, + row.names = FALSE, + showNA = FALSE, + colStyle = styles) + xlsx::setColumnWidth(sheet, 1, 45) + xlsx::setColumnWidth(sheet, 2:25, 6) + } + + for (abbrevTargetName in unique(primaryTcos$abbrevTargetName)) { + # abbrevTargetName = ""SGLT2i-BD"" + workBook <- xlsx::createWorkbook(type=""xlsx"") + outcomeId <- 200 # only DKA IP/ER outcome + primaryTcsByTarget <- primaryTcos[primaryTcos$abbrevTargetName == abbrevTargetName & primaryTcos$outcomeId == outcomeId, ] + for (i in 1:nrow(primaryTcsByTarget)) { + # i=5 + allBalance <- list() + tables <- list() + header3 <- c(""Characteristic"") + for (k in 1:length(databaseNames)) { + # k=3 + databaseName <- databaseNames[k] + shinyDataFolder <- file.path(outputFolders[k], ""results"", ""shinyData"") + fileName <- paste0(""bal_a"", primaryAnalysisId, + ""_t"", primaryTcsByTarget$targetId[i], + ""_c"", primaryTcsByTarget$comparatorId[i], + ""_o"", outcomeId, + ""_"", databaseName,"".rds"") + balance <- readRDS(file.path(outputFolders[k], ""results"", ""balance"", fileName)) + # Infer population sizes before matching: + beforeTargetPopSize <- round(mean(balance$beforeMatchingSumTreated / balance$beforeMatchingMeanTreated, na.rm = TRUE)) + beforeComparatorPopSize <- round(mean(balance$beforeMatchingSumComparator / balance$beforeMatchingMeanComparator, na.rm = TRUE)) + + fileName <- paste0(""multiTherBal_a"", primaryAnalysisId, + ""_t"", primaryTcsByTarget$targetId[i], + ""_c"", primaryTcsByTarget$comparatorId[i], + ""_o"", outcomeId, + ""_"", databaseName,"".rds"") + multiTherBalance <- readRDS(file.path(shinyDataFolder, fileName)) + balance <- balance[, names(multiTherBalance)] + balance <- rbind(balance, multiTherBalance) + + tables[[k]] <- prepareTable1(balance) + allBalance[[k]] <- balance + fileName <- file.path(shinyDataFolder, paste0(""resultsHois_"", databaseName,"".rds"")) + resultsHois <- readRDS(fileName) + row <- resultsHois[resultsHois$targetId == primaryTcsByTarget$targetId[i] & + resultsHois$comparatorId == primaryTcsByTarget$comparatorId[i] & + resultsHois$outcomeId == outcomeId & + resultsHois$analysisId == primaryAnalysisId, ] + + header3 <- c(header3, + paste0(""% (n = "",format(beforeTargetPopSize, big.mark = "",""), "")""), + paste0(""% (n = "",format(beforeComparatorPopSize, big.mark = "",""), "")""), + ""Std.diff"", + paste0(""% (n = "",format(row$treated, big.mark = "",""), "")""), + paste0(""% (n = "",format(row$comparator, big.mark = "",""), "")""), + ""Std.diff"") + + } + # Create main table by combining all balances to get complete list of covariates: + allBalance <- do.call(rbind, allBalance) + allBalance$covariateName <- as.character(allBalance$covariateName) + allBalance$covariateName[allBalance$covariateId == 20003] <- ""age group: 100-104"" + allBalance <- allBalance[order(nchar(allBalance$covariateName), allBalance$covariateName), ] + #allBalance <- allBalance[order(allBalance$covariateName), ] + allBalance <- allBalance[!duplicated(allBalance$covariateName), ] + + headerCol <- prepareTable1(allBalance)[, 1] + mainTable <- matrix(NA, nrow = length(headerCol), ncol = length(tables) * 6) + for (k in 1:length(databaseNames)) { + mainTable[match(tables[[k]]$Characteristic, headerCol), ((k-1)*6)+(1:6)] <- as.matrix(tables[[k]][, 2:7]) + } + mainTable <- as.data.frame(mainTable) + mainTable <- cbind(data.frame(headerCol = headerCol), mainTable) + sheetName <- paste(abbrevTargetName, primaryTcsByTarget$addrevComparatorName[i], sep = "", "") + addSheet(mainTable = mainTable, + sheetName = sheetName) + + } + fileName <- paste0(""Char_"", sub(""-90"", """", primaryTcsByTarget$targetName[1]), "".xlsx"") + xlsx::saveWorkbook(workBook, file.path(reportFolder, fileName)) + } +} + + +prepareTable1 <- function(balance) { + pathToCsv <- system.file(""settings"", ""Table1Specs.csv"", package = ""sglt2iDka"") + specifications <- read.csv(pathToCsv, stringsAsFactors = FALSE) + + fixCase <- function(label) { + idx <- (toupper(label) == label) + if (any(idx)) { + label[idx] <- paste0(substr(label[idx], 1, 1), + tolower(substr(label[idx], 2, nchar(label[idx])))) + } + return(label) + } + resultsTable <- data.frame() + for (i in 1:nrow(specifications)) { # i=1 + if (specifications$analysisId[i] == """") { + resultsTable <- rbind(resultsTable, + data.frame(Characteristic = specifications$label[i], value = """")) + } else { + idx <- balance$analysisId == specifications$analysisId[i] + if (any(idx)) { + if (specifications$covariateIds[i] != """") { + covariateIds <- as.numeric(strsplit(specifications$covariateIds[i], "","")[[1]]) + idx <- balance$covariateId %in% covariateIds + } else { + covariateIds <- NULL + } + if (any(idx)) { + balanceSubset <- balance[idx, ] + if (is.null(covariateIds)) { + balanceSubset <- balanceSubset[order(balanceSubset$covariateId), ] + } else { + balanceSubset <- merge(balanceSubset, data.frame(covariateId = covariateIds, + rn = 1:length(covariateIds))) + balanceSubset <- balanceSubset[order(balanceSubset$rn, + balanceSubset$covariateId), ] + } + balanceSubset$covariateName <- fixCase(gsub(""^.*: "", + """", + balanceSubset$covariateName)) + balanceSubset$covariateName[balanceSubset$covariateId == 20003] <- ""100-104"" + if (specifications$covariateIds[i] == """" || length(covariateIds) > 1) { + resultsTable <- rbind(resultsTable, data.frame(Characteristic = specifications$label[i], + beforeMatchingMeanTreated = NA, + beforeMatchingMeanComparator = NA, + beforeMatchingStdDiff = NA, + afterMatchingMeanTreated = NA, + afterMatchingMeanComparator = NA, + afterMatchingStdDiff = NA, + stringsAsFactors = FALSE)) + resultsTable <- rbind(resultsTable, + data.frame(Characteristic = paste0("" "", balanceSubset$covariateName), + beforeMatchingMeanTreated = balanceSubset$beforeMatchingMeanTreated, + beforeMatchingMeanComparator = balanceSubset$beforeMatchingMeanComparator, + beforeMatchingStdDiff = balanceSubset$beforeMatchingStdDiff, + afterMatchingMeanTreated = balanceSubset$afterMatchingMeanTreated, + afterMatchingMeanComparator = balanceSubset$afterMatchingMeanComparator, + afterMatchingStdDiff = balanceSubset$afterMatchingStdDiff, + stringsAsFactors = FALSE)) + } else { + resultsTable <- rbind(resultsTable, data.frame(Characteristic = specifications$label[i], + beforeMatchingMeanTreated = balanceSubset$beforeMatchingMeanTreated, + beforeMatchingMeanComparator = balanceSubset$beforeMatchingMeanComparator, + beforeMatchingStdDiff = balanceSubset$beforeMatchingStdDiff, + afterMatchingMeanTreated = balanceSubset$afterMatchingMeanTreated, + afterMatchingMeanComparator = balanceSubset$afterMatchingMeanComparator, + afterMatchingStdDiff = balanceSubset$afterMatchingStdDiff, + stringsAsFactors = FALSE)) + } + } + } + } + } + idx <- resultsTable$Characteristic == ""CHADS2Vasc (mean)"" | resultsTable$Characteristic == ""Charlson comorbidity index (mean)"" | resultsTable$Characteristic == ""DCSI (mean)"" + resultsTable$beforeMatchingMeanTreated[!idx] <- resultsTable$beforeMatchingMeanTreated[!idx] * 100 + resultsTable$beforeMatchingMeanComparator[!idx] <- resultsTable$beforeMatchingMeanComparator[!idx] * 100 + resultsTable$afterMatchingMeanTreated[!idx] <- resultsTable$afterMatchingMeanTreated[!idx] * 100 + resultsTable$afterMatchingMeanComparator[!idx] <- resultsTable$afterMatchingMeanComparator[!idx] * 100 + return(resultsTable) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/R/createHrHeterogeneityTable.R",".R","3467","84","#' @export +createHrHeterogeneityTable <- function(outputFolders, + databaseNames, + reportFolder) { + loadResultsHrsByQ <- function(outputFolder) { + file <- file.path(outputFolder, ""diagnostics"", ""effectHeterogeneity.csv"") + x <- read.csv(file, stringsAsFactors = FALSE) + return(x) + } + results <- lapply(outputFolders, loadResultsHrsByQ) + + fileName <- file.path(reportFolder, paste0(""HRsByQuintile.xlsx"")) + unlink(fileName) + wb <- XLConnect::loadWorkbook(fileName, create = TRUE) + + for (i in 1:length(results)) { + result <- results[[i]] + database <- databaseNames[i] + + result$analysisDescription[result$analysisDescription == ""Time to First Post Index Event Intent to Treat Matching""] <- ""ITT"" + result$analysisDescription[result$analysisDescription == ""Time to First Post Index Event Per Protocol Matching""] <- ""PP"" + result$targetName <- sub(pattern = ""-90"", replacement = """", x = result$targetName) + result$comparatorName <- sub(pattern = ""-90"", replacement = """", x = result$comparatorName) + result$rr[result$rr > 10000] <- NA + result <- result[, -c(1,3,5,7,19,20)] + result <- result[, c(3, 4, 2, 1, 15, 9, 11, 13, 10, 12, 14, 5:8)] + result[, c(""rr"", ""ci95lb"", ""ci95ub"", ""p"")] <- round(result[, c(""rr"", ""ci95lb"", ""ci95ub"", ""p"")], 2) + + header0 <- c(""Target Cohort"", + ""Comparator Cohort"", + ""Outcome"", + ""TAR"", + ""PS Quintile"", + ""T Persons"", + ""T Days"", + ""T Events"", + ""C Persons"", + ""C Days"", + ""C Events"", + ""RR"", + ""95% CI LB"", + ""95% CI UB"", + ""p"" ) + XLConnect::createSheet(wb, name = database) + XLConnect::writeWorksheet(wb, + sheet = database, + data = as.data.frame(t(header0)), + startRow = 1, + startCol = 1, + rownames = FALSE, + header = FALSE) + XLConnect::writeWorksheet(wb, + sheet = database, + data = result, + startRow = 2, + startCol = 1, + header = FALSE, + rownames = FALSE) + } + XLConnect::saveWorkbook(wb) + + + loadResultsHrsByQTest <- function(outputFolder) { + file <- file.path(outputFolder, ""diagnostics"", ""effectHeterogeneityTest.csv"") + x <- read.csv(file, stringsAsFactors = FALSE) + return(x) + } + results <- lapply(outputFolders, loadResultsHrsByQTest) + + hrHeterogeneityTestResult <- data.frame() + for (i in 1:length(results)) { # i=1 + result <- results[[i]] + database <- databaseNames[i] + dbHrTest <- data.frame(database = database, percentLessP005 = round(sum(result$hrHetero)/nrow(result), 5) * 100) + hrHeterogeneityTestResult <- rbind(hrHeterogeneityTestResult, dbHrTest) + } + fileNameTestResult <- file.path(reportFolder, paste0(""HRsByQuintileTestResult.csv"")) + write.csv(hrHeterogeneityTestResult, fileNameTestResult, row.names = FALSE) + + fileNameTest <- file.path(reportFolder, paste0(""HRsByQuintileTest.csv"")) + hrHeterogeneityTest <- do.call(rbind, results) + write.csv(hrHeterogeneityTest, fileNameTest, row.names = FALSE) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/R/CustomCovariateBuilder.R",".R","9884","190","#' @export +createPriorOutcomesCovariateSettings <- function(outcomeDatabaseSchema = ""unknown"", + outcomeTable = ""unknown"", + outcomeIds = NA, + outcomeNames, + analysisId = NA, + windowStart = -365, + windowEnd = -1) { + covariateSettings <- list(outcomeDatabaseSchema = outcomeDatabaseSchema, + outcomeTable = outcomeTable, + outcomeIds = outcomeIds, + outcomeNames = outcomeNames, + analysisId = analysisId, + windowStart = windowStart, + windowEnd = windowEnd) + attr(covariateSettings, ""fun"") <- ""sglt2iDka::getDbPriorOutcomesCovariateData"" + class(covariateSettings) <- ""covariateSettings"" + return(covariateSettings) +} + +#' @export +getDbPriorOutcomesCovariateData <- function(connection, + oracleTempSchema = NULL, + cdmDatabaseSchema, + cohortTable = ""#cohort_person"", + cohortId = -1, + cdmVersion = ""5"", + rowIdField = ""subject_id"", + covariateSettings, + aggregated = FALSE) { + if (aggregated) + stop(""Aggregation not supported"") + writeLines(""Creating covariates based on prior outcomes"") + sql <- SqlRender::loadRenderTranslateSql(""getPriorOutcomeCovariates.sql"", + packageName = ""sglt2iDka"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + window_start = covariateSettings$windowStart, + window_end = covariateSettings$windowEnd, + row_id_field = rowIdField, + cohort_temp_table = cohortTable, + cohort_id = cohortId, + outcome_database_schema = covariateSettings$outcomeDatabaseSchema, + outcome_table = covariateSettings$outcomeTable, + outcome_ids = covariateSettings$outcomeIds) + covariates <- DatabaseConnector::querySql.ffdf(connection, sql) + colnames(covariates) <- SqlRender::snakeCaseToCamelCase(colnames(covariates)) + covariateRef <- data.frame(covariateId = covariateSettings$outcomeIds * 1000 + covariateSettings$analysisId, #999, + covariateName = paste(""Prior outcome:"", covariateSettings$outcomeNames), + analysisId = covariateSettings$analysisId, # 999, + conceptId = 0) + covariateRef <- ff::as.ffdf(covariateRef) + + # Construct analysis reference: + analysisRef <- data.frame(analysisId = as.numeric(covariateSettings$analysisId), #999), + analysisName = ""Prior outcome"", + domainId = ""Cohort"", + startDay = as.numeric(covariateSettings$windowStart), + endDay = as.numeric(covariateSettings$windowEnd), + isBinary = ""Y"", + missingMeansZero = ""Y"") + analysisRef <- ff::as.ffdf(analysisRef) + # Construct analysis reference: + metaData <- list(sql = sql, call = match.call()) + result <- list(covariates = covariates, + covariateRef = covariateRef, + analysisRef = analysisRef, + metaData = metaData) + class(result) <- ""covariateData"" + return(result) +} + +#' @export +setOutcomeDatabaseSchemaAndTable <- function(settings, + outcomeDatabaseSchema, + outcomeTable) { + if (class(settings) == ""covariateSettings"") { + if (!is.null(settings$outcomeDatabaseSchema)) { + settings$outcomeDatabaseSchema <- outcomeDatabaseSchema + settings$outcomeTable <- outcomeTable + } + } else { + if (is.list(settings) && length(settings) != 0) { + for (i in 1:length(settings)) { + if (is.list(settings[[i]])) { + settings[[i]] <- setOutcomeDatabaseSchemaAndTable(settings[[i]], outcomeDatabaseSchema, outcomeTable) + } + } + } + } + return(settings) +} + + +#' @export +createPriorExposureCovariateSettings <- function(exposureDatabaseSchema = ""unknown"", + covariateIdPrefix, + codeListSchema = ""unknown"", + codeListTable = ""unknown"", + vocabularyDatabaseSchema = ""unknown"", + drug) { + covariateSettings <- list(exposureDatabaseSchema = exposureDatabaseSchema, + covariateIdPrefix = covariateIdPrefix, + codeListSchema = codeListSchema, + codeListTable = codeListTable, + vocabularyDatabaseSchema = vocabularyDatabaseSchema, + drug = drug) + attr(covariateSettings, ""fun"") <- ""sglt2iDka::getDbPriorExposureCovariateData"" + class(covariateSettings) <- ""covariateSettings"" + return(covariateSettings) +} + +#' @export +getDbPriorExposureCovariateData <- function(connection, + oracleTempSchema = NULL, + cdmDatabaseSchema, + cohortTable = ""#cohort_person"", + cohortId = -1, + cdmVersion = ""5"", + rowIdField = ""subject_id"", + covariateSettings, + aggregated = FALSE) { + if (aggregated) + stop(""Aggregation not supported"") + writeLines(""Creating covariates based on prior insulin exposure"") + sql <- SqlRender::loadRenderTranslateSql(""getPriorExposureCovariates.sql"", + packageName = ""sglt2iDka"", + dbms = attr(connection, ""dbms""), + oracleTempSchema = oracleTempSchema, + row_id_field = rowIdField, + covariate_id_prefix = covariateSettings$covariateIdPrefix, + code_list_schema = covariateSettings$codeListSchema, + code_list_table = covariateSettings$codeListTable, + cohort_temp_table = cohortTable, + vocabulary_database_schema = covariateSettings$vocabularyDatabaseSchema, + cohort_id = cohortId, + cdm_database_schema = covariateSettings$exposureDatabaseSchema, + drug = covariateSettings$drug) + covariates <- DatabaseConnector::querySql.ffdf(connection, sql) + colnames(covariates) <- SqlRender::snakeCaseToCamelCase(colnames(covariates)) + covariateRef <- data.frame(covariateId = covariateSettings$covariateIdPrefix + 998, + covariateName = paste(""Any time prior exposure:"", covariateSettings$drug), + analysisId = 998, + conceptId = 0) + covariateRef <- ff::as.ffdf(covariateRef) + + # Construct analysis reference: + analysisRef <- data.frame(analysisId = as.numeric(998), + analysisName = ""Any time prior exposure"", + domainId = ""Drug"", + startDay = 0, + endDay = 0, + isBinary = ""Y"", + missingMeansZero = ""Y"") + analysisRef <- ff::as.ffdf(analysisRef) + # Construct analysis reference: + metaData <- list(sql = sql, call = match.call()) + result <- list(covariates = covariates, + covariateRef = covariateRef, + analysisRef = analysisRef, + metaData = metaData) + class(result) <- ""covariateData"" + return(result) +} + +#' @export +setExposureDatabaseSchemaAndIds <- function(settings, + exposureDatabaseSchema, + codeListSchema, + codeListTable, + vocabularyDatabaseSchema) { + if (class(settings) == ""covariateSettings"") { + if (!is.null(settings$exposureDatabaseSchema)) { + settings$exposureDatabaseSchema <- exposureDatabaseSchema + settings$codeListSchema <- codeListSchema + settings$codeListTable <- codeListTable + settings$vocabularyDatabaseSchema <- vocabularyDatabaseSchema + } + } else { + if (is.list(settings) && length(settings) != 0) { + for (i in 1:length(settings)) { + if (is.list(settings[[i]])) { + settings[[i]] <- setExposureDatabaseSchemaAndIds(settings[[i]], exposureDatabaseSchema, codeListSchema, codeListTable, vocabularyDatabaseSchema) + } + } + } + } + return(settings) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/R/createIrDoseTableFormatted.R",".R","12589","220","#' @export +createIrDoseTableFormatted <- function(outputFolders, + databaseNames, + reportFolder) { + loadIrDoseResults <- function(outputFolder) { + shinyDataFolder <- file.path(outputFolder, ""results"", ""irDoseData"") + file <- list.files(shinyDataFolder, pattern = ""irDoseData_.*.rds"", full.names = TRUE) + x <- readRDS(file) + return(x) + } + results <- lapply(outputFolders, loadIrDoseResults) + results <- do.call(rbind, results) + results$timeAtRisk <- ""ITT"" + results$targetCohort <- sub(pattern = ""-90"", replacement = """", x = results$targetName) + results$comparatorCohort <- sub(pattern = ""-90"", replacement = """", x = results$comparatorName) + + fileName <- file.path(reportFolder, paste0(""IRsDoseFormatted.xlsx"")) + unlink(fileName) + + outcomeNames <- unique(results$outcomeName) + timeAtRisks <- unique(results$timeAtRisk) + wb <- XLConnect::loadWorkbook(fileName, create = TRUE) + + subgroups <- list( + beforeMatching = c( + ""bmTreated"", ""bmTreatedDays"", ""bmEventsTreated"", + ""bmTarTargetMean"", ""bmTarTargetSd"", ""bmTarTargetMin"", ""bmTarTargetMedian"", ""bmTarTargetMax"", + ""bmComparator"", ""bmComparatorDays"", ""bmEventsComparator"", + ""bmTarComparatorMean"", ""bmTarComparatorSd"", ""bmTarComparatorMin"", ""bmTarComparatorMedian"", ""bmTarComparatorMax"")) + + for (i in 1) { # i=1 + mainTable <- data.frame() + cols <- subgroups[[i]] + subgroup <- names(subgroups)[i] + for (database in databaseNames) { # database = ""CCAE"" + dbTable <- data.frame() + for (outcomeName in outcomeNames) { # outcomeName <- outcomeNames[1] + for (timeAtRisk in timeAtRisks) { # timeAtRisk <- timeAtRisks[1] + subset <- results[results$database == database & + results$outcomeName == outcomeName & + results$timeAtRisk == timeAtRisk, ] + + # Broad + # Ts + cana100Broad <- subset[subset$targetCohort ==""Canagliflozin-100 mg-BROAD"", ][1, cols] + cana300Broad <- subset[subset$targetCohort ==""Canagliflozin-300 mg-BROAD"", ][1, cols] + canaOtherBroad <- subset[subset$targetCohort ==""Canagliflozin-Other-BROAD"", ][1, cols] + dapa5Broad <- subset[subset$targetCohort ==""Dapagliflozin-5 mg-BROAD"", ][1, cols] + dapa10Broad <- subset[subset$targetCohort ==""Dapagliflozin-10 mg-BROAD"", ][1, cols] + # Cs + dapaOtherBroad <- subset[subset$comparatorCohort == ""Dapagliflozin-Other-BROAD"", ][1, cols] + empa10Broad <- subset[subset$comparatorCohort == ""Empagliflozin-10 mg-BROAD"", ][1, cols] + empa25Broad <- subset[subset$comparatorCohort == ""Empagliflozin-25 mg-BROAD"", ][1, cols] + empaOtherBroad <- subset[subset$comparatorCohort == ""Empagliflozin-Other-BROAD"", ][1, cols] + + # Narrow + # Ts + cana100Narrow <- subset[subset$targetCohort ==""Canagliflozin-100 mg-NARROW"", ][1, cols] + cana300Narrow <- subset[subset$targetCohort ==""Canagliflozin-300 mg-NARROW"", ][1, cols] + canaOtherNarrow <- subset[subset$targetCohort ==""Canagliflozin-Other-NARROW"", ][1, cols] + dapa5Narrow <- subset[subset$targetCohort ==""Dapagliflozin-5 mg-NARROW"", ][1, cols] + # Cs + dapa10Narrow <- subset[subset$comparatorCohort == ""Dapagliflozin-10 mg-NARROW"", ][1, cols] + dataOtherNarrow <- subset[subset$comparatorCohort == ""Dapagliflozin-Other-NARROW"", ][1, cols] + empa10Narrow <- subset[subset$comparatorCohort == ""Empagliflozin-10 mg-NARROW"", ][1, cols] + empa25Narrow <- subset[subset$comparatorCohort == ""Empagliflozin-25 mg-NARROW"", ][1, cols] + empaOtherNarrow <- subset[subset$comparatorCohort == ""Empagliflozin-Other-NARROW"", ][1, cols] + + subTable <- data.frame(outcomeName = outcomeName, + timeAtRisk = timeAtRisk, + exposure = c(""Canagliflozin-100 mg-BROAD"", + ""Canagliflozin-300 mg-BROAD"", + ""Canagliflozin-Other-BROAD"", + ""Dapagliflozin-5 mg-BROAD"", + ""Dapagliflozin-10 mg-BROAD"", + + ""Dapagliflozin-Other-BROAD"", + ""Empagliflozin-10 mg-BROAD"", + ""Empagliflozin-25 mg-BROAD"", + ""Empagliflozin-Other-BROAD"", + + ""Canagliflozin-100 mg-NARROW"", + ""Canagliflozin-300 mg-NARROW"", + ""Canagliflozin-Other-NARROW"", + ""Dapagliflozin-5 mg-NARROW"", + + ""Dapagliflozin-10 mg-NARROW"", + ""Dapagliflozin-Other-NARROW"", + ""Empagliflozin-10 mg-NARROW"", + ""Empagliflozin-25 mg-NARROW"", + ""Empagliflozin-Other-NARROW""), + personTime = c(cana100Broad[, 2], + cana300Broad[, 2], + canaOtherBroad[, 2], + dapa5Broad[, 2], + dapa10Broad[, 2], + + dapaOtherBroad[, 10], + empa10Broad[, 10], + empa25Broad[, 10], + empaOtherBroad[, 10], + + cana100Narrow[, 2], + cana300Narrow[, 2], + canaOtherNarrow[, 2], + dapa5Narrow[, 2], + + dapa10Narrow[, 10], + dataOtherNarrow[, 10], + empa10Narrow[, 10], + empa25Narrow[, 10], + empaOtherNarrow[, 10]) / 365.25, + events = c(cana100Broad[, 3], + cana300Broad[, 3], + canaOtherBroad[, 3], + dapa5Broad[, 3], + dapa10Broad[, 3], + + dapaOtherBroad[, 11], + empa10Broad[, 11], + empa25Broad[, 11], + empaOtherBroad[, 11], + + cana100Narrow[, 3], + cana300Narrow[, 3], + canaOtherNarrow[, 3], + dapa5Narrow[, 3], + + dapa10Narrow[, 11], + dataOtherNarrow[, 11], + empa10Narrow[, 11], + empa25Narrow[, 11], + empaOtherNarrow[, 11])) + + subTable$ir <- 1000 * subTable$events / subTable$personTime + broadSubTable <- subTable[grep(""BROAD"", subTable$exposure), c(""outcomeName"", ""exposure"", ""events"", ""ir"")] + narrowSubTable <- subTable[grep(""NARROW"", subTable$exposure), c(""events"", ""ir"")] + formattedSubTable <- cbind(broadSubTable, narrowSubTable) + formattedSubTable$exposure <- sub(""-BROAD"", """", formattedSubTable$exposure) + names(formattedSubTable) <- c(""outcomeName"", ""exposure"", ""eventsBroad"", ""irBroad"", ""eventsNarrow"", ""irNarrow"") + formattedSubTable$exposureOrder <- match(formattedSubTable$exposure, c(""Canagliflozin-300 mg"", + ""Canagliflozin-100 mg"", + ""Canagliflozin-Other"", + ""Dapagliflozin-10 mg"", + ""Dapagliflozin-5 mg"", + ""Dapagliflozin-Other"", + ""Empagliflozin-25 mg"", + ""Empagliflozin-10 mg"", + ""Empagliflozin-Other"")) + formattedSubTable <- formattedSubTable[order(formattedSubTable$exposureOrder), ] + formattedSubTable <- formattedSubTable[, -7] + dbTable <- rbind(dbTable, formattedSubTable) + } + } + colnames(dbTable)[3:6] <- paste(colnames(dbTable)[3:6], database, sep = ""_"") + if (ncol(mainTable) == 0) { + mainTable <- dbTable + } else { + if (!all.equal(mainTable$outcomeName, dbTable$outcomeName) || + !all.equal(mainTable$timeAtRisk, dbTable$timeAtRisk) || + !all.equal(mainTable$exposure, dbTable$exposure)) { + stop(""Something wrong with data ordering"") + } + mainTable <- cbind(mainTable, dbTable[, 3:6]) + } + } + mainTable[, seq(4,18,2)] <- round(mainTable[, seq(4,18,2)], 2) # IRs + + XLConnect::createSheet(wb, name = subgroup) + header0 <- c("""", """", rep(databaseNames, each = 4)) + XLConnect::writeWorksheet(wb, + sheet = subgroup, + data = as.data.frame(t(header0)), + startRow = 1, + startCol = 1, + rownames = FALSE, + header = FALSE) + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""C1:F1"") + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""G1:J1"") + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""K1:N1"") + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""O1:R1"") + + header1 <- c("""", """", rep(""Broad"",2), rep(""Narrow"",2), rep(""Broad"",2), rep(""Narrow"",2), rep(""Broad"",2), rep(""Narrow"",2), rep(""Broad"",2), rep(""Narrow"",2)) + XLConnect::writeWorksheet(wb, + sheet = subgroup, + data = as.data.frame(t(header1)), + startRow = 2, + startCol = 1, + rownames = FALSE, + header = FALSE) + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""C2:D2"") + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""E2:F2"") + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""G2:H2"") + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""I2:J2"") + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""K2:L2"") + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""M2:N2"") + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""O2:P2"") + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""Q2:R2"") + + header2 <- c(""Outcome"", ""Exposure"", rep(c(""Events"", ""IR""), length(databaseNames) *2 )) + XLConnect::writeWorksheet(wb, + sheet = subgroup, + data = as.data.frame(t(header2)), + startRow = 3, + startCol = 1, + rownames = FALSE, + header = FALSE) + XLConnect::writeWorksheet(wb, + sheet = subgroup, + data = mainTable, + startRow = 4, + startCol = 1, + rownames = FALSE, + header = FALSE) + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""A4:A12"") + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""A13:A21"") + } + XLConnect::saveWorkbook(wb) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/R/createIrSubgroupsTableFormatted.R",".R","16881","253","#' @export +createIrSubgroupsTableFormatted <- function(outputFolders, + databaseNames, + reportFolder) { + loadResultsHois <- function(outputFolder, + fileName) { + shinyDataFolder <- file.path(outputFolder, ""results"", ""shinyData"") + file <- list.files(shinyDataFolder, pattern = ""resultsHois_.*.rds"", full.names = TRUE) + x <- readRDS(file) + if (is.null(x$i2)) + x$i2 <- NA + return(x) + } + results <- lapply(outputFolders, loadResultsHois) + results <- do.call(rbind, results) + results$targetCohort <- sub(pattern = ""-90"", replacement = """", x = results$targetName) + results$comparatorCohort <- sub(pattern = ""-90"", replacement = """", x = results$comparatorName) + results$timeAtRisk[results$analysisDescription == ""Time to First Post Index Event Intent to Treat Matching""] <- ""ITT"" + results <- results[!results$analysisDescription == ""Time to First Post Index Event Per Protocol Matching"", ] + + outcomeNames <- unique(results$outcomeName) + timeAtRisks <- unique(results$timeAtRisk) + + fileName <- file.path(reportFolder, paste0(""IRsSubgroupsFormatted.xlsx"")) + unlink(fileName) + wb <- XLConnect::loadWorkbook(fileName, create = TRUE) + + subgroups <- list( + Age10_19 = c( + ""bmTreated1019"", ""bmTreatedDays1019"", ""bmEventsTreated1019"", + ""bmTarTargetMean1019"", ""bmTarTargetSd1019"", ""bmTarTargetMin1019"", ""bmTarTargetMedian1019"", ""bmTarTargetMax1019"", + ""bmComparator1019"", ""bmComparatorDays1019"", ""bmEventsComparator1019"", + ""bmTarComparatorMean1019"", ""bmTarComparatorSd1019"", ""bmTarComparatorMin1019"", ""bmTarComparatorMedian1019"", ""bmTarComparatorMax1019""), + Age20_29 = c( + ""bmTreated2029"", ""bmTreatedDays2029"", ""bmEventsTreated2029"", + ""bmTarTargetMean2029"", ""bmTarTargetSd2029"", ""bmTarTargetMin2029"", ""bmTarTargetMedian2029"", ""bmTarTargetMax2029"", + ""bmComparator2029"", ""bmComparatorDays2029"", ""bmEventsComparator2029"", + ""bmTarComparatorMean2029"", ""bmTarComparatorSd2029"", ""bmTarComparatorMin2029"", ""bmTarComparatorMedian2029"", ""bmTarComparatorMax2029""), + Age30_39 = c( + ""bmTreated3039"", ""bmTreatedDays3039"", ""bmEventsTreated3039"", + ""bmTarTargetMean3039"", ""bmTarTargetSd3039"", ""bmTarTargetMin3039"", ""bmTarTargetMedian3039"", ""bmTarTargetMax3039"", + ""bmComparator3039"", ""bmComparatorDays3039"", ""bmEventsComparator3039"", + ""bmTarComparatorMean3039"", ""bmTarComparatorSd3039"", ""bmTarComparatorMin3039"", ""bmTarComparatorMedian3039"", ""bmTarComparatorMax3039""), + Age40_49 = c( + ""bmTreated4049"", ""bmTreatedDays4049"", ""bmEventsTreated4049"", + ""bmTarTargetMean4049"", ""bmTarTargetSd4049"", ""bmTarTargetMin4049"", ""bmTarTargetMedian4049"", ""bmTarTargetMax4049"", + ""bmComparator4049"", ""bmComparatorDays4049"", ""bmEventsComparator4049"", + ""bmTarComparatorMean4049"", ""bmTarComparatorSd4049"", ""bmTarComparatorMin4049"", ""bmTarComparatorMedian4049"", ""bmTarComparatorMax4049""), + Age50_59 = c( + ""bmTreated5059"", ""bmTreatedDays5059"", ""bmEventsTreated5059"", + ""bmTarTargetMean5059"", ""bmTarTargetSd5059"", ""bmTarTargetMin5059"", ""bmTarTargetMedian5059"", ""bmTarTargetMax5059"", + ""bmComparator5059"", ""bmComparatorDays5059"", ""bmEventsComparator5059"", + ""bmTarComparatorMean5059"", ""bmTarComparatorSd5059"", ""bmTarComparatorMin5059"", ""bmTarComparatorMedian5059"", ""bmTarComparatorMax5059""), + Age60_69 = c( + ""bmTreated6069"", ""bmTreatedDays6069"", ""bmEventsTreated6069"", + ""bmTarTargetMean6069"", ""bmTarTargetSd6069"", ""bmTarTargetMin6069"", ""bmTarTargetMedian6069"", ""bmTarTargetMax6069"", + ""bmComparator6069"", ""bmComparatorDays6069"", ""bmEventsComparator6069"", + ""bmTarComparatorMean6069"", ""bmTarComparatorSd6069"", ""bmTarComparatorMin6069"", ""bmTarComparatorMedian6069"", ""bmTarComparatorMax6069""), + Age70_79 = c( + ""bmTreated7079"", ""bmTreatedDays7079"", ""bmEventsTreated7079"", + ""bmTarTargetMean7079"", ""bmTarTargetSd7079"", ""bmTarTargetMin7079"", ""bmTarTargetMedian7079"", ""bmTarTargetMax7079"", + ""bmComparator7079"", ""bmComparatorDays7079"", ""bmEventsComparator7079"", + ""bmTarComparatorMean7079"", ""bmTarComparatorSd7079"", ""bmTarComparatorMin7079"", ""bmTarComparatorMedian7079"", ""bmTarComparatorMax7079""), + Age80_89 = c( + ""bmTreated8089"", ""bmTreatedDays8089"", ""bmEventsTreated8089"", + ""bmTarTargetMean8089"", ""bmTarTargetSd8089"", ""bmTarTargetMin8089"", ""bmTarTargetMedian8089"", ""bmTarTargetMax8089"", + ""bmComparator8089"", ""bmComparatorDays8089"", ""bmEventsComparator8089"", + ""bmTarComparatorMean8089"", ""bmTarComparatorSd8089"", ""bmTarComparatorMin8089"", ""bmTarComparatorMedian8089"", ""bmTarComparatorMax8089""), + Age90_99 = c( + ""bmTreated9099"", ""bmTreatedDays9099"", ""bmEventsTreated9099"", + ""bmTarTargetMean9099"", ""bmTarTargetSd9099"", ""bmTarTargetMin9099"", ""bmTarTargetMedian9099"", ""bmTarTargetMax9099"", + ""bmComparator9099"", ""bmComparatorDays9099"", ""bmEventsComparator9099"", + ""bmTarComparatorMean9099"", ""bmTarComparatorSd9099"", ""bmTarComparatorMin9099"", ""bmTarComparatorMedian9099"", ""bmTarComparatorMax9099""), + Age100_109 = c( + ""bmTreated100109"", ""bmTreatedDays100109"", ""bmEventsTreated100109"", + ""bmTarTargetMean100109"", ""bmTarTargetSd100109"", ""bmTarTargetMin100109"", ""bmTarTargetMedian100109"", ""bmTarTargetMax100109"", + ""bmComparator100109"", ""bmComparatorDays100109"", ""bmEventsComparator100109"", + ""bmTarComparatorMean100109"", ""bmTarComparatorSd100109"", ""bmTarComparatorMin100109"", ""bmTarComparatorMedian100109"", ""bmTarComparatorMax100109""), + Male = c( + ""bmTreatedMale"", ""bmTreatedDaysMale"", ""bmEventsTreatedMale"", + ""bmTarTargetMeanMale"", ""bmTarTargetSdMale"", ""bmTarTargetMinMale"", ""bmTarTargetMedianMale"", ""bmTarTargetMaxMale"", + ""bmComparatorMale"", ""bmComparatorDaysMale"", ""bmEventsComparatorMale"", + ""bmTarComparatorMeanMale"", ""bmTarComparatorSdMale"", ""bmTarComparatorMinMale"", ""bmTarComparatorMedianMale"", ""bmTarComparatorMaxMale""), + Female = c( + ""bmTreatedFemale"", ""bmTreatedDaysFemale"", ""bmEventsTreatedFemale"", + ""bmTarTargetMeanFemale"", ""bmTarTargetSdFemale"", ""bmTarTargetMinFemale"", ""bmTarTargetMedianFemale"", ""bmTarTargetMaxFemale"", + ""bmComparatorFemale"", ""bmComparatorDaysFemale"", ""bmEventsComparatorFemale"", + ""bmTarComparatorMeanFemale"", ""bmTarComparatorSdFemale"", ""bmTarComparatorMinFemale"", ""bmTarComparatorMedianFemale"", ""bmTarComparatorMaxFemale""), + PriorInsulin = c( + ""bmTreatedPriorInsulin"", ""bmTreatedDaysPriorInsulin"", ""bmEventsTreatedPriorInsulin"", + ""bmTarTargetMeanPriorInsulin"", ""bmTarTargetSdPriorInsulin"", ""bmTarTargetMinPriorInsulin"", ""bmTarTargetMedianPriorInsulin"", ""bmTarTargetMaxPriorInsulin"", + ""bmComparatorPriorInsulin"", ""bmComparatorDaysPriorInsulin"", ""bmEventsComparatorPriorInsulin"", + ""bmTarComparatorMeanPriorInsulin"", ""bmTarComparatorSdPriorInsulin"", ""bmTarComparatorMinPriorInsulin"", ""bmTarComparatorMedianPriorInsulin"", ""bmTarComparatorMaxPriorInsulin""), + NoPriorInsulin = c( + ""bmTreatedNoPriorInsulin"", ""bmTreatedDaysNoPriorInsulin"", ""bmEventsTreatedNoPriorInsulin"", + ""bmTarTargetMeanNoPriorInsulin"", ""bmTarTargetSdNoPriorInsulin"", ""bmTarTargetMinNoPriorInsulin"", ""bmTarTargetMedianNoPriorInsulin"", ""bmTarTargetMaxNoPriorInsulin"", + ""bmComparatorNoPriorInsulin"", ""bmComparatorDaysNoPriorInsulin"", ""bmEventsComparatorNoPriorInsulin"", + ""bmTarComparatorMeanNoPriorInsulin"", ""bmTarComparatorSdNoPriorInsulin"", ""bmTarComparatorMinNoPriorInsulin"", ""bmTarComparatorMedianNoPriorInsulin"", ""bmTarComparatorMaxNoPriorInsulin""), + PriorDkaIpEr = c( + ""bmTreatedPriorDkaIpEr"", ""bmTreatedDaysPriorDkaIpEr"", ""bmEventsTreatedPriorDkaIpEr"", + ""bmTarTargetMeanPriorDkaIpEr"", ""bmTarTargetSdPriorDkaIpEr"", ""bmTarTargetMinPriorDkaIpEr"", ""bmTarTargetMedianPriorDkaIpEr"", ""bmTarTargetMaxPriorDkaIpEr"", + ""bmComparatorPriorDkaIpEr"", ""bmComparatorDaysPriorDkaIpEr"", ""bmEventsComparatorPriorDkaIpEr"", + ""bmTarComparatorMeanPriorDkaIpEr"", ""bmTarComparatorSdPriorDkaIpEr"", ""bmTarComparatorMinPriorDkaIpEr"", ""bmTarComparatorMedianPriorDkaIpEr"", ""bmTarComparatorMaxPriorDkaIpEr""), + NoPriorDkaIpEr = c( + ""bmTreatedNoPriorDkaIpEr"", ""bmTreatedDaysNoPriorDkaIpEr"", ""bmEventsTreatedNoPriorDkaIpEr"", + ""bmTarTargetMeanNoPriorDkaIpEr"", ""bmTarTargetSdNoPriorDkaIpEr"", ""bmTarTargetMinNoPriorDkaIpEr"", ""bmTarTargetMedianNoPriorDkaIpEr"", ""bmTarTargetMaxNoPriorDkaIpEr"", + ""bmComparatorNoPriorDkaIpEr"", ""bmComparatorDaysNoPriorDkaIpEr"", ""bmEventsComparatorNoPriorDkaIpEr"", + ""bmTarComparatorMeanNoPriorDkaIpEr"", ""bmTarComparatorSdNoPriorDkaIpEr"", ""bmTarComparatorMinNoPriorDkaIpEr"", ""bmTarComparatorMedianNoPriorDkaIpEr"", ""bmTarComparatorMaxNoPriorDkaIpEr"")) + + mainTable <- data.frame() + for (i in 1:length(subgroups)) { # i=1 + subgroupTable <- data.frame() + cols <- subgroups[[i]] + subgroup <- names(subgroups)[i] + for (database in databaseNames) { # database <- ""CCAE"" + dbTable <- data.frame() + for (outcomeName in outcomeNames) { # outcomeName <- outcomeNames[2] + for (timeAtRisk in timeAtRisks[1]) { # timeAtRisk = timeAtRisks[1] + subset <- results[results$database == database & + results$outcomeName == outcomeName & + results$timeAtRisk == timeAtRisk, ] + + # Ts broad + sglt2iBroad <- subset[subset$targetCohort == ""SGLT2i-BROAD"", ][1, cols] + canaBroad <- subset[subset$targetCohort == ""Canagliflozin-BROAD"", ][1, cols] + dapaBroad <- subset[subset$targetCohort == ""Dapagliflozin-BROAD"", ][1, cols] + empaBroad <- subset[subset$targetCohort == ""Empagliflozin-BROAD"", ][1, cols] + + # Cs broad + dpp4Broad <- subset[subset$comparatorCohort == ""DPP-4i-BROAD"", ][1, cols] + glp1Broad <- subset[subset$comparatorCohort == ""GLP-1a-BROAD"", ][1, cols] + suBroad <- subset[subset$comparatorCohort == ""SU-BROAD"", ][1, cols] + tzdBroad <- subset[subset$comparatorCohort == ""TZDs-BROAD"", ][1, cols] + insulinBroad <- subset[subset$comparatorCohort == ""Insulin-BROAD"", ][1, cols] + metforminBroad <- subset[subset$comparatorCohort == ""Metformin-BROAD"", ][1, cols] + insAhasBroad <- subset[subset$comparatorCohort == ""Insulinotropic AHAs-BROAD"", ][1, cols] + otherAhasBroad <- subset[subset$comparatorCohort == ""Other AHAs-BROAD"", ][1, cols] + + # Ts narrow + sglt2iNarrow <- subset[subset$targetCohort == ""SGLT2i-NARROW"", ][1, cols] + canaNarrow <- subset[subset$targetCohort == ""Canagliflozin-NARROW"", ][1, cols] + empaNarrow <- subset[subset$targetCohort == ""Empagliflozin-NARROW"", ][1, cols] + dapaNarrow <- subset[subset$targetCohort == ""Dapagliflozin-NARROW"", ][1, cols] + + # Cs narrow + dpp4Narrow <- subset[subset$comparatorCohort == ""DPP-4i-NARROW"", ][1, cols] + glp1Narrow <- subset[subset$comparatorCohort == ""GLP-1a-NARROW"", ][1, cols] + suNarrow <- subset[subset$comparatorCohort == ""SU-NARROW"", ][1, cols] + tzdNarrow <- subset[subset$comparatorCohort == ""TZDs-NARROW"", ][1, cols] + insulinNarrow <- subset[subset$comparatorCohort == ""Insulin-NARROW"", ][1, cols] + metforminNarrow <- subset[subset$comparatorCohort == ""Metformin-NARROW"", ][1, cols] + insAhasNarrow <- subset[subset$comparatorCohort == ""Insulinotropic AHAs-NARROW"", ][1, cols] + otherAhasNarrow <- subset[subset$comparatorCohort == ""Other AHAs-NARROW"", ][1, cols] + + subTable <- data.frame(outcomeName = outcomeName, + exposure = c( + ""SGLT2i-BROAD"", ""Canagliflozin-BROAD"", ""Dapagliflozin-BROAD"", ""Empagliflozin-BROAD"", + ""DPP-4i-BROAD"", ""GLP-1a-BROAD"", ""SU-BROAD"", ""TZDs-BROAD"", + ""Insulin-BROAD"", ""Metformin-BROAD"", ""Insulinotropic AHAs-BROAD"", ""Other AHAs-BROAD"", + + ""SGLT2i-NARROW"", ""Canagliflozin-NARROW"", ""Dapagliflozin-NARROW"", ""Empagliflozin-NARROW"", + ""DPP-4i-NARROW"", ""GLP-1a-NARROW"", ""SU-NARROW"", ""TZDs-NARROW"", + ""Insulin-NARROW"", ""Metformin-NARROW"", ""Insulinotropic AHAs-NARROW"", ""Other AHAs-NARROW""), + + subgroup = subgroup, + + personTime = c( + sglt2iBroad[, 2], canaBroad[, 2], dapaBroad[, 2], empaBroad[, 2], + dpp4Broad[, 10], glp1Broad[, 10], suBroad[, 10], tzdBroad[, 10], + insulinBroad[, 10], metforminBroad[, 10], insAhasBroad[, 10], otherAhasBroad[, 10], + + sglt2iNarrow[, 2], canaNarrow[, 2], dapaNarrow[, 2], empaNarrow[, 2], + dpp4Narrow[, 10], glp1Narrow[, 10], suNarrow[, 10], tzdNarrow[, 10], + insulinNarrow[, 10], metforminNarrow[, 10], insAhasNarrow[, 10], otherAhasNarrow[, 10]) / 365.25, + + events = c( + sglt2iBroad[, 3], canaBroad[, 3], dapaBroad[, 3], empaBroad[, 3], + dpp4Broad[, 11], glp1Broad[, 11], suBroad[, 11], tzdBroad[, 11], + insulinBroad[, 11], metforminBroad[, 11], insAhasBroad[, 11], otherAhasBroad[, 11], + + sglt2iNarrow[, 3], canaNarrow[, 3], dapaNarrow[, 3], empaNarrow[, 3], + dpp4Narrow[, 11], glp1Narrow[, 11], suNarrow[, 11], tzdNarrow[, 11], + insulinNarrow[, 11], metforminNarrow[, 11], insAhasNarrow[, 11], otherAhasNarrow[, 11])) + + subTable$ir <- 1000 * subTable$events / subTable$personTime + + broadSubTable <- subTable[grep(""BROAD"", subTable$exposure), c(""outcomeName"", ""exposure"", ""subgroup"", ""ir"")] + narrowSubTable <- subTable[grep(""NARROW"", subTable$exposure), c(""ir"")] + wideSubTable <- cbind(broadSubTable, narrowSubTable) + + wideSubTable$exposure <- sub(""-BROAD"", """", wideSubTable$exposure) + names(wideSubTable)[4:5] <- c(paste0(""irBroad_"", database), paste0(""irNarrow_"", database)) + + dbTable <- rbind(dbTable, wideSubTable) + } + } + if (ncol(subgroupTable) == 0) { + subgroupTable <- dbTable + } else { + subgroupTable <- cbind(subgroupTable, dbTable[, 4:5]) + } + } + mainTable <- rbind(mainTable, subgroupTable) + } + mainTable[, 4:11] <- round(mainTable[, 4:11], 2) # IRs + facs <- sapply(mainTable, is.factor) + mainTable[facs] <- lapply(mainTable[facs], as.character) + mainTable$outcomeOrder <- match(mainTable$outcomeName, c(""DKA (IP & ER)"", ""DKA (IP)"")) + mainTable$exposureOrder <- match(mainTable$exposure, unique(mainTable$exposure)) + mainTable$subgroupOrder <- match(mainTable$subgroup, unique(mainTable$subgroup)) + mainTable <- mainTable[order(mainTable$outcomeOrder, mainTable$exposureOrder, mainTable$subgroupOrder), ] + mainTable <- mainTable[, -c(12:14)] + + XLConnect::createSheet(wb, name = ""subgroups"") + header0 <- c("""", """", """", rep(databaseNames, each = 2)) + XLConnect::writeWorksheet(wb, + sheet = ""subgroups"", + data = as.data.frame(t(header0)), + startRow = 1, + startCol = 1, + rownames = FALSE, + header = FALSE) + XLConnect::mergeCells(wb, sheet = ""subgroups"", reference = ""D1:E1"") + XLConnect::mergeCells(wb, sheet = ""subgroups"", reference = ""F1:G1"") + XLConnect::mergeCells(wb, sheet = ""subgroups"", reference = ""H1:I1"") + XLConnect::mergeCells(wb, sheet = ""subgroups"", reference = ""J1:K1"") + + header1 <- c(""Outcome"", ""Exposure"", ""Subgroup"", rep(c(""Broad T2DM"", ""Narrow T2DM""), length(databaseNames))) + XLConnect::writeWorksheet(wb, + sheet = ""subgroups"", + data = as.data.frame(t(header1)), + startRow = 2, + startCol = 1, + rownames = FALSE, + header = FALSE) + + XLConnect::writeWorksheet(wb, + sheet = ""subgroups"", + data = mainTable, + startRow = 3, + startCol = 1, + rownames = FALSE, + header = FALSE) + XLConnect::mergeCells(wb, sheet = ""subgroups"", reference = ""A3:A194"") + XLConnect::mergeCells(wb, sheet = ""subgroups"", reference = ""A195:A386"") + cells <- paste0(""B"", seq(from = 3, to = 371, by = 16), "":B"", seq(from = 18, to = 386, by = 16)) + for (cell in cells) { + XLConnect::mergeCells(wb, sheet = ""subgroups"", reference = cell) + } + XLConnect::saveWorkbook(wb) +} + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/R/createIrTable.R",".R","22395","324","#' @export +createIrTable <- function(outputFolders, + databaseNames, + reportFolder, + sensitivity) { + if (sensitivity == FALSE) { + loadResultsHois <- function(outputFolder, + fileName) { + shinyDataFolder <- file.path(outputFolder, ""results"", ""shinyData"") + file <- list.files(shinyDataFolder, pattern = ""resultsHois_.*.rds"", full.names = TRUE) + x <- readRDS(file) + if (is.null(x$i2)) + x$i2 <- NA + return(x) + } + results <- lapply(outputFolders, loadResultsHois) + results <- do.call(rbind, results) + results$targetCohort <- sub(pattern = ""-90"", replacement = """", x = results$targetName) + results$comparatorCohort <- sub(pattern = ""-90"", replacement = """", x = results$comparatorName) + results$timeAtRisk[results$analysisDescription == ""Time to First Post Index Event Intent to Treat Matching""] <- ""ITT"" + results$timeAtRisk[results$analysisDescription == ""Time to First Post Index Event Per Protocol Matching""] <- ""PP"" + fileName <- file.path(reportFolder, paste0(""IRs.xlsx"")) + unlink(fileName) + } + + if (sensitivity == TRUE) { + loadIrSensitivityResults <- function(outputFolder) { + shinyDataFolder <- file.path(outputFolder, ""results"", ""irSensitivityData"") + file <- list.files(shinyDataFolder, pattern = ""irSensitivityData_.*.rds"", full.names = TRUE) + x <- readRDS(file) + return(x) + } + results <- lapply(outputFolders, loadIrSensitivityResults) + results <- do.call(rbind, results) + results$timeAtRisk <- """" + results[grep(""-60"", results$targetName), ""timeAtRisk""] <- ""PP-60"" + results[grep(""-120"", results$targetName), ""timeAtRisk""] <- ""PP-120"" + results$targetCohort <- sub(pattern = ""-60"", replacement = """", x = results$targetName) + results$targetCohort <- sub(pattern = ""-120"", replacement = """", x = results$targetCohort) + results$comparatorCohort <- sub(pattern = ""-60"", replacement = """", x = results$comparatorName) + results$comparatorCohort <- sub(pattern = ""-120"", replacement = """", x = results$comparatorCohort) + fileName <- file.path(reportFolder, paste0(""IRsSensitivity.xlsx"")) + unlink(fileName) + } + + outcomeNames <- unique(results$outcomeName) + timeAtRisks <- unique(results$timeAtRisk) + wb <- XLConnect::loadWorkbook(fileName, create = TRUE) + + subgroups <- list( + Overall = c( + ""bmTreated"", ""bmTreatedDays"", ""bmEventsTreated"", + ""bmTarTargetMean"", ""bmTarTargetSd"", ""bmTarTargetMin"", ""bmTarTargetMedian"", ""bmTarTargetMax"", + ""bmComparator"", ""bmComparatorDays"", ""bmEventsComparator"", + ""bmTarComparatorMean"", ""bmTarComparatorSd"", ""bmTarComparatorMin"", ""bmTarComparatorMedian"", ""bmTarComparatorMax""), + Male = c( + ""bmTreatedMale"", ""bmTreatedDaysMale"", ""bmEventsTreatedMale"", + ""bmTarTargetMeanMale"", ""bmTarTargetSdMale"", ""bmTarTargetMinMale"", ""bmTarTargetMedianMale"", ""bmTarTargetMaxMale"", + ""bmComparatorMale"", ""bmComparatorDaysMale"", ""bmEventsComparatorMale"", + ""bmTarComparatorMeanMale"", ""bmTarComparatorSdMale"", ""bmTarComparatorMinMale"", ""bmTarComparatorMedianMale"", ""bmTarComparatorMaxMale""), + Female = c( + ""bmTreatedFemale"", ""bmTreatedDaysFemale"", ""bmEventsTreatedFemale"", + ""bmTarTargetMeanFemale"", ""bmTarTargetSdFemale"", ""bmTarTargetMinFemale"", ""bmTarTargetMedianFemale"", ""bmTarTargetMaxFemale"", + ""bmComparatorFemale"", ""bmComparatorDaysFemale"", ""bmEventsComparatorFemale"", + ""bmTarComparatorMeanFemale"", ""bmTarComparatorSdFemale"", ""bmTarComparatorMinFemale"", ""bmTarComparatorMedianFemale"", ""bmTarComparatorMaxFemale""), + PriorInsulin = c( + ""bmTreatedPriorInsulin"", ""bmTreatedDaysPriorInsulin"", ""bmEventsTreatedPriorInsulin"", + ""bmTarTargetMeanPriorInsulin"", ""bmTarTargetSdPriorInsulin"", ""bmTarTargetMinPriorInsulin"", ""bmTarTargetMedianPriorInsulin"", ""bmTarTargetMaxPriorInsulin"", + ""bmComparatorPriorInsulin"", ""bmComparatorDaysPriorInsulin"", ""bmEventsComparatorPriorInsulin"", + ""bmTarComparatorMeanPriorInsulin"", ""bmTarComparatorSdPriorInsulin"", ""bmTarComparatorMinPriorInsulin"", ""bmTarComparatorMedianPriorInsulin"", ""bmTarComparatorMaxPriorInsulin""), + NoPriorInsulin = c( + ""bmTreatedNoPriorInsulin"", ""bmTreatedDaysNoPriorInsulin"", ""bmEventsTreatedNoPriorInsulin"", + ""bmTarTargetMeanNoPriorInsulin"", ""bmTarTargetSdNoPriorInsulin"", ""bmTarTargetMinNoPriorInsulin"", ""bmTarTargetMedianNoPriorInsulin"", ""bmTarTargetMaxNoPriorInsulin"", + ""bmComparatorNoPriorInsulin"", ""bmComparatorDaysNoPriorInsulin"", ""bmEventsComparatorNoPriorInsulin"", + ""bmTarComparatorMeanNoPriorInsulin"", ""bmTarComparatorSdNoPriorInsulin"", ""bmTarComparatorMinNoPriorInsulin"", ""bmTarComparatorMedianNoPriorInsulin"", ""bmTarComparatorMaxNoPriorInsulin""), + PriorDkaIpEr = c( + ""bmTreatedPriorDkaIpEr"", ""bmTreatedDaysPriorDkaIpEr"", ""bmEventsTreatedPriorDkaIpEr"", + ""bmTarTargetMeanPriorDkaIpEr"", ""bmTarTargetSdPriorDkaIpEr"", ""bmTarTargetMinPriorDkaIpEr"", ""bmTarTargetMedianPriorDkaIpEr"", ""bmTarTargetMaxPriorDkaIpEr"", + ""bmComparatorPriorDkaIpEr"", ""bmComparatorDaysPriorDkaIpEr"", ""bmEventsComparatorPriorDkaIpEr"", + ""bmTarComparatorMeanPriorDkaIpEr"", ""bmTarComparatorSdPriorDkaIpEr"", ""bmTarComparatorMinPriorDkaIpEr"", ""bmTarComparatorMedianPriorDkaIpEr"", ""bmTarComparatorMaxPriorDkaIpEr""), + NoPriorDkaIpEr = c( + ""bmTreatedNoPriorDkaIpEr"", ""bmTreatedDaysNoPriorDkaIpEr"", ""bmEventsTreatedNoPriorDkaIpEr"", + ""bmTarTargetMeanNoPriorDkaIpEr"", ""bmTarTargetSdNoPriorDkaIpEr"", ""bmTarTargetMinNoPriorDkaIpEr"", ""bmTarTargetMedianNoPriorDkaIpEr"", ""bmTarTargetMaxNoPriorDkaIpEr"", + ""bmComparatorNoPriorDkaIpEr"", ""bmComparatorDaysNoPriorDkaIpEr"", ""bmEventsComparatorNoPriorDkaIpEr"", + ""bmTarComparatorMeanNoPriorDkaIpEr"", ""bmTarComparatorSdNoPriorDkaIpEr"", ""bmTarComparatorMinNoPriorDkaIpEr"", ""bmTarComparatorMedianNoPriorDkaIpEr"", ""bmTarComparatorMaxNoPriorDkaIpEr""), + Age10_19 = c( + ""bmTreated1019"", ""bmTreatedDays1019"", ""bmEventsTreated1019"", + ""bmTarTargetMean1019"", ""bmTarTargetSd1019"", ""bmTarTargetMin1019"", ""bmTarTargetMedian1019"", ""bmTarTargetMax1019"", + ""bmComparator1019"", ""bmComparatorDays1019"", ""bmEventsComparator1019"", + ""bmTarComparatorMean1019"", ""bmTarComparatorSd1019"", ""bmTarComparatorMin1019"", ""bmTarComparatorMedian1019"", ""bmTarComparatorMax1019""), + Age20_29 = c( + ""bmTreated2029"", ""bmTreatedDays2029"", ""bmEventsTreated2029"", + ""bmTarTargetMean2029"", ""bmTarTargetSd2029"", ""bmTarTargetMin2029"", ""bmTarTargetMedian2029"", ""bmTarTargetMax2029"", + ""bmComparator2029"", ""bmComparatorDays2029"", ""bmEventsComparator2029"", + ""bmTarComparatorMean2029"", ""bmTarComparatorSd2029"", ""bmTarComparatorMin2029"", ""bmTarComparatorMedian2029"", ""bmTarComparatorMax2029""), + Age30_39 = c( + ""bmTreated3039"", ""bmTreatedDays3039"", ""bmEventsTreated3039"", + ""bmTarTargetMean3039"", ""bmTarTargetSd3039"", ""bmTarTargetMin3039"", ""bmTarTargetMedian3039"", ""bmTarTargetMax3039"", + ""bmComparator3039"", ""bmComparatorDays3039"", ""bmEventsComparator3039"", + ""bmTarComparatorMean3039"", ""bmTarComparatorSd3039"", ""bmTarComparatorMin3039"", ""bmTarComparatorMedian3039"", ""bmTarComparatorMax3039""), + Age40_49 = c( + ""bmTreated4049"", ""bmTreatedDays4049"", ""bmEventsTreated4049"", + ""bmTarTargetMean4049"", ""bmTarTargetSd4049"", ""bmTarTargetMin4049"", ""bmTarTargetMedian4049"", ""bmTarTargetMax4049"", + ""bmComparator4049"", ""bmComparatorDays4049"", ""bmEventsComparator4049"", + ""bmTarComparatorMean4049"", ""bmTarComparatorSd4049"", ""bmTarComparatorMin4049"", ""bmTarComparatorMedian4049"", ""bmTarComparatorMax4049""), + Age50_59 = c( + ""bmTreated5059"", ""bmTreatedDays5059"", ""bmEventsTreated5059"", + ""bmTarTargetMean5059"", ""bmTarTargetSd5059"", ""bmTarTargetMin5059"", ""bmTarTargetMedian5059"", ""bmTarTargetMax5059"", + ""bmComparator5059"", ""bmComparatorDays5059"", ""bmEventsComparator5059"", + ""bmTarComparatorMean5059"", ""bmTarComparatorSd5059"", ""bmTarComparatorMin5059"", ""bmTarComparatorMedian5059"", ""bmTarComparatorMax5059""), + Age60_69 = c( + ""bmTreated6069"", ""bmTreatedDays6069"", ""bmEventsTreated6069"", + ""bmTarTargetMean6069"", ""bmTarTargetSd6069"", ""bmTarTargetMin6069"", ""bmTarTargetMedian6069"", ""bmTarTargetMax6069"", + ""bmComparator6069"", ""bmComparatorDays6069"", ""bmEventsComparator6069"", + ""bmTarComparatorMean6069"", ""bmTarComparatorSd6069"", ""bmTarComparatorMin6069"", ""bmTarComparatorMedian6069"", ""bmTarComparatorMax6069""), + Age70_79 = c( + ""bmTreated7079"", ""bmTreatedDays7079"", ""bmEventsTreated7079"", + ""bmTarTargetMean7079"", ""bmTarTargetSd7079"", ""bmTarTargetMin7079"", ""bmTarTargetMedian7079"", ""bmTarTargetMax7079"", + ""bmComparator7079"", ""bmComparatorDays7079"", ""bmEventsComparator7079"", + ""bmTarComparatorMean7079"", ""bmTarComparatorSd7079"", ""bmTarComparatorMin7079"", ""bmTarComparatorMedian7079"", ""bmTarComparatorMax7079""), + Age80_89 = c( + ""bmTreated8089"", ""bmTreatedDays8089"", ""bmEventsTreated8089"", + ""bmTarTargetMean8089"", ""bmTarTargetSd8089"", ""bmTarTargetMin8089"", ""bmTarTargetMedian8089"", ""bmTarTargetMax8089"", + ""bmComparator8089"", ""bmComparatorDays8089"", ""bmEventsComparator8089"", + ""bmTarComparatorMean8089"", ""bmTarComparatorSd8089"", ""bmTarComparatorMin8089"", ""bmTarComparatorMedian8089"", ""bmTarComparatorMax8089""), + Age90_99 = c( + ""bmTreated9099"", ""bmTreatedDays9099"", ""bmEventsTreated9099"", + ""bmTarTargetMean9099"", ""bmTarTargetSd9099"", ""bmTarTargetMin9099"", ""bmTarTargetMedian9099"", ""bmTarTargetMax9099"", + ""bmComparator9099"", ""bmComparatorDays9099"", ""bmEventsComparator9099"", + ""bmTarComparatorMean9099"", ""bmTarComparatorSd9099"", ""bmTarComparatorMin9099"", ""bmTarComparatorMedian9099"", ""bmTarComparatorMax9099""), + Age100_109 = c( + ""bmTreated100109"", ""bmTreatedDays100109"", ""bmEventsTreated100109"", + ""bmTarTargetMean100109"", ""bmTarTargetSd100109"", ""bmTarTargetMin100109"", ""bmTarTargetMedian100109"", ""bmTarTargetMax100109"", + ""bmComparator100109"", ""bmComparatorDays100109"", ""bmEventsComparator100109"", + ""bmTarComparatorMean100109"", ""bmTarComparatorSd100109"", ""bmTarComparatorMin100109"", ""bmTarComparatorMedian100109"", ""bmTarComparatorMax100109"")) + + for (i in 1:length(subgroups)) { + mainTable <- data.frame() + cols <- subgroups[[i]] + subgroup <- names(subgroups)[i] + for (database in databaseNames) { # database <- ""mdcd"" + dbTable <- data.frame() + for (outcomeName in outcomeNames) { # outcomeName <- outcomeNames[2] + for (timeAtRisk in timeAtRisks) { # timeAtRisk <- timeAtRisks[1] + subset <- results[results$database == database & + results$outcomeName == outcomeName & + results$timeAtRisk == timeAtRisk, ] + + # Ts broad + sglt2iBroad <- subset[subset$targetCohort == ""SGLT2i-BROAD"", ][1, cols] + canaBroad <- subset[subset$targetCohort == ""Canagliflozin-BROAD"", ][1, cols] + dapaBroad <- subset[subset$targetCohort == ""Dapagliflozin-BROAD"", ][1, cols] + empaBroad <- subset[subset$targetCohort == ""Empagliflozin-BROAD"", ][1, cols] + + # Cs broad + dpp4Broad <- subset[subset$comparatorCohort == ""DPP-4i-BROAD"", ][1, cols] + glp1Broad <- subset[subset$comparatorCohort == ""GLP-1a-BROAD"", ][1, cols] + suBroad <- subset[subset$comparatorCohort == ""SU-BROAD"", ][1, cols] + tzdBroad <- subset[subset$comparatorCohort == ""TZDs-BROAD"", ][1, cols] + insulinBroad <- subset[subset$comparatorCohort == ""Insulin-BROAD"", ][1, cols] + metforminBroad <- subset[subset$comparatorCohort == ""Metformin-BROAD"", ][1, cols] + insAhasBroad <- subset[subset$comparatorCohort == ""Insulinotropic AHAs-BROAD"", ][1, cols] + otherAhasBroad <- subset[subset$comparatorCohort == ""Other AHAs-BROAD"", ][1, cols] + + # Ts narrow + sglt2iNarrow <- subset[subset$targetCohort == ""SGLT2i-NARROW"", ][1, cols] + canaNarrow <- subset[subset$targetCohort == ""Canagliflozin-NARROW"", ][1, cols] + empaNarrow <- subset[subset$targetCohort == ""Empagliflozin-NARROW"", ][1, cols] + dapaNarrow <- subset[subset$targetCohort == ""Dapagliflozin-NARROW"", ][1, cols] + + # Cs narrow + dpp4Narrow <- subset[subset$comparatorCohort == ""DPP-4i-NARROW"", ][1, cols] + glp1Narrow <- subset[subset$comparatorCohort == ""GLP-1a-NARROW"", ][1, cols] + suNarrow <- subset[subset$comparatorCohort == ""SU-NARROW"", ][1, cols] + tzdNarrow <- subset[subset$comparatorCohort == ""TZDs-NARROW"", ][1, cols] + insulinNarrow <- subset[subset$comparatorCohort == ""Insulin-NARROW"", ][1, cols] + metforminNarrow <- subset[subset$comparatorCohort == ""Metformin-NARROW"", ][1, cols] + insAhasNarrow <- subset[subset$comparatorCohort == ""Insulinotropic AHAs-NARROW"", ][1, cols] + otherAhasNarrow <- subset[subset$comparatorCohort == ""Other AHAs-NARROW"", ][1, cols] + + subTable <- data.frame(outcomeName = outcomeName, + timeAtRisk = timeAtRisk, + exposure = c( + ""SGLT2i-BROAD"", ""Canagliflozin-BROAD"", ""Dapagliflozin-BROAD"", ""Empagliflozin-BROAD"", + ""DPP-4i-BROAD"", ""GLP-1a-BROAD"", ""SU-BROAD"", ""TZDs-BROAD"", + ""Insulin-BROAD"", ""Metformin-BROAD"", ""Insulinotropic AHAs-BROAD"", ""Other AHAs-BROAD"", + + ""SGLT2i-NARROW"", ""Canagliflozin-NARROW"", ""Dapagliflozin-NARROW"", ""Empagliflozin-NARROW"", + ""DPP-4i-NARROW"", ""GLP-1a-NARROW"", ""SU-NARROW"", ""TZDs-NARROW"", + ""Insulin-NARROW"", ""Metformin-NARROW"", ""Insulinotropic AHAs-NARROW"", ""Other AHAs-NARROW""), + + subjects = c( + sglt2iBroad[, 1], canaBroad[, 1], dapaBroad[, 1], empaBroad[, 1], + dpp4Broad[, 9], glp1Broad[, 9], suBroad[, 9], tzdBroad[, 9], + insulinBroad[, 9], metforminBroad[, 9], insAhasBroad[, 9], otherAhasBroad[, 9], + + sglt2iNarrow[, 1], canaNarrow[, 1], dapaNarrow[, 1], empaNarrow[, 1], + dpp4Narrow[, 9], glp1Narrow[, 9], suNarrow[, 9], tzdNarrow[, 9], + insulinNarrow[, 9], metforminNarrow[, 9], insAhasNarrow[, 9], otherAhasNarrow[, 9]), + + personTime = c( + sglt2iBroad[, 2], canaBroad[, 2], dapaBroad[, 2], empaBroad[, 2], + dpp4Broad[, 10], glp1Broad[, 10], suBroad[, 10], tzdBroad[, 10], + insulinBroad[, 10], metforminBroad[, 10], insAhasBroad[, 10], otherAhasBroad[, 10], + + sglt2iNarrow[, 2], canaNarrow[, 2], dapaNarrow[, 2], empaNarrow[, 2], + dpp4Narrow[, 10], glp1Narrow[, 10], suNarrow[, 10], tzdNarrow[, 10], + insulinNarrow[, 10], metforminNarrow[, 10], insAhasNarrow[, 10], otherAhasNarrow[, 10]) / 365.25, + + meanPersonTime = c( + sglt2iBroad[, 4], canaBroad[, 4], dapaBroad[, 4], empaBroad[, 4], + dpp4Broad[, 12], glp1Broad[, 12], suBroad[, 12], tzdBroad[, 12], + insulinBroad[, 12], metforminBroad[, 12], insAhasBroad[, 12], otherAhasBroad[, 12], + + sglt2iNarrow[, 4], canaNarrow[, 4], dapaNarrow[, 4], empaNarrow[, 4], + dpp4Narrow[, 12], glp1Narrow[, 12], suNarrow[, 12], tzdNarrow[, 12], + insulinNarrow[, 12], metforminNarrow[, 12], insAhasNarrow[, 12], otherAhasNarrow[, 12]) / 365.25, + + sdPersonTime = c( + sglt2iBroad[, 5], canaBroad[, 5], dapaBroad[, 5], empaBroad[, 5], + dpp4Broad[, 13], glp1Broad[, 13], suBroad[, 13], tzdBroad[, 13], + insulinBroad[, 13], metforminBroad[, 13], insAhasBroad[, 13], otherAhasBroad[, 13], + + sglt2iNarrow[, 5], canaNarrow[, 5], dapaNarrow[, 5], empaNarrow[, 5], + dpp4Narrow[, 13], glp1Narrow[, 13], suNarrow[, 13], tzdNarrow[, 13], + insulinNarrow[, 13], metforminNarrow[, 13], insAhasNarrow[, 13], otherAhasNarrow[, 13]) / 365.25, + + minPersonTime = c( + sglt2iBroad[, 6], canaBroad[, 6], dapaBroad[, 6], empaBroad[, 6], + dpp4Broad[, 14], glp1Broad[, 14], suBroad[, 14], tzdBroad[, 14], + insulinBroad[, 14], metforminBroad[, 14], insAhasBroad[, 14], otherAhasBroad[, 14], + + sglt2iNarrow[, 6], canaNarrow[, 6], dapaNarrow[, 6], empaNarrow[, 6], + dpp4Narrow[, 14], glp1Narrow[, 14], suNarrow[, 14], tzdNarrow[, 14], + insulinNarrow[, 14], metforminNarrow[, 14], insAhasNarrow[, 14], otherAhasNarrow[, 14]) / 365.25, + + medianPersonTime = c( + sglt2iBroad[, 7], canaBroad[, 7], dapaBroad[, 7], empaBroad[, 7], + dpp4Broad[, 15], glp1Broad[, 15], suBroad[, 15], tzdBroad[, 15], + insulinBroad[, 15], metforminBroad[, 15], insAhasBroad[, 15], otherAhasBroad[, 15], + + sglt2iNarrow[, 7], canaNarrow[, 7], dapaNarrow[, 7], empaNarrow[, 7], + dpp4Narrow[, 15], glp1Narrow[, 15], suNarrow[, 15], tzdNarrow[, 15], + insulinNarrow[, 15], metforminNarrow[, 15], insAhasNarrow[, 15], otherAhasNarrow[, 15]) / 365.25, + + maxPersonTime = c( + sglt2iBroad[, 8], canaBroad[, 8], dapaBroad[, 8], empaBroad[, 8], + dpp4Broad[, 16], glp1Broad[, 16], suBroad[, 16], tzdBroad[, 16], + insulinBroad[, 16], metforminBroad[, 16], insAhasBroad[, 16], otherAhasBroad[, 16], + + sglt2iNarrow[, 8], canaNarrow[, 8], dapaNarrow[, 8], empaNarrow[, 8], + dpp4Narrow[, 16], glp1Narrow[, 16], suNarrow[, 16], tzdNarrow[, 16], + insulinNarrow[, 16], metforminNarrow[, 16], insAhasNarrow[, 16], otherAhasNarrow[, 16]) / 365.25, + + events = c( + sglt2iBroad[, 3], canaBroad[, 3], dapaBroad[, 3], empaBroad[, 3], + dpp4Broad[, 11], glp1Broad[, 11], suBroad[, 11], tzdBroad[, 11], + insulinBroad[, 11], metforminBroad[, 11], insAhasBroad[, 11], otherAhasBroad[, 11], + + sglt2iNarrow[, 3], canaNarrow[, 3], dapaNarrow[, 3], empaNarrow[, 3], + dpp4Narrow[, 11], glp1Narrow[, 11], suNarrow[, 11], tzdNarrow[, 11], + insulinNarrow[, 11], metforminNarrow[, 11], insAhasNarrow[, 11], otherAhasNarrow[, 11])) + + subTable$ir <- 1000 * subTable$events / subTable$personTime + dbTable <- rbind(dbTable, subTable) + } + } + colnames(dbTable)[4:12] <- paste(colnames(dbTable)[4:12], database, sep = ""_"") + if (ncol(mainTable) == 0) { + mainTable <- dbTable + } else { + if (!all.equal(mainTable$outcomeName, dbTable$outcomeName) || + !all.equal(mainTable$timeAtRisk, dbTable$timeAtRisk) || + !all.equal(mainTable$exposure, dbTable$exposure)) { + stop(""Something wrong with data ordering"") + } + mainTable <- cbind(mainTable, dbTable[, 4:12]) + } + } + mainTable[, c(5, 14, 23, 32)] <- round(mainTable[, c(5, 14, 23, 32)], 0) # total person years + mainTable[, c(6:10, 15:19, 24:28, 33:37)] <- round(mainTable[, c(6:10, 15:19, 24:28, 33:37)], 1) # stats person years + mainTable[, c(12, 21, 30, 39)] <- round(mainTable[, c(12, 21, 30, 39)], 1) # IRs + + XLConnect::createSheet(wb, name = subgroup) + header0 <- c("""", """", """", rep(databaseNames, each = 9)) + XLConnect::writeWorksheet(wb, + sheet = subgroup, + data = as.data.frame(t(header0)), + startRow = 1, + startCol = 1, + rownames = FALSE, + header = FALSE) + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""D1:L1"") + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""M1:U1"") + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""V1:AD1"") + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""AE1:AM1"") + header1 <- c(""Outcome"", + ""Time-at-risk"", + ""Exposure"", + rep(c(""Persons"", ""PY total"", ""PY mean"", ""PY SD"", ""PY min"", ""PY med"", ""PY max"", ""Events"", ""IR""), length(databaseNames))) + XLConnect::writeWorksheet(wb, + sheet = subgroup, + data = as.data.frame(t(header1)), + startRow = 2, + startCol = 1, + rownames = FALSE, + header = FALSE) + XLConnect::writeWorksheet(wb, + sheet = subgroup, + data = mainTable, + startRow = 3, + startCol = 1, + rownames = FALSE, + header = FALSE) + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""A3:A50"") + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""B3:B26"") + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""B27:B50"") + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""A51:A98"") + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""B51:B74"") + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""B75:B98"") + } + XLConnect::saveWorkbook(wb) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/R/createIrSensitivityTableFormatted.R",".R","12170","210","#' @export +createIrSensitivityTableFormatted <- function(outputFolders, + databaseNames, + reportFolder) { + + loadResultsHois <- function(outputFolder, + fileName) { + shinyDataFolder <- file.path(outputFolder, ""results"", ""shinyData"") + file <- list.files(shinyDataFolder, pattern = ""resultsHois_.*.rds"", full.names = TRUE) + x <- readRDS(file) + if (is.null(x$i2)) + x$i2 <- NA + return(x) + } + resultsITT90 <- lapply(outputFolders, loadResultsHois) + resultsITT90 <- do.call(rbind, resultsITT90) + resultsITT90$targetCohort <- sub(pattern = ""-90"", replacement = """", x = resultsITT90$targetName) + resultsITT90$comparatorCohort <- sub(pattern = ""-90"", replacement = """", x = resultsITT90$comparatorName) + resultsITT90$timeAtRisk[resultsITT90$analysisDescription == ""Time to First Post Index Event Per Protocol Matching""] <- ""90day"" + resultsITT90$timeAtRisk[resultsITT90$analysisDescription == ""Time to First Post Index Event Intent to Treat Matching""] <- ""ITT"" + + loadIrSensitivityResults <- function(outputFolder) { + shinyDataFolder <- file.path(outputFolder, ""results"", ""irSensitivityData"") + file <- list.files(shinyDataFolder, pattern = ""irSensitivityData_.*.rds"", full.names = TRUE) + x <- readRDS(file) + return(x) + } + results60120 <- lapply(outputFolders, loadIrSensitivityResults) + results60120 <- do.call(rbind, results60120) + results60120$timeAtRisk <- """" + results60120[grep(""-60"", results60120$targetName), ""timeAtRisk""] <- ""60day"" + results60120[grep(""-120"", results60120$targetName), ""timeAtRisk""] <- ""120day"" + results60120$targetCohort <- sub(pattern = ""-60"", replacement = """", x = results60120$targetName) + results60120$targetCohort <- sub(pattern = ""-120"", replacement = """", x = results60120$targetCohort) + results60120$comparatorCohort <- sub(pattern = ""-60"", replacement = """", x = results60120$comparatorName) + results60120$comparatorCohort <- sub(pattern = ""-120"", replacement = """", x = results60120$comparatorCohort) + + dropCols <- names(resultsITT90) %in% setdiff(names(resultsITT90), names(results60120)) + resultsITT90 <- resultsITT90[!dropCols] + resultsITT6090120 <- rbind(resultsITT90, results60120) + + outcomeNames <- unique(resultsITT6090120$outcomeName) + timeAtRisks <- unique(resultsITT6090120$timeAtRisk) + + fileName <- file.path(reportFolder, paste0(""IRsSensitivityFormatted.xlsx"")) + unlink(fileName) + wb <- XLConnect::loadWorkbook(fileName, create = TRUE) + + subgroups <- list( + Overall = c( + ""bmTreated"", ""bmTreatedDays"", ""bmEventsTreated"", + ""bmTarTargetMean"", ""bmTarTargetSd"", ""bmTarTargetMin"", ""bmTarTargetMedian"", ""bmTarTargetMax"", + ""bmComparator"", ""bmComparatorDays"", ""bmEventsComparator"", + ""bmTarComparatorMean"", ""bmTarComparatorSd"", ""bmTarComparatorMin"", ""bmTarComparatorMedian"", ""bmTarComparatorMax"")) + + for (i in 1:length(subgroups)) { # i=1 + cols <- subgroups[[i]] + subgroup <- names(subgroups)[i] + mainTable <- data.frame() + for (database in databaseNames) { # database <- ""CCAE"" + outcomeTable <- data.frame() + for (outcomeName in outcomeNames) { # outcomeName <- outcomeNames[2] + tarTable <- data.frame() + for (timeAtRisk in timeAtRisks) { # timeAtRisk <- timeAtRisks[1] + subset <- resultsITT6090120[resultsITT6090120$database == database & + resultsITT6090120$outcomeName == outcomeName & + resultsITT6090120$timeAtRisk == timeAtRisk, ] + + # Ts broad + sglt2iBroad <- subset[subset$targetCohort == ""SGLT2i-BROAD"", ][1, cols] + canaBroad <- subset[subset$targetCohort == ""Canagliflozin-BROAD"", ][1, cols] + dapaBroad <- subset[subset$targetCohort == ""Dapagliflozin-BROAD"", ][1, cols] + empaBroad <- subset[subset$targetCohort == ""Empagliflozin-BROAD"", ][1, cols] + + # Cs broad + dpp4Broad <- subset[subset$comparatorCohort == ""DPP-4i-BROAD"", ][1, cols] + glp1Broad <- subset[subset$comparatorCohort == ""GLP-1a-BROAD"", ][1, cols] + suBroad <- subset[subset$comparatorCohort == ""SU-BROAD"", ][1, cols] + tzdBroad <- subset[subset$comparatorCohort == ""TZDs-BROAD"", ][1, cols] + insulinBroad <- subset[subset$comparatorCohort == ""Insulin-BROAD"", ][1, cols] + metforminBroad <- subset[subset$comparatorCohort == ""Metformin-BROAD"", ][1, cols] + insAhasBroad <- subset[subset$comparatorCohort == ""Insulinotropic AHAs-BROAD"", ][1, cols] + otherAhasBroad <- subset[subset$comparatorCohort == ""Other AHAs-BROAD"", ][1, cols] + + # Ts narrow + sglt2iNarrow <- subset[subset$targetCohort == ""SGLT2i-NARROW"", ][1, cols] + canaNarrow <- subset[subset$targetCohort == ""Canagliflozin-NARROW"", ][1, cols] + empaNarrow <- subset[subset$targetCohort == ""Empagliflozin-NARROW"", ][1, cols] + dapaNarrow <- subset[subset$targetCohort == ""Dapagliflozin-NARROW"", ][1, cols] + + # Cs narrow + dpp4Narrow <- subset[subset$comparatorCohort == ""DPP-4i-NARROW"", ][1, cols] + glp1Narrow <- subset[subset$comparatorCohort == ""GLP-1a-NARROW"", ][1, cols] + suNarrow <- subset[subset$comparatorCohort == ""SU-NARROW"", ][1, cols] + tzdNarrow <- subset[subset$comparatorCohort == ""TZDs-NARROW"", ][1, cols] + insulinNarrow <- subset[subset$comparatorCohort == ""Insulin-NARROW"", ][1, cols] + metforminNarrow <- subset[subset$comparatorCohort == ""Metformin-NARROW"", ][1, cols] + insAhasNarrow <- subset[subset$comparatorCohort == ""Insulinotropic AHAs-NARROW"", ][1, cols] + otherAhasNarrow <- subset[subset$comparatorCohort == ""Other AHAs-NARROW"", ][1, cols] + + subTable <- data.frame(outcomeName = outcomeName, + exposure = c( + ""SGLT2i-BROAD"", ""Canagliflozin-BROAD"", ""Dapagliflozin-BROAD"", ""Empagliflozin-BROAD"", + ""DPP-4i-BROAD"", ""GLP-1a-BROAD"", ""SU-BROAD"", ""TZDs-BROAD"", + ""Insulin-BROAD"", ""Metformin-BROAD"", ""Insulinotropic AHAs-BROAD"", ""Other AHAs-BROAD"", + + ""SGLT2i-NARROW"", ""Canagliflozin-NARROW"", ""Dapagliflozin-NARROW"", ""Empagliflozin-NARROW"", + ""DPP-4i-NARROW"", ""GLP-1a-NARROW"", ""SU-NARROW"", ""TZDs-NARROW"", + ""Insulin-NARROW"", ""Metformin-NARROW"", ""Insulinotropic AHAs-NARROW"", ""Other AHAs-NARROW""), + + database = database, + + personTime = c( + sglt2iBroad[, 2], canaBroad[, 2], dapaBroad[, 2], empaBroad[, 2], + dpp4Broad[, 10], glp1Broad[, 10], suBroad[, 10], tzdBroad[, 10], + insulinBroad[, 10], metforminBroad[, 10], insAhasBroad[, 10], otherAhasBroad[, 10], + + sglt2iNarrow[, 2], canaNarrow[, 2], dapaNarrow[, 2], empaNarrow[, 2], + dpp4Narrow[, 10], glp1Narrow[, 10], suNarrow[, 10], tzdNarrow[, 10], + insulinNarrow[, 10], metforminNarrow[, 10], insAhasNarrow[, 10], otherAhasNarrow[, 10]) / 365.25, + + events = c( + sglt2iBroad[, 3], canaBroad[, 3], dapaBroad[, 3], empaBroad[, 3], + dpp4Broad[, 11], glp1Broad[, 11], suBroad[, 11], tzdBroad[, 11], + insulinBroad[, 11], metforminBroad[, 11], insAhasBroad[, 11], otherAhasBroad[, 11], + + sglt2iNarrow[, 3], canaNarrow[, 3], dapaNarrow[, 3], empaNarrow[, 3], + dpp4Narrow[, 11], glp1Narrow[, 11], suNarrow[, 11], tzdNarrow[, 11], + insulinNarrow[, 11], metforminNarrow[, 11], insAhasNarrow[, 11], otherAhasNarrow[, 11])) + + subTable$ir <- 1000 * subTable$events / subTable$personTime + + broadSubTable <- subTable[grep(""BROAD"", subTable$exposure), c(""outcomeName"", ""exposure"", ""database"", ""ir"")] + narrowSubTable <- subTable[grep(""NARROW"", subTable$exposure), ""ir""] + wideSubTable <- cbind(broadSubTable, narrowSubTable) + wideSubTable$exposure <- sub(""-BROAD"", """", wideSubTable$exposure) + names(wideSubTable)[4:5] <- c(paste0(""irBroad_"", timeAtRisk), paste0(""irNarrow_"", timeAtRisk)) + + if (ncol(tarTable) == 0) { + tarTable <- wideSubTable + } else { + tarTable <- cbind(tarTable, wideSubTable[, 4:5]) + } + } + outcomeTable <- rbind(outcomeTable, tarTable) + } + mainTable <- rbind(mainTable, outcomeTable) + } + + facs <- sapply(mainTable, is.factor) + mainTable[facs] <- lapply(mainTable[facs], as.character) + mainTable[, 4:11] <- round(mainTable[, 4:11], 2) # IRs + mainTable$outcomeOrder <- match(mainTable$outcomeName, c(""DKA (IP)"", ""DKA (IP & ER)"")) + mainTable$dbOrder <- match(mainTable$database, c(""CCAE"", ""MDCD"", ""MDCR"", ""Optum"")) + mainTable$exposureOrder <- match(mainTable$exposure, c(""SGLT2i"", + ""Canagliflozin"", + ""Dapagliflozin"", + ""Empagliflozin"", + ""SU"", + ""DPP-4i"", + ""GLP-1a"", + ""TZDs"", + ""Insulin"", + ""Metformin"", + ""Insulinotropic AHAs"", + ""Other AHAs"")) + mainTable <- mainTable[order(mainTable$outcomeOrder, mainTable$exposureOrder, mainTable$dbOrder), ] + mainTable <- mainTable[, -c(12:14)] + mainTable <- mainTable[, c(""outcomeName"", ""exposure"", ""database"", + ""irBroad_ITT"", ""irBroad_90day"", ""irBroad_60day"", ""irBroad_120day"", + ""irNarrow_ITT"", ""irNarrow_90day"", ""irNarrow_60day"", ""irNarrow_120day"")] + + XLConnect::createSheet(wb, name = subgroup) + header0 <- c("""", """", """", rep(""Broad T2DM"", 4), rep(""Narrow T2DM"", 4)) + XLConnect::writeWorksheet(wb, + sheet = subgroup, + data = as.data.frame(t(header0)), + startRow = 1, + startCol = 1, + rownames = FALSE, + header = FALSE) + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""D1:G1"") + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""H1:K1"") + + header1 <- c(""Outcome"", ""Exposure"", ""Database"", rep(c(""ITT"", ""90 day"", ""60 day"", ""120 day""), 2)) + XLConnect::writeWorksheet(wb, + sheet = subgroup, + data = as.data.frame(t(header1)), + startRow = 2, + startCol = 1, + rownames = FALSE, + header = FALSE) + + XLConnect::writeWorksheet(wb, + sheet = subgroup, + data = mainTable, + startRow = 3, + startCol = 1, + rownames = FALSE, + header = FALSE) + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""A3:A50"") + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""A51:A98"") + cells <- paste0(""B"", seq(from = 3, to = 95, by = 4), "":B"", seq(from = 6, to = 98, by = 4)) + for (cell in cells) { + XLConnect::mergeCells(wb, sheet = subgroup, reference = cell) + } + } + XLConnect::saveWorkbook(wb) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/R/createKmPlotPanels.R",".R","4035","106"," + +#' Create 2x2 KM Plot Panels using existing KM plot RDS files +#' +#' @param rdsPath The path to the already generated KM plots stored as RDS files +#' @param cdmDatabaseSchemas A list of CDM names +#' @param tcos (OPTIONAL) A list of Target-Comparator-Outcome lists. By default, run the createTcos function. +#' @param cohorts (OPTIONAL) A data frame of the cohort universe. By default, read the CohortUniverse CSV file. +#' @param outcomes (OPTIONAL) A data frame of outcome cohorts (""id"" and ""name"" are the fields). By default, this is auto-generated. +#' +#' @export +createKmPlotPanels <- function(rdsPath, + cdmDatabaseSchemas, + tcos = NULL, + cohorts = NULL, + outcomes = NULL) { + + if (!dir.exists(""kmPanels"")) { + dir.create(""kmPanels"") + } + + if (missing(tcos)) { + tcos <- createTcos() + } + if (missing(cohorts)) { + cohorts <- read.csv(system.file(""settings"", ""cohortUniverse.csv"", package = ""sglt2iDka""), stringsAsFactors = FALSE) + } + + if (missing(outcomes)) { + outcomes <- data.frame( + id = c(200, 201), + name = c(""DKA (IP & ER)"", ""DKA (IP)"") + ) + } + + # for each analysis, go through TC-pairs and their outcomes to then obtain the associated RDS file + for (analysis in c(1:2)) { + for (tco in tcos) { + for (outcomeId in outcomes$id) { + grobs <- lapply(cdmDatabaseSchemas, function(cdmDb) { + + rdsFilePath <- file.path(rdsPath, sprintf(""km_a%1d_t%2d_c%3d_o%4d_%1s.rds"", + analysis, + tco$targetId, + tco$comparatorId, + outcomeId, + cdmDb)) + rdsFilePath <- gsub(pattern = "" "", replacement = """", x = rdsFilePath) + writeLines(rdsFilePath) + + if (file.exists(rdsFilePath)) { + + # the file exists, format it + + thisRds <- readRDS(rdsFilePath) + + title <- textGrob(cdmDb, gp = gpar(fontsize = 12, fontface = ""bold"")) + padding <- grid::unit(x = 1, units = ""line"") + + thisPlot <- gtable::gtable_add_rows(x = thisRds, heights = grobHeight(title) + padding, pos = 0) + thisPlot <- gtable::gtable_add_grob(thisPlot, title, t = 1, l = 1, r = ncol(thisPlot)) + } else { + thisPlot <- NULL + } + + thisPlot + }) + + # only grab non-null plots + grobs <- grobs[!sapply(grobs, is.null)] + + + # create the new panel image file path + panelPath <- sprintf(""kmPanels/km_a%1d_t%2d_c%3d_o%4d.png"", + analysis, + tco$targetId, + tco$comparatorId, + outcomeId) + panelPath <- gsub(pattern = "" "", replacement = """", x = panelPath) + + # format the panel plot and save it + titleText <- sprintf(""%1s vs %2s: %3s"", + gsub(pattern = ""-90"", replacement = """", x = cohorts$FULL_NAME[cohorts$COHORT_DEFINITION_ID == tco$targetId]), + gsub(pattern = ""-90"", replacement = """", x = cohorts$FULL_NAME[cohorts$COHORT_DEFINITION_ID == tco$comparatorId]), + outcomes$name[outcomes$id == outcomeId]) + + gridTitle <- textGrob(titleText, gp = gpar(fontface = ""bold"")) + + plotGrid <- do.call(""grid.arrange"", c(grobs, ncol = 2)) + + padding <- grid::unit(x = 1, units = ""line"") + plotGrid <- gtable::gtable_add_rows(x = plotGrid, heights = grobHeight(gridTitle) + padding, pos = 0) + plotGrid <- gtable::gtable_add_grob(plotGrid, gridTitle, t = 1, l = 1, r = ncol(plotGrid)) + + ggplot2::ggsave(filename = panelPath, plot = plotGrid, + width = 14, height = 18) + + + } + } + } +} + + + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/R/Diagnostics.R",".R","15071","274","#' @export +generateDiagnostics <- function(outputFolder, + databaseName) { + + packageName <- ""sglt2iDka"" + modelType <- ""cox"" # For MDRR computation + psStrategy <- ""matching"" # For covariate balance labels + + cmOutputFolder <- file.path(outputFolder, ""cmOutput"") + diagnosticsFolder <- file.path(outputFolder, ""diagnostics"") + if (!file.exists(diagnosticsFolder)) + dir.create(diagnosticsFolder) + + tcosAnalyses <- read.csv(system.file(""settings"", ""tcoAnalysisVariants.csv"", package = ""sglt2iDka""), stringsAsFactors = FALSE) + tcosOfInterest <- unique(tcosAnalyses[, c(""targetCohortId"", ""targetDrugName"", ""targetCohortName"", ""comparatorCohortId"", ""comparatorDrugName"", ""comparatorCohortName"", + ""outcomeCohortId"", ""outcomeCohortName"")]) + names(tcosOfInterest) <- c(""targetId"", ""targetDrugName"", ""targetName"", ""comparatorId"", ""comparatorDrugName"", ""comparatorName"", + ""outcomeId"", ""outcomeName"") + + reference <- readRDS(file.path(cmOutputFolder, ""outcomeModelReference.rds"")) + analysisSummary <- CohortMethod::summarizeAnalyses(reference) + analysisSummary <- addCohortNames(analysisSummary, dose = FALSE, ""targetId"", ""targetName"") + analysisSummary <- addCohortNames(analysisSummary, dose = FALSE, ""comparatorId"", ""comparatorName"") + analysisSummary <- addCohortNames(analysisSummary, dose = FALSE, ""outcomeId"", ""outcomeName"") + cmAnalysisList <- CohortMethod::loadCmAnalysisList(system.file(""settings"", ""cmAnalysisList.json"", package = packageName)) + analyses <- data.frame(analysisId = unique(reference$analysisId), + analysisDescription = """", + stringsAsFactors = FALSE) + for (i in 1:length(cmAnalysisList)) { + analyses$analysisDescription[analyses$analysisId == cmAnalysisList[[i]]$analysisId] <- cmAnalysisList[[i]]$description + } + analysisSummary <- merge(analysisSummary, analyses) + + negativeControlOutcomeCohorts <- read.csv(system.file(""settings"", ""negativeControlOutcomeCohorts.csv"", package = ""sglt2iDka""), stringsAsFactors = FALSE) + negativeControlOutcomeCohortIds <- negativeControlOutcomeCohorts$COHORT_DEFINITION_ID + outcomeIds <- unique(tcosOfInterest$outcomeId) + outcomeNames <- unique(tcosOfInterest$outcomeName) + + mdrrs <- data.frame() + mdrrsFileName <- file.path(diagnosticsFolder, ""mdrr.csv"") + hetergeneityOfEffect <- data.frame() + hetergeneityOfEffectFileName <- file.path(diagnosticsFolder, ""effectHeterogeneity.csv"") + models <- data.frame() + modelsFileName <- file.path(diagnosticsFolder, ""propensityModels.csv"") + + tcsOfInterest <- unique(tcosOfInterest[, c(""targetId"", ""comparatorId"")]) + for (i in 1:nrow(tcsOfInterest)) { + # i=1 + + targetId <- tcsOfInterest$targetId[i] + comparatorId <- tcsOfInterest$comparatorId[i] + idx <- which(tcosOfInterest$targetId == targetId & tcosOfInterest$comparatorId == comparatorId)[1] + targetLabel <- tcosOfInterest$targetName[idx] + comparatorLabel <- tcosOfInterest$comparatorName[idx] + + for (analysisId in unique(reference$analysisId)) { + # analysisId=1 + + analysisDescription <- analyses$analysisDescription[analyses$analysisId == analysisId] + negControlSubset <- analysisSummary[analysisSummary$targetId == targetId & + analysisSummary$comparatorId == comparatorId & + analysisSummary$outcomeId %in% negativeControlOutcomeCohortIds & + analysisSummary$analysisId == analysisId, ] + label <- ""OutcomeControls"" + validNcs <- sum(!is.na(negControlSubset$seLogRr)) + + # calibration plots + if (validNcs < 5) { + null <- NULL + } else { + fileName <- file.path(diagnosticsFolder, paste0(""nullDistribution_a"", analysisId, + ""_t"", targetId, + ""_c"", comparatorId, + ""_"", label, + "".png"")) + if (!file.exists(fileName)) { + null <- EmpiricalCalibration::fitMcmcNull(negControlSubset$logRr, negControlSubset$seLogRr) + plot <- EmpiricalCalibration::plotCalibrationEffect(logRrNegatives = negControlSubset$logRr, + seLogRrNegatives = negControlSubset$seLogRr, + null = null, + showCis = TRUE) + title <- paste(targetLabel, comparatorLabel, sep = "" vs.\n"") + plot <- plot + ggplot2::ggtitle(title) + plot <- plot + ggplot2::theme(plot.title = ggplot2::element_text(colour = ""#000000"", size = 10, hjust = 0.5)) + ggplot2::ggsave(fileName, plot, width = 6, height = 5, dpi = 400) + } + } + + refDataQuintilEffects <- data.frame() + for (outcomeId in outcomeIds) { + # outcomeId=200 + + outcomeName <- outcomeNames[outcomeIds == outcomeId] + strataFile <- reference$strataFile[reference$analysisId == analysisId & + reference$targetId == targetId & + reference$comparatorId == comparatorId & + reference$outcomeId == outcomeId] + population <- readRDS(strataFile) + + # compute MDRR + if (!file.exists(mdrrsFileName)) { + mdrr <- CohortMethod::computeMdrr(population, alpha = 0.05, power = 0.8, twoSided = TRUE, modelType = modelType) + mdrr$targetId <- targetId + mdrr$targetName <- targetLabel + mdrr$comparatorId <- comparatorId + mdrr$comparatorName <- comparatorLabel + mdrr$outcomeId <- outcomeId + mdrr$outcomeName <- outcomeName + mdrr$analysisId <- mdrr$analysisId + mdrr$analysisDescription <- analysisDescription + mdrrs <- rbind(mdrrs, mdrr) + } + + # heterogeneity of effect across PS quintiles + if (!file.exists(hetergeneityOfEffectFileName)) { + refData <- data.frame(analysisId = 0, + analysisDescription = """", + outcomeId = 0, + outcomeName = """", + targetId = 0, + targetName = """", + comparatorId = 0, + comparatorName = """", + database = """") + refData$analysisId <- analysisId + refData$analysisDescription <- analysisDescription + refData$outcomeId <- outcomeId + refData$outcomeName <- outcomeName + refData$targetId <- targetId + refData$targetName <- targetLabel + refData$comparatorId <- comparatorId + refData$comparatorName <- comparatorLabel + refData$database <- databaseName + + stratifiedPopulation <- CohortMethod::stratifyByPs(population = population, numberOfStrata = 5, baseSelection = ""all"") + quintileEffects <- data.frame() + for (quintile in 1:5) { + outcomeModel <- CohortMethod::fitOutcomeModel(population = stratifiedPopulation[stratifiedPopulation$stratumId == quintile, ], + modelType = ""cox"", + stratified = FALSE, + useCovariates = FALSE, + control = Cyclops::createControl(noiseLevel = ""quiet"")) + quintileEffect <- sglt2iDka::summarizeOneAnalysis(outcomeModel) + quintileEffect$quintile <- quintile + quintileEffects <- rbind(quintileEffects, quintileEffect) + } + refDataQuintilEffects <- merge(refData, quintileEffects) + hetergeneityOfEffect <- rbind(hetergeneityOfEffect, refDataQuintilEffects) + } + + # KM plots + fileName <- file.path(diagnosticsFolder, paste0(""km_a"", analysisId, + ""_t"", targetId, + ""_c"", comparatorId, + ""_o"", outcomeId, + "".png"")) + if (!file.exists(fileName)) { + plot <- sglt2iDka::plotKaplanMeier(population = population, + targetLabel = targetLabel, + comparatorLabel = comparatorLabel, + fileName = fileName) + } + } + + exampleRef <- reference[reference$analysisId == analysisId & + reference$targetId == targetId & + reference$comparatorId == comparatorId & + reference$outcomeId == outcomeIds[1], ] + + ps <- readRDS(exampleRef$sharedPsFile) + psAfterMatching <- readRDS(exampleRef$strataFile) + cmData <- CohortMethod::loadCohortMethodData(exampleRef$cohortMethodDataFolder) + + # preference score plots + fileName <- file.path(diagnosticsFolder, paste0(""psBefore"", psStrategy, + ""_a"",analysisId, + ""_t"",targetId, + ""_c"",comparatorId, + "".png"")) + if (!file.exists(fileName)) { + plot <- CohortMethod::plotPs(data = ps, + treatmentLabel = targetLabel, + comparatorLabel = comparatorLabel) + plot <- plot + ggplot2::theme(legend.title = ggplot2::element_blank(), legend.position = ""top"", legend.direction = ""vertical"") + ggplot2::ggsave(fileName, plot, width = 3.5, height = 4, dpi = 400) + } + + # follow-up distribution plots + fileName <- file.path(diagnosticsFolder, paste0(""followupDist_a"", analysisId, + ""_t"", targetId, + ""_c"", comparatorId, + "".png"")) + if (!file.exists(fileName)) { + plot <- CohortMethod::plotFollowUpDistribution(psAfterMatching, + targetLabel = targetLabel, + comparatorLabel = comparatorLabel, + title = NULL) + plot <- plot + ggplot2::theme(legend.title = ggplot2::element_blank(), legend.position = ""top"", legend.direction = ""vertical"") + ggplot2::ggsave(fileName, plot, width = 4, height = 3.5, dpi = 400) + } + + # propensity score models + if (!file.exists(modelsFileName)) { + model <- CohortMethod::getPsModel(ps, cmData) + model$targetId <- targetId + model$targetName <- targetLabel + model$comparatorId <- comparatorId + model$comparatorName <- comparatorLabel + model$analysisId <- mdrr$analysisId + model$analysisDescription <- analysisDescription + models <- rbind(models, model) + } + + # index date visualization + fileName <- file.path(diagnosticsFolder, paste0(""index_date_a"", analysisId, + ""_t"", targetId, + ""_c"", comparatorId, + "".png"")) + if (!file.exists(fileName)) { + cohorts <- cmData$cohorts + cohorts$group <- targetLabel + cohorts$group[cohorts$treatment == 0] <- comparatorLabel + plot <- ggplot2::ggplot(cohorts, ggplot2::aes(x = cohortStartDate, color = group, fill = group, group = group)) + + ggplot2::geom_density(alpha = 0.5) + + ggplot2::xlab(""Cohort start date"") + + ggplot2::ylab(""Density"") + + ggplot2::theme(legend.title = ggplot2::element_blank(), + legend.position = ""top"", + legend.direction = ""vertical"") + ggplot2::ggsave(filename = fileName, plot = plot, width = 5, height = 3.5, dpi = 400) + } + + # covariate balance scatter plot + fileName <- file.path(diagnosticsFolder, paste0(""balanceScatter_a"", analysisId, + ""_t"", targetId, + ""_c"", comparatorId, + "".png"")) + if (!file.exists(fileName)) { + balance <- CohortMethod::computeCovariateBalance(psAfterMatching, cmData) + balanceScatterPlot <- CohortMethod::plotCovariateBalanceScatterPlot(balance = balance, + beforeLabel = paste(""Before"", psStrategy), + afterLabel = paste(""After"", psStrategy)) + title <- paste(targetLabel, comparatorLabel, sep = "" vs.\n"") + balanceScatterPlot <- balanceScatterPlot + ggplot2::ggtitle(title) + balanceScatterPlot <- balanceScatterPlot + ggplot2::theme(plot.title = ggplot2::element_text(colour = ""#000000"", size = 8, hjust = 0.5)) + ggplot2::ggsave(fileName, balanceScatterPlot, width = 4, height = 4.5, dpi = 400) + } + + # top covariate balance plot + fileName <- file.path(diagnosticsFolder, paste0(""balanceTop_a"", analysisId, + ""_t"", targetId, + ""_c"", comparatorId, + "".png"")) + if (!file.exists(fileName)) { + balanceTopPlot <- CohortMethod::plotCovariateBalanceOfTopVariables(balance = balance, + beforeLabel = paste(""Before"", psStrategy), + afterLabel = paste(""After"", psStrategy)) + title <- paste(targetLabel, comparatorLabel, sep = "" vs.\n"") + balanceTopPlot <- balanceTopPlot + ggplot2::ggtitle(title) + balanceTopPlot <- balanceTopPlot + ggplot2::theme(plot.title = ggplot2::element_text(colour = ""#000000"", size = 9, hjust = 0.5)) + ggplot2::ggsave(fileName, balanceTopPlot, width = 10, height = 6.5, dpi = 400) + } + } + } + if (!file.exists(mdrrsFileName)) + write.csv(mdrrs, mdrrsFileName, row.names = FALSE) + + if (!file.exists(hetergeneityOfEffectFileName)) + write.csv(hetergeneityOfEffect, hetergeneityOfEffectFileName, row.names = FALSE) + + if (!file.exists(modelsFileName)) + write.csv(models, modelsFileName, row.names = FALSE) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/R/createHrHeterogeneityPlots.R",".R","6986","113","#' @export +createHrHeterogeneityPlots <- function(outputFolders, + databaseNames, + reportFolder) { + loadResultsHrsByQ <- function(outputFolder) { + file <- file.path(outputFolder, ""diagnostics"", ""effectHeterogeneity.csv"") + x <- read.csv(file, stringsAsFactors = FALSE) + return(x) + } + results <- lapply(outputFolders, loadResultsHrsByQ) + results <- do.call(rbind, results) + results$tOrder <- match(results$targetName, c(""SGLT2i-BROAD-90"", + ""SGLT2i-NARROW-90"", + ""Canagliflozin-BROAD-90"", + ""Canagliflozin-NARROW-90"", + ""Dapagliflozin-BROAD-90"", + ""Dapagliflozin-NARROW-90"", + ""Empagliflozin-BROAD-90"", + ""Empagliflozin-NARROW-90"")) + results$cOrder <- match(results$comparatorName, c(""SU-BROAD-90"", + ""SU-NARROW-90"", + ""DPP-4i-BROAD-90"", + ""DPP-4i-NARROW-90"", + ""GLP-1a-BROAD-90"", + ""GLP-1a-NARROW-90"", + ""TZDs-BROAD-90"", + ""TZDs-NARROW-90"", + ""Insulin-BROAD-90"", + ""Insulin-NARROW-90"", + ""Metformin-BROAD-90"", + ""Metformin-NARROW-90"", + ""Insulinotropic AHAs-BROAD-90"", + ""Insulinotropic AHAs-NARROW-90"", + ""Other AHAs-BROAD-90"", + ""Other AHAs-NARROW-90"")) + results <- results[order(results$tOrder, results$cOrder), ] + dbPlots <- list() + for (db in unique(results$database)) { # db=""MDCR"" + dbResults <- results[results$analysisId == 1 & results$targetId %in% c(11, 14) & results$outcomeId == 200 & results$database == db, ] + dbResults$logRr[dbResults$eventsTreated == 0 | dbResults$eventsComparator == 0] <- NA + tcsOfInterest <- unique(dbResults[, c(""targetId"", ""comparatorId"")]) + plots <- list() + for (i in 1:nrow(tcsOfInterest)) { # i=6 + targetId <- tcsOfInterest$targetId[i] + comparatorId <- tcsOfInterest$comparatorId[i] + tcResult <- dbResults[dbResults$targetId == targetId & dbResults$comparatorId == comparatorId, ] + targetName <- sub(pattern = ""-90"", replacement = """", x = tcResult$targetName[1]) + comparatorName <- sub(pattern = ""-90"", replacement = """", x = tcResult$comparatorName[1]) + comparatorName <- sub(""Insulinotropic"", ""Ins."", comparatorName) + data <- data.frame(database = tcResult$database, + Quintile = tcResult$quintile, + logRr = tcResult$logRr, + logLb = tcResult$logRr + qnorm(0.025) * tcResult$seLogRr, + logUb = tcResult$logRr + qnorm(0.975) * tcResult$seLogRr) + breaks <- c(0.1, 0.25, 0.5, 1, 2, 4, 10) + labels <- c(0.1, paste(""0.25\nFavors"", targetName), 0.5, 1, 2, paste(""4\nFavors"", comparatorName), 10) + plot <- ggplot2::ggplot(data, + ggplot2::aes(x = exp(logRr), + y = Quintile, + xmin = exp(logLb), + xmax = exp(logUb)), + environment = environment()) + + ggplot2::geom_vline(xintercept = breaks, colour = ""#AAAAAA"", lty = 1, size = 0.1) + + ggplot2::geom_vline(xintercept = 1, colour = ""#000000"", lty = 1, size = 0.75) + + ggplot2::geom_errorbarh(height = 0, size = 1, alpha = 0.7, ggplot2::aes(colour = database)) + + ggplot2::geom_point(shape = 16, size = 2.2, alpha = 0.7, ggplot2::aes(colour = database)) + + ggplot2::coord_cartesian(xlim = c(0.1, 10)) + + ggplot2::scale_x_continuous(""Hazard ratio"", trans = ""log10"", breaks = breaks, labels = labels) + + ggplot2::scale_y_continuous(trans = ""reverse"") + + ggplot2::theme(text = ggplot2::element_text(size = 15), + panel.grid.minor = ggplot2::element_blank(), + panel.background = ggplot2::element_rect(fill = ""#FAFAFA"",colour = NA), + panel.grid.major = ggplot2::element_line(colour = ""#EEEEEE""), + axis.ticks = ggplot2::element_blank(), + axis.title.y = ggplot2::element_blank(), + axis.title.x = ggplot2::element_blank(), + #axis.text.y = ggplot2::element_blank(), + axis.text.y = ggplot2::element_text(size = 8), + axis.text.x = ggplot2::element_text(size = 8), + legend.position = ""none"") + plots[[length(plots) + 1]] <- plot + } + col0 <- grid::textGrob(db, gp = grid::gpar(fontface = ""bold"")) + col1 <- grid::textGrob(""SGLT2i-BROAD"") + col2 <- grid::textGrob(""SGLT2i-NARROW"") + row1 <- grid::textGrob(""SU"", rot = 90) + row2 <- grid::textGrob(""DPP-4i"", rot = 90) + row3 <- grid::textGrob(""GLP-1a"", rot = 90) + row4 <- grid::textGrob(""TZDs"", rot = 90) + row5 <- grid::textGrob(""Insulin"", rot = 90) + row6 <- grid::textGrob(""Metformin"", rot = 90) + row7 <- grid::textGrob(""Ins. AHAs"", rot = 90) + + dbPlot <- gridExtra::grid.arrange(col0, col1, col2, + row1, plots[[1]], plots[[8]], + row2, plots[[2]], plots[[9]], + row3, plots[[3]], plots[[10]], + row4, plots[[4]], plots[[11]], + row5, plots[[5]], plots[[12]], + row6, plots[[6]], plots[[13]], + row7, plots[[7]], plots[[14]], nrow = 8, + heights = grid::unit(c(5, rep(30,7)), rep(""mm"",7)), + widths = grid::unit(c(10, rep(75,2)), rep(""mm"",3))) + dbPlots[[length(dbPlots) + 1]] <- dbPlot + } + + finalPlot <- gridExtra::grid.arrange(dbPlots[[1]], dbPlots[[2]], + dbPlots[[3]], dbPlots[[4]], + ncol = 2) + plotFile <- file.path(reportFolder, ""hrHeterogeneityPlot.png"") + ggplot2::ggsave(filename = plotFile, plot = finalPlot, width = 14, height = 18) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/R/createIrDoseTable.R",".R","18604","331","#' @export +createIrDoseTable <- function(outputFolders, + databaseNames, + reportFolder) { + loadIrDoseResults <- function(outputFolder) { + shinyDataFolder <- file.path(outputFolder, ""results"", ""irDoseData"") + file <- list.files(shinyDataFolder, pattern = ""irDoseData_.*.rds"", full.names = TRUE) + x <- readRDS(file) + return(x) + } + results <- lapply(outputFolders, loadIrDoseResults) + results <- do.call(rbind, results) + results$timeAtRisk <- ""ITT"" + results$targetCohort <- sub(pattern = ""-90"", replacement = """", x = results$targetName) + results$comparatorCohort <- sub(pattern = ""-90"", replacement = """", x = results$comparatorName) + + fileName <- file.path(reportFolder, paste0(""IRsDose.xlsx"")) + unlink(fileName) + + outcomeNames <- unique(results$outcomeName) + timeAtRisks <- unique(results$timeAtRisk) + wb <- XLConnect::loadWorkbook(fileName, create = TRUE) + + subgroups <- list( + beforeMatching = c( + ""bmTreated"", ""bmTreatedDays"", ""bmEventsTreated"", + ""bmTarTargetMean"", ""bmTarTargetSd"", ""bmTarTargetMin"", ""bmTarTargetMedian"", ""bmTarTargetMax"", + ""bmComparator"", ""bmComparatorDays"", ""bmEventsComparator"", + ""bmTarComparatorMean"", ""bmTarComparatorSd"", ""bmTarComparatorMin"", ""bmTarComparatorMedian"", ""bmTarComparatorMax""), + afterMatching = c( + ""amTreated"", ""amTreatedDays"", ""amEventsTreated"", + ""amTarTargetMean"", ""amTarTargetSd"", ""amTarTargetMin"", ""amTarTargetMedian"", ""amTarTargetMax"", + ""amComparator"", ""amComparatorDays"", ""amEventsComparator"", + ""amTarComparatorMean"", ""amTarComparatorSd"", ""amTarComparatorMin"", ""amTarComparatorMedian"", ""amTarComparatorMax"")) + + for (i in 1) { # before matching only; if including after-matching, use 1:length(subgroups)) { + mainTable <- data.frame() + cols <- subgroups[[i]] + subgroup <- names(subgroups)[i] + for (database in databaseNames) { # database = ""CCAE"" + dbTable <- data.frame() + for (outcomeName in outcomeNames) { # outcomeName <- outcomeNames[1] + for (timeAtRisk in timeAtRisks) { # timeAtRisk <- timeAtRisks[1] + subset <- results[results$database == database & + results$outcomeName == outcomeName & + results$timeAtRisk == timeAtRisk, ] + + # Broad + # Ts + cana100Broad <- subset[subset$targetCohort ==""Canagliflozin-100 mg-BROAD"", ][1, cols] + cana300Broad <- subset[subset$targetCohort ==""Canagliflozin-300 mg-BROAD"", ][1, cols] + canaOtherBroad <- subset[subset$targetCohort ==""Canagliflozin-Other-BROAD"", ][1, cols] + dapa5Broad <- subset[subset$targetCohort ==""Dapagliflozin-5 mg-BROAD"", ][1, cols] + dapa10Broad <- subset[subset$targetCohort ==""Dapagliflozin-10 mg-BROAD"", ][1, cols] + # Cs + dapaOtherBroad <- subset[subset$comparatorCohort == ""Dapagliflozin-Other-BROAD"", ][1, cols] + empa10Broad <- subset[subset$comparatorCohort == ""Empagliflozin-10 mg-BROAD"", ][1, cols] + empa25Broad <- subset[subset$comparatorCohort == ""Empagliflozin-25 mg-BROAD"", ][1, cols] + empaOtherBroad <- subset[subset$comparatorCohort == ""Empagliflozin-Other-BROAD"", ][1, cols] + + # Narrow + # Ts + cana100Narrow <- subset[subset$targetCohort ==""Canagliflozin-100 mg-NARROW"", ][1, cols] + cana300Narrow <- subset[subset$targetCohort ==""Canagliflozin-300 mg-NARROW"", ][1, cols] + canaOtherNarrow <- subset[subset$targetCohort ==""Canagliflozin-Other-NARROW"", ][1, cols] + dapa5Narrow <- subset[subset$targetCohort ==""Dapagliflozin-5 mg-NARROW"", ][1, cols] + # Cs + dapa10Narrow <- subset[subset$comparatorCohort == ""Dapagliflozin-10 mg-NARROW"", ][1, cols] + dataOtherNarrow <- subset[subset$comparatorCohort == ""Dapagliflozin-Other-NARROW"", ][1, cols] + empa10Narrow <- subset[subset$comparatorCohort == ""Empagliflozin-10 mg-NARROW"", ][1, cols] + empa25Narrow <- subset[subset$comparatorCohort == ""Empagliflozin-25 mg-NARROW"", ][1, cols] + empaOtherNarrow <- subset[subset$comparatorCohort == ""Empagliflozin-Other-NARROW"", ][1, cols] + + subTable <- data.frame(outcomeName = outcomeName, + timeAtRisk = timeAtRisk, + exposure = c(""Canagliflozin-100 mg-BROAD"", + ""Canagliflozin-300 mg-BROAD"", + ""Canagliflozin-Other-BROAD"", + ""Dapagliflozin-5 mg-BROAD"", + ""Dapagliflozin-10 mg-BROAD"", + + ""Dapagliflozin-Other-BROAD"", + ""Empagliflozin-10 mg-BROAD"", + ""Empagliflozin-25 mg-BROAD"", + ""Empagliflozin-Other-BROAD"", + + ""Canagliflozin-100 mg-NARROW"", + ""Canagliflozin-300 mg-NARROW"", + ""Canagliflozin-Other-NARROW"", + ""Dapagliflozin-5 mg-NARROW"", + + ""Dapagliflozin-10 mg-NARROW"", + ""Dapagliflozin-Other-NARROW"", + ""Empagliflozin-10 mg-NARROW"", + ""Empagliflozin-25 mg-NARROW"", + ""Empagliflozin-Other-NARROW""), + subjects = c(cana100Broad[, 1], + cana300Broad[, 1], + canaOtherBroad[, 1], + dapa5Broad[, 1], + dapa10Broad[, 1], + + dapaOtherBroad[, 9], + empa10Broad[, 9], + empa25Broad[, 9], + empaOtherBroad[, 9], + + cana100Narrow[, 1], + cana300Narrow[, 1], + canaOtherNarrow[, 1], + dapa5Narrow[, 1], + + dapa10Narrow[, 9], + dataOtherNarrow[, 9], + empa10Narrow[, 9], + empa25Narrow[, 9], + empaOtherNarrow[, 9]), + + personTime = c(cana100Broad[, 2], + cana300Broad[, 2], + canaOtherBroad[, 2], + dapa5Broad[, 2], + dapa10Broad[, 2], + + dapaOtherBroad[, 10], + empa10Broad[, 10], + empa25Broad[, 10], + empaOtherBroad[, 10], + + cana100Narrow[, 2], + cana300Narrow[, 2], + canaOtherNarrow[, 2], + dapa5Narrow[, 2], + + dapa10Narrow[, 10], + dataOtherNarrow[, 10], + empa10Narrow[, 10], + empa25Narrow[, 10], + empaOtherNarrow[, 10]) / 365.25, + + meanPersonTime = c(cana100Broad[, 4], + cana300Broad[, 4], + canaOtherBroad[, 4], + dapa5Broad[, 4], + dapa10Broad[, 4], + + dapaOtherBroad[, 12], + empa10Broad[, 12], + empa25Broad[, 12], + empaOtherBroad[, 12], + + cana100Narrow[, 4], + cana300Narrow[, 4], + canaOtherNarrow[, 4], + dapa5Narrow[, 4], + + dapa10Narrow[, 12], + dataOtherNarrow[, 12], + empa10Narrow[, 12], + empa25Narrow[, 12], + empaOtherNarrow[, 12]) / 365.25, + + sdPersonTime = c(cana100Broad[, 5], + cana300Broad[, 5], + canaOtherBroad[, 5], + dapa5Broad[, 5], + dapa10Broad[, 5], + + dapaOtherBroad[, 13], + empa10Broad[, 13], + empa25Broad[, 13], + empaOtherBroad[, 13], + + cana100Narrow[, 5], + cana300Narrow[, 5], + canaOtherNarrow[, 5], + dapa5Narrow[, 5], + + dapa10Narrow[, 13], + dataOtherNarrow[, 13], + empa10Narrow[, 13], + empa25Narrow[, 13], + empaOtherNarrow[, 13]) / 365.25, + + minPersonTime = c(cana100Broad[, 6], + cana300Broad[, 6], + canaOtherBroad[, 6], + dapa5Broad[, 6], + dapa10Broad[, 6], + + dapaOtherBroad[, 14], + empa10Broad[, 14], + empa25Broad[, 14], + empaOtherBroad[, 14], + + cana100Narrow[, 6], + cana300Narrow[, 6], + canaOtherNarrow[, 6], + dapa5Narrow[, 6], + + dapa10Narrow[, 14], + dataOtherNarrow[, 14], + empa10Narrow[, 14], + empa25Narrow[, 14], + empaOtherNarrow[, 14]) / 365.25, + + medianPersonTime = c(cana100Broad[, 7], + cana300Broad[, 7], + canaOtherBroad[, 7], + dapa5Broad[, 7], + dapa10Broad[, 7], + + dapaOtherBroad[, 15], + empa10Broad[, 15], + empa25Broad[, 15], + empaOtherBroad[, 15], + + cana100Narrow[, 7], + cana300Narrow[, 7], + canaOtherNarrow[, 7], + dapa5Narrow[, 7], + + dapa10Narrow[, 15], + dataOtherNarrow[, 15], + empa10Narrow[, 15], + empa25Narrow[, 15], + empaOtherNarrow[, 15]) / 365.25, + + maxPersonTime = c(cana100Broad[, 8], + cana300Broad[, 8], + canaOtherBroad[, 8], + dapa5Broad[, 8], + dapa10Broad[, 8], + + dapaOtherBroad[, 15], + empa10Broad[, 15], + empa25Broad[, 15], + empaOtherBroad[, 15], + + cana100Narrow[, 8], + cana300Narrow[, 8], + canaOtherNarrow[, 8], + dapa5Narrow[, 8], + + dapa10Narrow[, 15], + dataOtherNarrow[, 15], + empa10Narrow[, 15], + empa25Narrow[, 15], + empaOtherNarrow[, 15]) / 365.25, + + events = c(cana100Broad[, 3], + cana300Broad[, 3], + canaOtherBroad[, 3], + dapa5Broad[, 3], + dapa10Broad[, 3], + + dapaOtherBroad[, 11], + empa10Broad[, 11], + empa25Broad[, 11], + empaOtherBroad[, 11], + + cana100Narrow[, 3], + cana300Narrow[, 3], + canaOtherNarrow[, 3], + dapa5Narrow[, 3], + + dapa10Narrow[, 11], + dataOtherNarrow[, 11], + empa10Narrow[, 11], + empa25Narrow[, 11], + empaOtherNarrow[, 11])) + + subTable$ir <- 1000 * subTable$events / subTable$personTime + dbTable <- rbind(dbTable, subTable) + } + } + colnames(dbTable)[4:12] <- paste(colnames(dbTable)[4:12], database, sep = ""_"") + if (ncol(mainTable) == 0) { + mainTable <- dbTable + } else { + if (!all.equal(mainTable$outcomeName, dbTable$outcomeName) || + !all.equal(mainTable$timeAtRisk, dbTable$timeAtRisk) || + !all.equal(mainTable$exposure, dbTable$exposure)) { + stop(""Something wrong with data ordering"") + } + mainTable <- cbind(mainTable, dbTable[, 4:12]) + } + } + mainTable[, c(5, 14, 23, 32)] <- round(mainTable[, c(5, 14, 23, 32)], 0) # total person years + mainTable[, c(6:10, 15:19, 24:28, 33:37)] <- round(mainTable[, c(6:10, 15:19, 24:28, 33:37)], 1) # stats person years + mainTable[, c(12, 21, 30, 39)] <- round(mainTable[, c(12, 21, 30, 39)], 1) # IRs + + XLConnect::createSheet(wb, name = subgroup) + header0 <- c("""", """", """", rep(databaseNames, each = 9)) + XLConnect::writeWorksheet(wb, + sheet = subgroup, + data = as.data.frame(t(header0)), + startRow = 1, + startCol = 1, + rownames = FALSE, + header = FALSE) + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""D1:L1"") + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""M1:U1"") + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""V1:AD1"") + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""AE1:AM1"") + header1 <- c(""Outcome"", + ""Time-at-risk"", + ""Exposure"", + rep(c(""Persons"", ""PY total"", ""PY mean"", ""PY SD"", ""PY min"", ""PY med"", ""PY max"", ""Events"", ""IR""), length(databaseNames))) + XLConnect::writeWorksheet(wb, + sheet = subgroup, + data = as.data.frame(t(header1)), + startRow = 2, + startCol = 1, + rownames = FALSE, + header = FALSE) + XLConnect::writeWorksheet(wb, + sheet = subgroup, + data = mainTable, + startRow = 3, + startCol = 1, + rownames = FALSE, + header = FALSE) + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""A3:A20"") + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""B3:B20"") + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""A21:A38"") + XLConnect::mergeCells(wb, sheet = subgroup, reference = ""B21:B38"") + } + XLConnect::saveWorkbook(wb) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/R/MetaAnalysis.R",".R","5489","143","#' @export +doMetaAnalysis <- function(outputFolders, + maOutputFolder, + maxCores) { + + OhdsiRTools::logInfo(""Performing meta-analysis"") + resultsFolder <- file.path(maOutputFolder, ""results"") + if (!file.exists(resultsFolder)) + dir.create(resultsFolder, recursive = TRUE) + shinyDataFolder <- file.path(resultsFolder, ""shinyData"") + if (!file.exists(shinyDataFolder)) + dir.create(shinyDataFolder) + + loadResults <- function(outputFolder) { + files <- list.files(file.path(outputFolder, ""results""), pattern = ""results_.*.csv"", full.names = TRUE) + OhdsiRTools::logInfo(""Loading "", files[1], "" for meta-analysis"") + return(read.csv(files[1])) + } + allResults <- lapply(outputFolders, loadResults) + allResults <- do.call(rbind, allResults) + groups <- split(allResults, paste(allResults$targetId, allResults$comparatorId, allResults$analysisId)) + cluster <- OhdsiRTools::makeCluster(min(maxCores, 12)) + results <- OhdsiRTools::clusterApply(cluster, groups, computeGroupMetaAnalysis, shinyDataFolder = shinyDataFolder) + OhdsiRTools::stopCluster(cluster) + results <- do.call(rbind, results) + + fileName <- file.path(resultsFolder, paste0(""results_Meta-analysis.csv"")) + write.csv(results, fileName, row.names = FALSE, na = """") + + hois <- results[results$type == ""Outcome of interest"", ] + fileName <- file.path(shinyDataFolder, paste0(""resultsHois_Meta-analysis.rds"")) + saveRDS(hois, fileName) + + ncs <- results[results$type == ""Negative control"", c(""targetId"", ""comparatorId"", ""outcomeId"", ""analysisId"", ""database"", ""logRr"", ""seLogRr"")] + fileName <- file.path(shinyDataFolder, paste0(""resultsNcs_Meta-analysis.rds"")) + saveRDS(ncs, fileName) +} + +computeGroupMetaAnalysis <- function(group, + shinyDataFolder) { + + # group <- groups[[""124 74 2""]] + analysisId <- group$analysisId[1] + targetId <- group$targetId[1] + comparatorId <- group$comparatorId[1] + OhdsiRTools::logTrace(""Performing meta-analysis for target "", targetId, "", comparator "", comparatorId, "", analysis"", analysisId) + outcomeGroups <- split(group, group$outcomeId) + outcomeGroupResults <- lapply(outcomeGroups, computeSingleMetaAnalysis) + groupResults <- do.call(rbind, outcomeGroupResults) + negControlSubset <- groupResults[groupResults$type == ""Negative control"", ] + validNcs <- sum(!is.na(negControlSubset$seLogRr)) + if (validNcs >= 5) { + fileName <- file.path(shinyDataFolder, paste0(""null_a"", analysisId, + ""_t"", targetId, + ""_c"", comparatorId, + ""_Meta-analysis.rds"")) + null <- EmpiricalCalibration::fitMcmcNull(negControlSubset$logRr, negControlSubset$seLogRr) + saveRDS(null, fileName) + calibratedP <- EmpiricalCalibration::calibrateP(null = null, + logRr = groupResults$logRr, + seLogRr = groupResults$seLogRr) + groupResults$calP <- calibratedP$p + groupResults$calP_lb95ci <- calibratedP$lb95ci + groupResults$calP_ub95ci <- calibratedP$ub95ci + mcmc <- attr(null, ""mcmc"") + groupResults$null_mean <- mean(mcmc$chain[,1]) + groupResults$null_sd <- 1/sqrt(mean(mcmc$chain[,2])) + } else { + groupResults$calP <- NA + groupResults$calP_lb95ci <- NA + groupResults$calP_ub95ci <- NA + groupResults$null_mean <- NA + groupResults$null_sd <- NA + } + return(groupResults) +} + +computeSingleMetaAnalysis <- function(outcomeGroup) { + + # outcomeGroup <- outcomeGroups[[2]] + maRow <- outcomeGroup[1, ] + outcomeGroup <- outcomeGroup[!is.na(outcomeGroup$seLogRr), ] + if (nrow(outcomeGroup) == 0) { + maRow$treated <- 0 + maRow$comparator <- 0 + maRow$treatedDays <- 0 + maRow$comparatorDays <- 0 + maRow$eventsTreated <- 0 + maRow$eventsComparator <- 0 + maRow$rr <- NA + maRow$ci95lb <- NA + maRow$ci95ub <- NA + maRow$p <- NA + maRow$logRr <- NA + maRow$seLogRr <- NA + maRow$i2 <- NA + } else if (nrow(outcomeGroup) == 1) { + maRow <- outcomeGroup[1, ] + maRow$i2 <- 0 + } else { + maRow$treated <- sum(outcomeGroup$treated) + maRow$comparator <- sum(outcomeGroup$comparator) + maRow$treatedDays <- sum(outcomeGroup$treatedDays) + maRow$comparatorDays <- sum(outcomeGroup$comparatorDays) + maRow$eventsTreated <- sum(outcomeGroup$eventsTreated) + maRow$eventsComparator <- sum(outcomeGroup$eventsComparator) + meta <- meta::metagen(outcomeGroup$logRr, outcomeGroup$seLogRr, sm = ""RR"", hakn = FALSE) + s <- summary(meta) + maRow$i2 <- s$I2$TE + if (maRow$i2 < .40) { + rnd <- s$random + maRow$rr <- exp(rnd$TE) + maRow$ci95lb <- exp(rnd$lower) + maRow$ci95ub <- exp(rnd$upper) + maRow$p <- rnd$p + maRow$logRr <- rnd$TE + maRow$seLogRr <- rnd$seTE + } else { + maRow$rr <- NA + maRow$ci95lb <- NA + maRow$ci95ub <- NA + maRow$p <- NA + maRow$logRr <- NA + maRow$seLogRr <- NA + } + } + if (is.na(maRow$logRr)) { + maRow$mdrr <- NA + } else { + alpha <- 0.05 + power <- 0.8 + z1MinAlpha <- qnorm(1 - alpha/2) + zBeta <- -qnorm(1 - power) + pA <- maRow$treated / (maRow$treated + maRow$comparator) + pB <- 1 - pA + totalEvents <- maRow$eventsTreated + maRow$eventsComparator + maRow$mdrr <- exp(sqrt((zBeta + z1MinAlpha)^2/(totalEvents * pA * pB))) + } + maRow$database <- ""Meta-analysis"" + return(maRow) +} + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/R/hrHeterogeneity.R",".R","6891","115","#' @export +hrHeterogeneity <- function(outputFolder, + databaseName, + primaryOnly = FALSE) { + packageName <- ""sglt2iDka"" + cmOutputFolder <- file.path(outputFolder, ""cmOutput"") + diagnosticsFolder <- file.path(outputFolder, ""diagnostics"") + if (!file.exists(diagnosticsFolder)) + dir.create(diagnosticsFolder) + + tcosAnalyses <- read.csv(system.file(""settings"", ""tcoAnalysisVariants.csv"", package = ""sglt2iDka""), stringsAsFactors = FALSE) + tcosAnalyses$tOrder <- match(tcosAnalyses$targetCohortName, c(""SGLT2i-BROAD-90"", + ""SGLT2i-NARROW-90"", + ""Canagliflozin-BROAD-90"", + ""Canagliflozin-NARROW-90"", + ""Dapagliflozin-BROAD-90"", + ""Dapagliflozin-NARROW-90"", + ""Empagliflozin-BROAD-90"", + ""Empagliflozin-NARROW-90"")) + tcosAnalyses$cOrder <- match(tcosAnalyses$comparatorCohortName, c(""SU-BROAD-90"", + ""SU-NARROW-90"", + ""DPP-4i-BROAD-90"", + ""DPP-4i-NARROW-90"", + ""GLP-1a-BROAD-90"", + ""GLP-1a-NARROW-90"", + ""TZDs-BROAD-90"", + ""TZDs-NARROW-90"", + ""Insulin-BROAD-90"", + ""Insulin-NARROW-90"", + ""Metformin-BROAD-90"", + ""Metformin-NARROW-90"", + ""Insulinotropic AHAs-BROAD-90"", + ""Insulinotropic AHAs-NARROW-90"", + ""Other AHAs-BROAD-90"", + ""Other AHAs-NARROW-90"")) + tcosAnalyses <- tcosAnalyses[order(tcosAnalyses$tOrder, tcosAnalyses$cOrder), ] + + if (primaryOnly == TRUE) { + tcosAnalyses <- tcosAnalyses[tcosAnalyses$timeAtRisk == ""Intent to Treat"" & tcosAnalyses$targetCohortId %in% c(11, 14) & tcosAnalyses$outcomeCohortId == 200, ] + } + + tcosOfInterest <- unique(tcosAnalyses[, c(""targetCohortId"", ""targetDrugName"", ""targetCohortName"", + ""comparatorCohortId"", ""comparatorDrugName"", ""comparatorCohortName"", + ""outcomeCohortId"", ""outcomeCohortName"")]) + names(tcosOfInterest) <- c(""targetId"", ""targetDrugName"", ""targetName"", + ""comparatorId"", ""comparatorDrugName"", ""comparatorName"", + ""outcomeId"", ""outcomeName"") + tcosOfInterest$targetName <- sub(pattern = ""-90"", replacement = """", x = tcosOfInterest$targetName) + tcosOfInterest$comparatorName <- sub(pattern = ""-90"", replacement = """", x = tcosOfInterest$comparatorName) + tcsOfInterest <- unique(tcosOfInterest[, c(""targetId"", ""comparatorId"")]) + outcomeIds <- unique(tcosOfInterest$outcomeId) + outcomeNames <- unique(tcosOfInterest$outcomeName) + + reference <- readRDS(file.path(cmOutputFolder, ""outcomeModelReference.rds"")) + effectHeterogeneityFileName <- file.path(diagnosticsFolder, paste0(""effectHeterogeneityTest.csv"")) + + effectHeterogeneity <- data.frame() + for (i in 1:nrow(tcsOfInterest)) { + targetId <- tcsOfInterest$targetId[i] + comparatorId <- tcsOfInterest$comparatorId[i] + idx <- which(tcosOfInterest$targetId == targetId & tcosOfInterest$comparatorId == comparatorId)[1] + targetLabel <- tcosOfInterest$targetName[idx] + comparatorLabel <- tcosOfInterest$comparatorName[idx] + for (analysisId in unique(reference$analysisId)) { + analysisDescription <- ifelse(analysisId == 1, ""ITT"", ""PP"") + for (outcomeId in outcomeIds) { + outcomeName <- outcomeNames[outcomeIds == outcomeId] + strataFile <- reference$strataFile[reference$analysisId == analysisId & + reference$targetId == targetId & + reference$comparatorId == comparatorId & + reference$outcomeId == outcomeId] + population <- readRDS(strataFile) + + refData <- data.frame(analysisId = 0, + analysisDescription = """", + targetId = 0, + targetName = """", + comparatorId = 0, + comparatorName = """", + outcomeId = 0, + outcomeName = """") + refData$analysisId <- analysisId + refData$analysisDescription <- analysisDescription + refData$targetId <- targetId + refData$targetName <- targetLabel + refData$comparatorId <- comparatorId + refData$comparatorName <- comparatorLabel + refData$outcomeId <- outcomeId + refData$outcomeName <- outcomeName + + strataPop <- CohortMethod::stratifyByPs(population = population, numberOfStrata = 5, baseSelection = ""all"") + strataPop$y <- ifelse(strataPop$outcomeCount != 0, 1, 0) + strataPop$stratumId <- relevel(as.factor(strataPop$stratumId), ref = 3) + + formula <- as.formula(survival::Surv(survivalTime, y) ~ treatment + stratumId + treatment:stratumId) + tryCatch({ + fit <- survival::coxph(formula, strataPop) + }, error = function(e) { + print(as.character(e)) + }) + coefs <- as.data.frame(summary(fit)$coefficients) + coefs <- cbind(terms = row.names(coefs), coefs) + row.names(coefs) <- NULL + coefs <- merge(refData, coefs) + intPValues <- coefs[coefs$terms %in% c(""treatment:stratumId1"", ""treatment:stratumId2"", ""treatment:stratumId4"", ""treatment:stratumId5""), ]$`Pr(>|z|)` + coefs$hrHetero <- ifelse(length(intPValues[intPValues < 0.05]), 1, 0) + + effectHeterogeneity <- rbind(effectHeterogeneity, coefs) + } + } + } + effectHeterogeneity <- cbind(effectHeterogeneity, database = databaseName) + write.csv(effectHeterogeneity, effectHeterogeneityFileName, row.names = FALSE) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/R/CreateStudyAnalysisDetails.R",".R","34347","448","#' @export +createEstimateVariants <- function(connectionDetails, + cohortDefinitionSchema, + cohortDefinitionTable, + codeListSchema, + codeListTable, + vocabularyDatabaseSchema, + outputFolder) { + connection <- DatabaseConnector::connect(connectionDetails) + on.exit(DatabaseConnector::disconnect(connection)) + sql <- SqlRender::renderSql(sql = ""select * from @cohort_definition_schema.@cohort_definition_table"", + cohort_definition_schema = cohortDefinitionSchema, + cohort_definition_table = cohortDefinitionTable)$sql + cohortDefinitions <- DatabaseConnector::querySql(connection, sql) + + cohortUniverseFile <- file.path(outputFolder, ""cohortUniverse.csv"") + write.csv(cohortDefinitions, file = cohortUniverseFile, row.names = FALSE) + + cohortDefinitions <- cohortDefinitions[cohortDefinitions$CENSOR %in% c(90, 0), ] + drugs <- unique(cohortDefinitions$COHORT_OF_INTEREST[cohortDefinitions$TARGET_COHORT == 1 | cohortDefinitions$COMPARATOR_COHORT == 1]) + cohortDefinitions$excludedCovariateConceptIds <- """" + for (drug in drugs) { + sql <- SqlRender::loadRenderTranslateSql(sqlFilename = ""getExclusionCovariateConceptIds.sql"", + packageName = ""sglt2iDka"", + dbms = attr(connection, ""dbms""), + code_list_schema = codeListSchema, + code_list_table = codeListTable, + vocabulary_database_schema = vocabularyDatabaseSchema, + drug = drug) + excludedCovariateConceptIds <- DatabaseConnector::querySql(connection, sql)[, 1] + excludedCovariateConceptIds <- noquote(paste(excludedCovariateConceptIds, collapse = "";"")) + cohortDefinitions$excludedCovariateConceptIds[cohortDefinitions$COHORT_OF_INTEREST == drug] <- excludedCovariateConceptIds + } + targetCohorts <- cohortDefinitions[cohortDefinitions$TARGET_COHORT == 1, + c(""COHORT_DEFINITION_ID"", ""COHORT_OF_INTEREST"", ""T2DM"", ""CENSOR"", ""FULL_NAME"", ""excludedCovariateConceptIds"")] + names(targetCohorts) <- c(""targetCohortId"", ""targetDrugName"", ""t2dm"", ""censor"", ""targetCohortName"", ""targetExcludedCovariateConceptIds"") + comparatorCohorts <- cohortDefinitions[cohortDefinitions$COMPARATOR_COHORT == 1, + c(""COHORT_DEFINITION_ID"", ""COHORT_OF_INTEREST"", ""T2DM"", ""CENSOR"", ""FULL_NAME"", ""excludedCovariateConceptIds"")] + names(comparatorCohorts) <- c(""comparatorCohortId"", ""comparatorDrugName"", ""t2dm"", ""censor"", ""comparatorCohortName"", ""comparatorExcludedCovariateConceptIds"") + outcomeCohorts <- cohortDefinitions[cohortDefinitions$OUTCOME_COHORT == 1, c(""COHORT_DEFINITION_ID"", ""COHORT_OF_INTEREST"")] + names(outcomeCohorts) <- c(""outcomeCohortId"", ""outcomeCohortName"") + tcs <- merge(targetCohorts, comparatorCohorts) + tcs$excludedCovariateConceptIds <- paste(tcs$targetExcludedCovariateConceptIds, tcs$comparatorExcludedCovariateConceptIds, sep = "";"") + tcos <- merge(tcs, outcomeCohorts) + fullGridTcosAnalyses <- merge(tcos, data.frame(timeAtRisk = c(""Intent to Treat"", ""Per Protocol""))) + tcosAnalyses <- fullGridTcosAnalyses[fullGridTcosAnalyses$targetDrugName != ""SGLT2i"" | fullGridTcosAnalyses$comparatorDrugName != ""Other AHAs"", ] + + tcosAnalysesFile <- file.path(outputFolder, ""tcoAnalysisVariants.csv"") + write.csv(tcosAnalyses, file = tcosAnalysesFile, row.names = FALSE) + negativeControlOutcomeCohorts <- cohortDefinitions[cohortDefinitions$NEGATIVE_CONTROL == 1, c(1,2)] + negativeControlOutcomeCohortsFile <- file.path(outputFolder, ""negativeControlOutcomeCohorts.csv"") + write.csv(negativeControlOutcomeCohorts, file = negativeControlOutcomeCohortsFile, row.names = FALSE) +} + + +#' @export +createTcos <- function() { + tcosAnalyses <- read.csv(system.file(""settings"", ""tcoAnalysisVariants.csv"", package = ""sglt2iDka""), stringsAsFactors = FALSE) + negativeControlOutcomeCohorts <- read.csv(system.file(""settings"", ""negativeControlOutcomeCohorts.csv"", package = ""sglt2iDka""), stringsAsFactors = FALSE) + negativeControlOutcomeCohortIds <- negativeControlOutcomeCohorts$COHORT_DEFINITION_ID + tcCombinations <- unique(tcosAnalyses[, c(""targetCohortId"", ""comparatorCohortId"")]) + tcoList <- list() + for (i in 1:nrow(tcCombinations)) { + targetCohortId <- tcCombinations$targetCohortId[i] + comparatorCohortId <- tcCombinations$comparatorCohortId[i] + outcomeCohortIds <- unique(tcosAnalyses$outcomeCohortId[tcosAnalyses$targetCohortId == targetCohortId & tcosAnalyses$comparatorCohortId == comparatorCohortId]) + outcomeCohortIds <- c(outcomeCohortIds, negativeControlOutcomeCohortIds) + excludeCovariateConceptIds <- unique(as.character(tcosAnalyses$excludedCovariateConceptIds[tcosAnalyses$targetCohortId == targetCohortId & tcosAnalyses$comparatorCohortId == comparatorCohortId])) + excludeCovariateConceptIds <- as.numeric(strsplit(excludeCovariateConceptIds, split = "";"")[[1]]) + tcoCombination <- CohortMethod::createDrugComparatorOutcomes(targetId = targetCohortId, + comparatorId = comparatorCohortId, + outcomeIds = outcomeCohortIds, + excludedCovariateConceptIds = excludeCovariateConceptIds) + tcoList[[length(tcoList) + 1]] <- tcoCombination + } + return(tcoList) +} + +#' @export +createAnalysesDetails <- function(outputFolder) { + defaultCovariateSettings <- FeatureExtraction::createCovariateSettings(useDemographicsGender = TRUE, + useDemographicsAgeGroup = TRUE, + useDemographicsIndexYear = TRUE, + useDemographicsIndexMonth = TRUE, + useConditionGroupEraLongTerm = TRUE, + useDrugExposureLongTerm = TRUE, + useDrugGroupEraLongTerm = TRUE, + useDrugEraOverlapping = TRUE, + # DrugGroupEraOverlapping = TRUE, + useProcedureOccurrenceLongTerm = TRUE, + useMeasurementLongTerm = TRUE, + useCharlsonIndex = TRUE, + useDcsi = TRUE, + useChads2 = TRUE, + useDistinctConditionCountLongTerm = TRUE, + useDistinctIngredientCountLongTerm = TRUE, + useDistinctProcedureCountLongTerm = TRUE, + useDistinctMeasurementCountLongTerm = TRUE, + useDistinctObservationCountLongTerm = TRUE, + useVisitCountLongTerm = TRUE, + useVisitConceptCountLongTerm = TRUE, + addDescendantsToExclude = TRUE) + priorOutcomesCovariateSettings <- sglt2iDka::createPriorOutcomesCovariateSettings(outcomeDatabaseSchema = ""unknown"", + outcomeTable = ""unknown"", + windowStart = -99999, + windowEnd = -1, + outcomeIds = c(200, 201), + outcomeNames = c(""DKA IP ER"", ""DKA IP""), + analysisId = 999) # any time prior + # priorOutcomes365dCovariateSettings <- sglt2iDka::createPriorOutcomesCovariateSettings(outcomeDatabaseSchema = ""unknown"", + # outcomeTable = ""unknown"", + # windowStart = -365, + # windowEnd = -1, + # outcomeIds = c(200, 201), + # outcomeNames = c(""DKA IP ER"", ""DKA IP""), + # analysisId = 997) # 365d prior + priorInsulinCovariateSettings <- sglt2iDka::createPriorExposureCovariateSettings(exposureDatabaseSchema = ""unknown"", + covariateIdPrefix = 1000, + codeListSchema = ""unknown"", + codeListTable = ""unknown"", + vocabularyDatabaseSchema = ""unknown"", + drug = ""Insulin"") + priorAHACovariateSettings <- sglt2iDka::createPriorExposureCovariateSettings(exposureDatabaseSchema = ""unknown"", + covariateIdPrefix = 2000, + codeListSchema = ""unknown"", + codeListTable = ""unknown"", + vocabularyDatabaseSchema = ""unknown"", + drug = ""AHAs"") + covariateSettings <- list(defaultCovariateSettings, + priorOutcomesCovariateSettings, + #priorOutcomes365dCovariateSettings, # unecessary to include + priorInsulinCovariateSettings, + priorAHACovariateSettings) + + getDbCmDataArgs <- CohortMethod::createGetDbCohortMethodDataArgs(washoutPeriod = 0, + firstExposureOnly = FALSE, + removeDuplicateSubjects = ""keep all"", + restrictToCommonPeriod = FALSE, + maxCohortSize = 0, # use 5000 for development + excludeDrugsFromCovariates = FALSE, + covariateSettings = covariateSettings) + + defaultPrior <- Cyclops::createPrior(""laplace"", + exclude = c(0), + useCrossValidation = TRUE) + + defaultControl <- Cyclops::createControl(cvType = ""auto"", + startingVariance = 0.01, + noiseLevel = ""quiet"", + tolerance = 1e-06, + maxIterations = 2500, + cvRepetitions = 10, + seed = 1234) + + createPsArgs <- CohortMethod::createCreatePsArgs(control = defaultControl, + prior = defaultPrior, + errorOnHighCorrelation = FALSE, + stopOnError = FALSE) + + matchOnPsArgs <- CohortMethod::createMatchOnPsArgs(maxRatio = 1) + + fitOutcomeModelArgs1 <- CohortMethod::createFitOutcomeModelArgs(useCovariates = FALSE, + modelType = ""cox"", + stratified = TRUE, + prior = defaultPrior, + control = defaultControl) + + timeToFirstPostIndexEventITT <- CohortMethod::createCreateStudyPopulationArgs(removeSubjectsWithPriorOutcome = FALSE, + firstExposureOnly = FALSE, + washoutPeriod = 0, + removeDuplicateSubjects = FALSE, + minDaysAtRisk = 0, + riskWindowStart = 1, + addExposureDaysToStart = FALSE, + riskWindowEnd = 9999, + addExposureDaysToEnd = FALSE, + censorAtNewRiskWindow = FALSE) + + timeToFirstPostIndexEventPP <- CohortMethod::createCreateStudyPopulationArgs(removeSubjectsWithPriorOutcome = FALSE, + firstExposureOnly = FALSE, + washoutPeriod = 0, + removeDuplicateSubjects = FALSE, + minDaysAtRisk = 0, + riskWindowStart = 1, + addExposureDaysToStart = FALSE, + riskWindowEnd = 0, + addExposureDaysToEnd = TRUE, + censorAtNewRiskWindow = FALSE) + + a1 <- CohortMethod::createCmAnalysis(analysisId = 1, + description = ""Time to First Post Index Event Intent to Treat Matching"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstPostIndexEventITT, + createPs = TRUE, + createPsArgs = createPsArgs, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgs, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + a2 <- CohortMethod::createCmAnalysis(analysisId = 2, + description = ""Time to First Post Index Event Per Protocol Matching"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstPostIndexEventPP, + createPs = TRUE, + createPsArgs = createPsArgs, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgs, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgs1) + + cmAnalysisList <- list(a1, a2) + CohortMethod::saveCmAnalysisList(cmAnalysisList, file.path(outputFolder, ""cmAnalysisList.json"")) +} + + +#' @export +createIrSensitivityVariants <- function(connectionDetails, + cohortDefinitionSchema, + cohortDefinitionTable, + outputFolder) { + connection <- DatabaseConnector::connect(connectionDetails) + on.exit(DatabaseConnector::disconnect(connection)) + sql <- SqlRender::renderSql(sql = ""select * from @cohort_definition_schema.@cohort_definition_table"", + cohort_definition_schema = cohortDefinitionSchema, + cohort_definition_table = cohortDefinitionTable)$sql + cohortDefinitions <- DatabaseConnector::querySql(connection, sql) + cohortDefinitions <- cohortDefinitions[cohortDefinitions$CENSOR %in% c(60, 120, 0) & cohortDefinitions$NEGATIVE_CONTROL == 0, ] + targetCohorts <- cohortDefinitions[cohortDefinitions$TARGET_COHORT == 1, + c(""COHORT_DEFINITION_ID"", ""COHORT_OF_INTEREST"", ""T2DM"", ""CENSOR"", ""FULL_NAME"")] + names(targetCohorts) <- c(""targetCohortId"", ""targetDrugName"", ""t2dm"", ""censor"", ""targetCohortName"") + comparatorCohorts <- cohortDefinitions[cohortDefinitions$COMPARATOR_COHORT == 1, + c(""COHORT_DEFINITION_ID"", ""COHORT_OF_INTEREST"", ""T2DM"", ""CENSOR"", ""FULL_NAME"")] + names(comparatorCohorts) <- c(""comparatorCohortId"", ""comparatorDrugName"", ""t2dm"", ""censor"", ""comparatorCohortName"") + outcomeCohorts <- cohortDefinitions[cohortDefinitions$OUTCOME_COHORT == 1, c(""COHORT_DEFINITION_ID"", ""COHORT_OF_INTEREST"")] + names(outcomeCohorts) <- c(""outcomeCohortId"", ""outcomeCohortName"") + tcs <- merge(targetCohorts, comparatorCohorts) + tcos <- merge(tcs, outcomeCohorts) + tcos <- tcos[tcos$targetDrugName != ""SGLT2i"" | tcos$comparatorDrugName != ""Other AHAs"", ] + tcosFile <- file.path(outputFolder, ""tcoIrSensitivityVariants.csv"") + write.csv(tcos, file = tcosFile, row.names = FALSE) +} + +#' @export +createIrSensitivityTcos <- function() { + tcos <- read.csv(system.file(""settings"", ""tcoIrSensitivityVariants.csv"", package = ""sglt2iDka""), stringsAsFactors = FALSE) + tcCombinations <- unique(tcos[, c(""targetCohortId"", ""comparatorCohortId"")]) + tcoList <- list() + for (i in 1:nrow(tcCombinations)) { + targetCohortId <- tcCombinations$targetCohortId[i] + comparatorCohortId <- tcCombinations$comparatorCohortId[i] + outcomeCohortIds <- unique(tcos$outcomeCohortId[tcos$targetCohortId == targetCohortId & tcos$comparatorCohortId == comparatorCohortId]) + tcoCombination <- CohortMethod::createDrugComparatorOutcomes(targetId = targetCohortId, + comparatorId = comparatorCohortId, + outcomeIds = outcomeCohortIds) + tcoList[[length(tcoList) + 1]] <- tcoCombination + } + return(tcoList) +} + + +#' @export +createIrSensitivityAnalysesDetails <- function(outputFolder) { + defaultCovariateSettings <- FeatureExtraction::createCovariateSettings(useDemographicsGender = TRUE, + useDemographicsAgeGroup = TRUE) + priorOutcomesCovariateSettings <- sglt2iDka::createPriorOutcomesCovariateSettings(outcomeDatabaseSchema = ""unknown"", + outcomeTable = ""unknown"", + windowStart = -99999, + windowEnd = -1, + outcomeIds = c(200, 201), + outcomeNames = c(""DKA IP ER"", ""DKA IP""), + analysisId = 999) # any time prior + priorInsulinCovariateSettings <- sglt2iDka::createPriorExposureCovariateSettings(exposureDatabaseSchema = ""unknown"", + covariateIdPrefix = 1000, + codeListSchema = ""unknown"", + codeListTable = ""unknown"", + vocabularyDatabaseSchema = ""unknown"", + drug = ""Insulin"") + priorAHACovariateSettings <- sglt2iDka::createPriorExposureCovariateSettings(exposureDatabaseSchema = ""unknown"", + covariateIdPrefix = 2000, + codeListSchema = ""unknown"", + codeListTable = ""unknown"", + vocabularyDatabaseSchema = ""unknown"", + drug = ""AHAs"") + covariateSettings <- list(defaultCovariateSettings, priorOutcomesCovariateSettings, priorInsulinCovariateSettings, priorAHACovariateSettings) + + getDbCmDataArgs <- CohortMethod::createGetDbCohortMethodDataArgs(washoutPeriod = 0, + firstExposureOnly = FALSE, + removeDuplicateSubjects = ""keep all"", + restrictToCommonPeriod = FALSE, + maxCohortSize = 0, + excludeDrugsFromCovariates = FALSE, + covariateSettings = covariateSettings) + + timeToFirstPostIndexEventPP <- CohortMethod::createCreateStudyPopulationArgs(removeSubjectsWithPriorOutcome = FALSE, + firstExposureOnly = FALSE, + washoutPeriod = 0, + removeDuplicateSubjects = FALSE, + minDaysAtRisk = 0, + riskWindowStart = 1, + addExposureDaysToStart = FALSE, + riskWindowEnd = 0, + addExposureDaysToEnd = TRUE, + censorAtNewRiskWindow = FALSE) + + a1 <- CohortMethod::createCmAnalysis(analysisId = 1, + description = ""Time to First Post Index Event IR Sensitivity"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstPostIndexEventPP) + + cmAnalysisList <- list(a1) + CohortMethod::saveCmAnalysisList(cmAnalysisList, file.path(outputFolder, ""cmIrSensitivityAnalysisList.json"")) +} + + +#' @export +createIrDoseVariants <- function(connectionDetails, + cohortDefinitionSchema, + cohortDoseDefinitionTable, + cohortDefinitionTable, + outputFolder) { + cohortDefinitionSchema <- ""scratch.dbo"" + cohortDoseDefinitionTable <- ""epi535_cohort_universe_dose"" + cohortDefinitionTable <- ""epi535_cohort_universe"" + connection <- DatabaseConnector::connect(connectionDetails) + on.exit(DatabaseConnector::disconnect(connection)) + sql <- SqlRender::renderSql(sql = ""select * from @cohort_definition_schema.@cohort_definition_table"", + cohort_definition_schema = cohortDefinitionSchema, + cohort_definition_table = cohortDoseDefinitionTable)$sql + cohortDefinitions <- DatabaseConnector::querySql(connection, sql) + cohortUniverseDoseFile <- file.path(outputFolder, ""cohortUniverseDose.csv"") + write.csv(cohortDefinitions, file = cohortUniverseDoseFile, row.names = FALSE) + targetCohorts <- cohortDefinitions[1:9, c(""COHORT_DEFINITION_ID"", ""COHORT_OF_INTEREST"", ""FULL_NAME"")] # create as few CM data objects as possible that obtain data on all dose cohorts + names(targetCohorts) <- c(""targetCohortId"", ""targetDrugName"", ""targetCohortName"") + comparatorCohorts <- cohortDefinitions[10:18, c(""COHORT_DEFINITION_ID"", ""COHORT_OF_INTEREST"", ""FULL_NAME"")] + names(comparatorCohorts) <- c(""comparatorCohortId"", ""comparatorDrugName"", ""comparatorCohortName"") + tcs <- cbind(targetCohorts, comparatorCohorts) + sql <- SqlRender::renderSql(sql = ""select * from @cohort_definition_schema.@cohort_definition_table"", + cohort_definition_schema = cohortDefinitionSchema, + cohort_definition_table = cohortDefinitionTable)$sql + outcomeCohorts <- DatabaseConnector::querySql(connection, sql) + outcomeCohorts <- outcomeCohorts[outcomeCohorts$OUTCOME_COHORT == 1, c(""COHORT_DEFINITION_ID"", ""COHORT_OF_INTEREST"")] + names(outcomeCohorts) <- c(""outcomeCohortId"", ""outcomeCohortName"") + tcos <- merge(tcs, outcomeCohorts) + tcosFile <- file.path(outputFolder, ""tcoIrDoseVariants.csv"") + write.csv(tcos, file = tcosFile, row.names = FALSE) +} + +#' @export +createIrDoseTcos <- function() { + tcos <- read.csv(system.file(""settings"", ""tcoIrDoseVariants.csv"", package = ""sglt2iDka""), stringsAsFactors = FALSE) + tcCombinations <- unique(tcos[, c(""targetCohortId"", ""comparatorCohortId"")]) + tcoList <- list() + for (i in 1:nrow(tcCombinations)) { + targetCohortId <- tcCombinations$targetCohortId[i] + comparatorCohortId <- tcCombinations$comparatorCohortId[i] + outcomeCohortIds <- unique(tcos$outcomeCohortId[tcos$targetCohortId == targetCohortId & tcos$comparatorCohortId == comparatorCohortId]) + tcoCombination <- CohortMethod::createDrugComparatorOutcomes(targetId = targetCohortId, + comparatorId = comparatorCohortId, + outcomeIds = outcomeCohortIds) + tcoList[[length(tcoList) + 1]] <- tcoCombination + } + return(tcoList) +} + +#' @export +createIrDoseAnalysesDetails <- function(outputFolder) { + defaultCovariateSettings <- FeatureExtraction::createCovariateSettings(useDemographicsGender = TRUE, + useDemographicsAgeGroup = TRUE) + priorOutcomesCovariateSettings <- sglt2iDka::createPriorOutcomesCovariateSettings(outcomeDatabaseSchema = ""unknown"", + outcomeTable = ""unknown"", + windowStart = -99999, + windowEnd = -1, + outcomeIds = c(200, 201), + outcomeNames = c(""DKA IP ER"", ""DKA IP""), + analysisId = 999) # any time prior + priorInsulinCovariateSettings <- sglt2iDka::createPriorExposureCovariateSettings(exposureDatabaseSchema = ""unknown"", + covariateIdPrefix = 1000, + codeListSchema = ""unknown"", + codeListTable = ""unknown"", + vocabularyDatabaseSchema = ""unknown"", + drug = ""Insulin"") + priorAHACovariateSettings <- sglt2iDka::createPriorExposureCovariateSettings(exposureDatabaseSchema = ""unknown"", + covariateIdPrefix = 2000, + codeListSchema = ""unknown"", + codeListTable = ""unknown"", + vocabularyDatabaseSchema = ""unknown"", + drug = ""AHAs"") + covariateSettings <- list(defaultCovariateSettings, priorOutcomesCovariateSettings, priorInsulinCovariateSettings, priorAHACovariateSettings) + + getDbCmDataArgs <- CohortMethod::createGetDbCohortMethodDataArgs(washoutPeriod = 0, + firstExposureOnly = FALSE, + removeDuplicateSubjects = ""keep all"", + restrictToCommonPeriod = FALSE, + maxCohortSize = 0, + excludeDrugsFromCovariates = FALSE, + covariateSettings = covariateSettings) + + timeToFirstPostIndexEventITT <- CohortMethod::createCreateStudyPopulationArgs(removeSubjectsWithPriorOutcome = FALSE, + firstExposureOnly = FALSE, + washoutPeriod = 0, + removeDuplicateSubjects = FALSE, + minDaysAtRisk = 0, + riskWindowStart = 1, + addExposureDaysToStart = FALSE, + riskWindowEnd = 9999, + addExposureDaysToEnd = FALSE, + censorAtNewRiskWindow = FALSE) + + a1 <- CohortMethod::createCmAnalysis(analysisId = 1, + description = ""Time to First Post Index Event IR dose ITT"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = timeToFirstPostIndexEventITT) + + cmAnalysisList <- list(a1) + CohortMethod::saveCmAnalysisList(cmAnalysisList, file.path(outputFolder, ""cmIrDoseAnalysisList.json"")) +} + +#' @export +addCohortNames <- function(data, + dose = FALSE, + IdColumnName = ""cohortDefinitionId"", + nameColumnName = ""cohortName"") { + if (dose) { + cohortsToCreate <- read.csv(system.file(""settings"", ""cohortUniverse.csv"", package = ""sglt2iDka""), stringsAsFactors = FALSE) + cohortsToCreateDose <- read.csv(system.file(""settings"", ""cohortUniverseDose.csv"", package = ""sglt2iDka""), stringsAsFactors = FALSE) + cohortsToCreateDose <- cohortsToCreateDose[, -c(13,14)] + cohortsToCreate <- rbind(cohortsToCreate, cohortsToCreateDose) + } else { + cohortsToCreate <- read.csv(system.file(""settings"", ""cohortUniverse.csv"", package = ""sglt2iDka""), stringsAsFactors = FALSE) + } + cohortsToCreate$FULL_NAME[is.na(cohortsToCreate$FULL_NAME)] <- cohortsToCreate$COHORT_OF_INTEREST[is.na(cohortsToCreate$FULL_NAME)] + cohortsToCreate <- cohortsToCreate[, c(""COHORT_DEFINITION_ID"", ""FULL_NAME"")] + names(cohortsToCreate) <- c(""cohortId"", ""name"") + idToName <- cohortsToCreate + idToName <- idToName[order(idToName$cohortId), ] + idToName <- idToName[!duplicated(idToName$cohortId), ] + names(idToName)[1] <- IdColumnName + names(idToName)[2] <- nameColumnName + data <- merge(data, idToName, all.x = TRUE) + # Change order of columns: + idCol <- which(colnames(data) == IdColumnName) + if (idCol < ncol(data) - 1) { + data <- data[, c(1:idCol, ncol(data) , (idCol+1):(ncol(data)-1))] + } + return(data) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/R/createHrPlots.R",".R","10297","158","#' @export +createHrPlots <- function(outputFolders, + maOutputFolder, + reportFolder) { + loadResultsHois <- function(outputFolder, + fileName) { + shinyDataFolder <- file.path(outputFolder, ""results"", ""shinyData"") + file <- list.files(shinyDataFolder, pattern = ""resultsHois_.*.rds"", full.names = TRUE) + x <- readRDS(file) + if (is.null(x$i2)) + x$i2 <- NA + return(x) + } + results <- lapply(c(outputFolders, maOutputFolder), loadResultsHois) + results <- do.call(rbind, results) + results$tOrder <- match(results$targetName, c(""SGLT2i-BROAD-90"", + ""SGLT2i-NARROW-90"", + ""Canagliflozin-BROAD-90"", + ""Canagliflozin-NARROW-90"", + ""Dapagliflozin-BROAD-90"", + ""Dapagliflozin-NARROW-90"", + ""Empagliflozin-BROAD-90"", + ""Empagliflozin-NARROW-90"")) + results$cOrder <- match(results$comparatorName, c(""SU-BROAD-90"", + ""SU-NARROW-90"", + ""DPP-4i-BROAD-90"", + ""DPP-4i-NARROW-90"", + ""GLP-1a-BROAD-90"", + ""GLP-1a-NARROW-90"", + ""TZDs-BROAD-90"", + ""TZDs-NARROW-90"", + ""Insulin-BROAD-90"", + ""Insulin-NARROW-90"", + ""Metformin-BROAD-90"", + ""Metformin-NARROW-90"", + ""Insulinotropic AHAs-BROAD-90"", + ""Insulinotropic AHAs-NARROW-90"", + ""Other AHAs-BROAD-90"", + ""Other AHAs-NARROW-90"")) + results <- results[order(results$tOrder, results$cOrder), ] + results$targetName <- sub(pattern = ""-90"", replacement = """", x = results$targetName) + results$comparatorName <- sub(pattern = ""-90"", replacement = """", x = results$comparatorName) + results$comparatorName <- sub(""Insulinotropic"", ""Ins."", results$comparatorName) + results$timeAtRisk[results$analysisDescription == ""Time to First Post Index Event Intent to Treat Matching""] <- ""ITT"" + results$timeAtRisk[results$analysisDescription == ""Time to First Post Index Event Per Protocol Matching""] <- ""PP"" + results$logRr[results$eventsTreated == 0 | results$eventsComparator == 0] <- NA + + resultsTable4 <- results[(results$targetName == ""SGLT2i-BROAD"" | results$targetName == ""SGLT2i-NARROW"") & + results$outcomeName == ""DKA (IP & ER)"" & results$timeAtRisk == ""ITT"", ] + resultsTable5 <- results[(results$targetName == ""Canagliflozin-BROAD"" | results$targetName == ""Canagliflozin-NARROW"") & + results$outcomeName == ""DKA (IP & ER)"" & results$timeAtRisk == ""ITT"", ] + resultsTable6 <- results[(results$targetName == ""Dapagliflozin-BROAD"" | results$targetName == ""Dapagliflozin-NARROW"") & + results$outcomeName == ""DKA (IP & ER)"" & results$timeAtRisk == ""ITT"", ] + resultsTable7 <- results[(results$targetName == ""Empagliflozin-BROAD"" | results$targetName == ""Empagliflozin-NARROW"") & + results$outcomeName == ""DKA (IP & ER)"" & results$timeAtRisk == ""ITT"", ] + resultsAppendix4 <- results[(results$targetName == ""SGLT2i-BROAD"" | results$targetName == ""SGLT2i-NARROW"") & + results$outcomeName == ""DKA (IP)"" & results$timeAtRisk == ""ITT"", ] + resultsAppendix5 <- results[(results$targetName == ""SGLT2i-BROAD"" | results$targetName == ""SGLT2i-NARROW"") & + results$outcomeName == ""DKA (IP & ER)"" & results$timeAtRisk == ""PP"", ] + resultSets <- list(Table4 = resultsTable4, + Table5 = resultsTable5, + Table6 = resultsTable6, + Table7 = resultsTable7, + AppendixTable4 = resultsAppendix4, + AppendixTable5 = resultsAppendix5) + + generatePlot <- function(analysisData, + targetDrug, + tableName) { + tcsOfInterest <- unique(analysisData[, c(""targetId"", ""comparatorId"")]) + plots <- list() + for (i in 1:nrow(tcsOfInterest)) { # i=9 + targetId <- tcsOfInterest$targetId[i] + comparatorId <- tcsOfInterest$comparatorId[i] + tcResult <- analysisData[analysisData$targetId == targetId & analysisData$comparatorId == comparatorId, ] + targetName <- tcResult$targetName[1] + comparatorName <- tcResult$comparatorName[1] + data <- data.frame(database = tcResult$database, + logRr = tcResult$logRr, + logLb = tcResult$logRr + qnorm(0.025) * tcResult$seLogRr, + logUb = tcResult$logRr + qnorm(0.975) * tcResult$seLogRr) + breaks <- c(0.1, 0.25, 0.5, 1, 2, 4, 10) + labels <- c(0.1, paste(""0.25\nFavors"", targetName), 0.5, 1, 2, paste(""4\nFavors"", comparatorName), 10) + plot <- ggplot2::ggplot(data, + ggplot2::aes(x = exp(logRr), + y = database, + xmin = exp(logLb), + xmax = exp(logUb)), + environment = environment()) + + ggplot2::geom_vline(xintercept = breaks, colour = ""#AAAAAA"", lty = 1, size = 0.1) + + ggplot2::geom_vline(xintercept = 1, colour = ""#000000"", lty = 1, size = 1) + + ggplot2::geom_errorbarh(height = 0, size = 2, alpha = 0.7, ggplot2::aes(colour = ""red"")) + + ggplot2::geom_point(shape = 16, size = 4.4, alpha = 0.7, ggplot2::aes(colour = ""red"")) + + ggplot2::coord_cartesian(xlim = c(0.1, 10)) + + ggplot2::scale_x_continuous(""Hazard ratio"", trans = ""log10"", breaks = breaks, labels = labels) + + ggplot2::scale_y_discrete(limits = c(""Meta-analysis"", ""Optum"", ""MDCR"", ""MDCD"", ""CCAE"")) + + ggplot2::theme(text = ggplot2::element_text(size = 15), + panel.grid.minor = ggplot2::element_blank(), + panel.background = ggplot2::element_rect(fill = ""#FAFAFA"",colour = NA), + panel.grid.major = ggplot2::element_line(colour = ""#EEEEEE""), + axis.ticks = ggplot2::element_blank(), + axis.title.y = ggplot2::element_blank(), + axis.title.x = ggplot2::element_blank(), + #axis.text.y = ggplot2::element_blank(), + axis.text.y = ggplot2::element_text(size = 14), + axis.text.x = ggplot2::element_text(size = 13), + legend.position = ""none"") + plots[[length(plots) + 1]] <- plot + } + col1 <- grid::textGrob(paste0(targetDrug, ""-BROAD""), gp = grid::gpar(fontsize = 18)) + col2 <- grid::textGrob(paste0(targetDrug, ""-NARROW""), gp = grid::gpar(fontsize = 18)) + col0 <- grid::textGrob("""") + row1 <- grid::textGrob(""SU"", rot = 90, gp = grid::gpar(fontsize = 18)) + row2 <- grid::textGrob(""DPP-4i"", rot = 90, gp = grid::gpar(fontsize = 18)) + row3 <- grid::textGrob(""GLP-1a"", rot = 90, gp = grid::gpar(fontsize = 18)) + row4 <- grid::textGrob(""TZDs"", rot = 90, gp = grid::gpar(fontsize = 18)) + row5 <- grid::textGrob(""Insulin"", rot = 90, gp = grid::gpar(fontsize = 18)) + row6 <- grid::textGrob(""Metformin"", rot = 90, gp = grid::gpar(fontsize = 18)) + row7 <- grid::textGrob(""Ins. AHAs"", rot = 90, gp = grid::gpar(fontsize = 18)) + row8 <- grid::textGrob(""Other AHAs"", rot = 90, gp = grid::gpar(fontsize = 18)) + if (nrow(tcsOfInterest) == 14) { + plot <- gridExtra::grid.arrange(col0, col1, col2, + row1, plots[[1]], plots[[8]], + row2, plots[[2]], plots[[9]], + row3, plots[[3]], plots[[10]], + row4, plots[[4]], plots[[11]], + row5, plots[[5]], plots[[12]], + row6, plots[[6]], plots[[13]], + row7, plots[[7]], plots[[14]], nrow = 8, + heights = grid::unit(c(5*2, rep(30*2,7)), rep(""mm"",7)), + widths = grid::unit(c(10*2, rep(75*2,2)), rep(""mm"",3))) + height <- 18 + } + if (nrow(tcsOfInterest) == 16) { + plot <- gridExtra::grid.arrange(col0, col1, col2, + row1, plots[[1]], plots[[9]], + row2, plots[[2]], plots[[10]], + row3, plots[[3]], plots[[11]], + row4, plots[[4]], plots[[12]], + row5, plots[[5]], plots[[13]], + row6, plots[[6]], plots[[14]], + row7, plots[[7]], plots[[15]], + row8, plots[[8]], plots[[16]], nrow = 9, + heights = grid::unit(c(5*2, rep(30*2,8)), rep(""mm"",8)), + widths = grid::unit(c(10*2, rep(75*2,2)), rep(""mm"",3))) + height <- 20 + } + plotFile <- file.path(reportFolder, paste0(""hrPlot_"", tableName, "".png"")) + ggplot2::ggsave(filename = plotFile, plot = plot, width = 14, height = height) + } + targetDrugs <- c(""SGLT2i"", ""Canagliflozin"", ""Dapagliflozin"", ""Empagliflozin"", ""SGLT2i"", ""SGLT2i"") + for (i in 1:length(resultSets)) { + generatePlot(analysisData = resultSets[[i]], + targetDrug = targetDrugs[i], + tableName = names(resultSets)[i]) + } +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/R/createHrTable.R",".R","10884","207","#' @export +createHrTable <- function(outputFolders, + databaseNames, + maOutputFolder, + reportFolder) { + loadResultsHois <- function(outputFolder, + fileName) { + shinyDataFolder <- file.path(outputFolder, ""results"", ""shinyData"") + file <- list.files(shinyDataFolder, pattern = ""resultsHois_.*.rds"", full.names = TRUE) + x <- readRDS(file) + if (is.null(x$i2)) + x$i2 <- NA + return(x) + } + results <- lapply(c(outputFolders, maOutputFolder), loadResultsHois) + results <- do.call(rbind, results) + results$targetCohort <- sub(pattern = ""-90"", replacement = """", x = results$targetName) + results$comparatorCohort <- sub(pattern = ""-90"", replacement = """", x = results$comparatorName) + results$comparison <- paste(results$targetCohort, results$comparatorCohort, sep = "" - "") + results$timeAtRisk[results$analysisDescription == ""Time to First Post Index Event Intent to Treat Matching""] <- ""ITT"" + results$timeAtRisk[results$analysisDescription == ""Time to First Post Index Event Per Protocol Matching""] <- ""PP"" + tcosAnalyses <- read.csv(system.file(""settings"", ""tcoAnalysisVariants.csv"", package = ""sglt2iDka""), stringsAsFactors = FALSE) # for correct ordering + tcosAnalyses$tOrder <- match(tcosAnalyses$targetCohortName, c(""SGLT2i-BROAD-90"", + ""SGLT2i-NARROW-90"", + ""Canagliflozin-BROAD-90"", + ""Canagliflozin-NARROW-90"", + ""Dapagliflozin-BROAD-90"", + ""Dapagliflozin-NARROW-90"", + ""Empagliflozin-BROAD-90"", + ""Empagliflozin-NARROW-90"")) + tcosAnalyses$cOrder <- match(tcosAnalyses$comparatorCohortName, c(""SU-BROAD-90"", + ""SU-NARROW-90"", + ""DPP-4i-BROAD-90"", + ""DPP-4i-NARROW-90"", + ""GLP-1a-BROAD-90"", + ""GLP-1a-NARROW-90"", + ""TZDs-BROAD-90"", + ""TZDs-NARROW-90"", + ""Insulin-BROAD-90"", + ""Insulin-NARROW-90"", + ""Metformin-BROAD-90"", + ""Metformin-NARROW-90"", + ""Insulinotropic AHAs-BROAD-90"", + ""Insulinotropic AHAs-NARROW-90"", + ""Other AHAs-BROAD-90"", + ""Other AHAs-NARROW-90"")) + tcosAnalyses <- tcosAnalyses[order(tcosAnalyses$tOrder, tcosAnalyses$cOrder), ] + tcosAnalyses$targetCohort <- sub(pattern = ""-90"", replacement = """", x = tcosAnalyses$targetCohortName) + tcosAnalyses$comparatorCohort <- sub(pattern = ""-90"", replacement = """", x = tcosAnalyses$comparatorCohortName) + comparisonsOfInterest <- unique(paste(tcosAnalyses$targetCohort, tcosAnalyses$comparatorCohort, sep = "" - "")) + + outcomeNames <- unique(results$outcomeName) + timeAtRisks <- unique(results$timeAtRisk) + + fileName <- file.path(reportFolder, paste0(""HRs.xlsx"")) + unlink(fileName) + wb <- XLConnect::loadWorkbook(fileName, create = TRUE) + + for (outcomeName in outcomeNames) { + # outcomeName <- outcomeNames[1] + + XLConnect::createSheet(wb, name = outcomeName) + + header0 <- rep("""", 20) + header0[3] <- ""Intent-to-treat"" + header0[13] <- ""Per protocol"" + XLConnect::writeWorksheet(wb, + sheet = outcomeName, + data = as.data.frame(t(header0)), + startRow = 1, + startCol = 1, + rownames = FALSE, + header = FALSE) + XLConnect::mergeCells(wb, sheet = outcomeName, reference = ""C1:L1"") + XLConnect::mergeCells(wb, sheet = outcomeName, reference = ""M1:T1"") + header1 <- c("""", + """", + ""Exposed (#/PY)"", + """", + ""Outcomes"", + """", + """", + """", + ""HR (95% CI)"", + ""p"", + ""Cal. p"", + ""Null"", + ""Exposed (#/PY)"", + """", + ""Outcomes"", + """", + """", + """", + ""HR (95% CI)"", + ""p"", + ""Cal. p"", + ""Null"") + XLConnect::writeWorksheet(wb, + sheet = outcomeName, + data = as.data.frame(t(header1)), + startRow = 2, + startCol = 1, + rownames = FALSE, + header = FALSE) + XLConnect::mergeCells(wb, sheet = outcomeName, reference = ""C2:D2"") + XLConnect::mergeCells(wb, sheet = outcomeName, reference = ""E2:H2"") + XLConnect::mergeCells(wb, sheet = outcomeName, reference = ""M2:N2"") + XLConnect::mergeCells(wb, sheet = outcomeName, reference = ""O2:R2"") + header2 <- c(""Comparison"", + ""Source"", + ""T"", + ""C"", + ""T"", + ""T-IR"", + ""C"", + ""C-IR"", + """", + """", + """", + """", + ""T"", + ""C"", + ""T"", + ""T-IR"", + ""C"", + ""C-IR"") + XLConnect::writeWorksheet(wb, + sheet = outcomeName, + data = as.data.frame(t(header2)), + startRow = 3, + startCol = 1, + rownames = FALSE, + header = FALSE) + + idx <- results$outcomeName == outcomeName & results$comparison %in% comparisonsOfInterest + + results$dbOrder <- match(results$database, c(""CCAE"", ""MDCD"", ""MDCR"", ""Optum"", ""Meta-analysis"")) + results$comparisonOrder <- match(results$comparison, comparisonsOfInterest) + + results$rr[results$eventsTreated == 0 | results$eventsComparator == 0 | is.na(results$seLogRr) | is.infinite(results$seLogRr)] <- NA + results$ci95lb[results$eventsTreated == 0 | results$eventsComparator == 0 | is.na(results$seLogRr) | is.infinite(results$seLogRr)] <- NA + results$ci95ub[results$eventsTreated == 0 | results$eventsComparator == 0 | is.na(results$seLogRr) | is.infinite(results$seLogRr)] <- NA + + intentToTreat <- results[idx & results$timeAtRisk == ""ITT"", ] + intentToTreat <- intentToTreat[order(intentToTreat$comparisonOrder, intentToTreat$dbOrder), ] + perProtocol <- results[idx & results$timeAtRisk == ""PP"", ] + perProtocol <- perProtocol[order(perProtocol$comparisonOrder, perProtocol$dbOrder), ] + + if (!all.equal(perProtocol$comparison, intentToTreat$comparison) || + !all.equal(perProtocol$database, intentToTreat$database)) { + stop(""Problem with sorting of data"") + } + + formatComparison <- function(x) { + result <- sub(pattern = "" - "", replacement = "" vs. "", x = x) + return(result) + } + formatSampleSize <- function(subjects, days) { + paste(formatC(subjects, big.mark = "","", format=""d""), + formatC(days/365.25, big.mark = "","", format=""d""), + sep = "" / "") + } + formatHr <- function(hr, lb, ub) { + sprintf(""%s (%s-%s)"", + formatC(hr, digits = 2, format = ""f""), + formatC(lb, digits = 2, format = ""f""), + formatC(ub, digits = 2, format = ""f"")) + } + + mainTable <- data.frame(question = formatComparison(intentToTreat$comparison), + source = intentToTreat$database, + titt = formatSampleSize(intentToTreat$treated, intentToTreat$treatedDays), + citt = formatSampleSize(intentToTreat$comparator, intentToTreat$comparatorDays), + oTitt = intentToTreat$eventsTreated, + irTitt = round(intentToTreat$eventsTreated / (intentToTreat$treatedDays / 365.25) * 1000, 2) , + oCitt = intentToTreat$eventsComparator, + irCitt = round(intentToTreat$eventsComparator / (intentToTreat$comparatorDays / 365.25) * 1000, 2), + hritt = formatHr(intentToTreat$rr, intentToTreat$ci95lb, intentToTreat$ci95ub), + pitt = round(intentToTreat$p, 2), + calitt = round(intentToTreat$calP, 2), + nullitt = round(exp(intentToTreat$null_mean), 2), + tpp = formatSampleSize(perProtocol$treated, perProtocol$treatedDays), + cpp = formatSampleSize(perProtocol$comparator, perProtocol$comparatorDays), + oTpp = perProtocol$eventsTreated, + irTpp = round(perProtocol$eventsTreated / (perProtocol$treatedDays / 365.25) * 1000, 2), + oCpp = perProtocol$eventsComparator, + irCpp = round(perProtocol$eventsComparator / (perProtocol$comparatorDays / 365.25) * 1000, 2), + hrpp = formatHr(perProtocol$rr, perProtocol$ci95lb, perProtocol$ci95ub), + ppp = round(perProtocol$p, 2), + calPpp = round(perProtocol$calP, 2), + nullpp = round(exp(perProtocol$null_mean), 2)) + + XLConnect::writeWorksheet(wb, + data = mainTable, + sheet = outcomeName, + startRow = 4, + startCol = 1, + header = FALSE, + rownames = FALSE) + cells <- paste0(""A"", seq(from = 4, to = 309, by = 5), "":A"", seq(from = 8, to = 313, by = 5)) + for (cell in cells) { + XLConnect::mergeCells(wb, sheet = outcomeName, reference = cell) + } + } + XLConnect::saveWorkbook(wb) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/R/CreateTablesAndFiguresForReport.R",".R","1564","32","#' @export +createTableAndFiguresForReport <- function(outputFolders, + databaseNames, + maOutputFolder, + reportFolder) { + if (!file.exists(reportFolder)) + dir.create(reportFolder, recursive = TRUE) + + # population characteristics + sglt2iDka::createPopCharTable(outputFolders, databaseNames, reportFolder) + + # IR tables main + sglt2iDka::createIrTable(outputFolders, databaseNames, reportFolder, sensitivity = FALSE) + sglt2iDka::createIrTableFormatted(outputFolders, databaseNames, reportFolder, sensitivity = FALSE) + + # IR tables sensitivity + sglt2iDka::createIrTable(outputFolders, databaseNames, reportFolder, sensitivity = TRUE) + sglt2iDka::createIrSensitivityTableFormatted(outputFolders, databaseNames, reportFolder) + sglt2iDka::createIrSubgroupsTableFormatted(outputFolders, databaseNames, reportFolder) + + # IR tables dose + sglt2iDka::createIrDoseTable(outputFolders, databaseNames, reportFolder) + sglt2iDka::createIrDoseTableFormatted(outputFolders, databaseNames, reportFolder) + + # HR tables + sglt2iDka::createHrTable(outputFolders, databaseNames, maOutputFolder, reportFolder) + sglt2iDka::createHrTableFormatted(outputFolders, databaseNames, maOutputFolder, reportFolder) + sglt2iDka::createHrPlots(outputFolders, maOutputFolder, reportFolder) + sglt2iDka::createHrHeterogeneityTable(outputFolders, databaseNames, reportFolder) + sglt2iDka::createHrHeterogeneityPlots(outputFolders, databaseNames, reportFolder) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/extras/PackageMaintenance.R",".R","5531","88","# Create analysis details ------------------------------------------------------ +connectionDetails <- DatabaseConnector::createConnectionDetails(dbms = Sys.getenv(""dbms""), + server = Sys.getenv(""server""), + port = as.numeric(Sys.getenv(""port"")), + user = NULL, + password = NULL) + +# estimation settings +sglt2iDka::createEstimateVariants(connectionDetails = connectionDetails, + cohortDefinitionSchema = ""scratch.dbo"", + cohortDefinitionTable = ""epi535_cohort_universe"", + codeListSchema = ""scratch.dbo"", + codeListTable = ""epi535_code_list"", + vocabularyDatabaseSchema = ""vocabulary_20171201.dbo"", + outputFolder = ""inst/settings"") + +sglt2iDka::createAnalysesDetails(outputFolder = ""inst/settings"") + + +# settings to pull data for IR analyses with 60 and 120 gap days --------------- +sglt2iDka::createIrSensitivityVariants(connectionDetails = connectionDetails, + cohortDefinitionSchema = ""scratch.dbo"", + cohortDefinitionTable = ""epi535_cohort_universe"", + outputFolder = ""inst/settings"") + +sglt2iDka::createIrSensitivityAnalysesDetails(outputFolder = ""inst/settings"") + + +# settings to pull data for IR dose-specific analysis -------------------------- +sglt2iDka::createIrDoseVariants(connectionDetails = connectionDetails, + cohortDefinitionSchema = ""scratch.dbo"", + cohortDoseDefinitionTable = ""epi535_cohort_universe_dose"", + cohortDefinitionTable = ""epi535_cohort_universe"", + outputFolder = ""inst/settings"") + +sglt2iDka::createIrDoseAnalysesDetails(outputFolder = ""inst/settings"") + + + + +# Store environment in which the study was executed ---------------------------- +OhdsiRTools::insertEnvironmentSnapshotInPackage(""sglt2iDka"") + + + + +# rename directory locations in outcomeModelReference.rds from run on other box +# ref <- readRDS(""S:/StudyResults/epi_535_4/CCAE/cmOutput/outcomeModelReference.rds"") +# ref$cohortMethodDataFolder <- sub(pattern = ""D:/jweave17"", replacement = ""S:/StudyResults"", x = ref$cohortMethodDataFolder) +# ref$studyPopFile <- sub(pattern = ""D:/jweave17"", replacement = ""S:/StudyResults"", x = ref$studyPopFile) +# ref$sharedPsFile <- sub(pattern = ""D:/jweave17"", replacement = ""S:/StudyResults"", x = ref$sharedPsFile) +# ref$psFile <- sub(pattern = ""D:/jweave17"", replacement = ""S:/StudyResults"", x = ref$psFile) +# ref$strataFile <- sub(pattern = ""D:/jweave17"", replacement = ""S:/StudyResults"", x = ref$strataFile) +# ref$outcomeModelFile <- sub(pattern = ""D:/jweave17"", replacement = ""S:/StudyResults"", x = ref$outcomeModelFile) +# saveRDS(ref, ""S:/StudyResults/epi_535_4/CCAE/cmOutput/outcomeModelReference.rds"") +# +# ref <- readRDS(""S:/StudyResults/epi_535_4/MDCD/cmOutput/outcomeModelReference.rds"") +# ref$cohortMethodDataFolder <- sub(pattern = ""D:"", replacement = ""S:"", x = ref$cohortMethodDataFolder) +# ref$studyPopFile <- sub(pattern = ""D:"", replacement = ""S:"", x = ref$studyPopFile) +# ref$sharedPsFile <- sub(pattern = ""D:"", replacement = ""S:"", x = ref$sharedPsFile) +# ref$psFile <- sub(pattern = ""D:"", replacement = ""S:"", x = ref$psFile) +# ref$strataFile <- sub(pattern = ""D:"", replacement = ""S:"", x = ref$strataFile) +# ref$outcomeModelFile <- sub(pattern = ""D:"", replacement = ""S:"", x = ref$outcomeModelFile) +# saveRDS(ref, ""S:/StudyResults/epi_535_4/MDCD/cmOutput/outcomeModelReference.rds"") + + +# rename directory locations in outcomeModelReference.rds from run on other box +# ref <- readRDS(""S:/StudyResults/epi_535_4/CCAE/cmIrSensitivityOutput/outcomeModelReference.rds"") +# ref$cohortMethodDataFolder <- sub(pattern = ""D:/jweave17"", replacement = ""S:/StudyResults"", x = ref$cohortMethodDataFolder) +# ref$studyPopFile <- sub(pattern = ""D:/jweave17"", replacement = ""S:/StudyResults"", x = ref$studyPopFile) +# ref$sharedPsFile <- sub(pattern = ""D:/jweave17"", replacement = ""S:/StudyResults"", x = ref$sharedPsFile) +# ref$psFile <- sub(pattern = ""D:/jweave17"", replacement = ""S:/StudyResults"", x = ref$psFile) +# ref$strataFile <- sub(pattern = ""D:/jweave17"", replacement = ""S:/StudyResults"", x = ref$strataFile) +# ref$outcomeModelFile <- sub(pattern = ""D:/jweave17"", replacement = ""S:/StudyResults"", x = ref$outcomeModelFile) +# saveRDS(ref, ""S:/StudyResults/epi_535_4/CCAE/cmIrSensitivityOutput/outcomeModelReference.rds"") +# +# ref <- readRDS(""S:/StudyResults/epi_535_4/MDCD/cmIrSensitivityOutput/outcomeModelReference.rds"") +# ref$cohortMethodDataFolder <- sub(pattern = ""D:"", replacement = ""S:"", x = ref$cohortMethodDataFolder) +# ref$studyPopFile <- sub(pattern = ""D:"", replacement = ""S:"", x = ref$studyPopFile) +# ref$sharedPsFile <- sub(pattern = ""D:"", replacement = ""S:"", x = ref$sharedPsFile) +# ref$psFile <- sub(pattern = ""D:"", replacement = ""S:"", x = ref$psFile) +# ref$strataFile <- sub(pattern = ""D:"", replacement = ""S:"", x = ref$strataFile) +# ref$outcomeModelFile <- sub(pattern = ""D:"", replacement = ""S:"", x = ref$outcomeModelFile) +# saveRDS(ref, ""S:/StudyResults/epi_535_4/MDCD/cmIrSensitivityOutput/outcomeModelReference.rds"") + + + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/extras/codeToRun.R",".R","5192","102","# Global settings --------------------------------------------------------------------- +options(fftempdir = ""S:/FFtemp"") +maxCores <- parallel::detectCores() + +mailSettings <- list(from = Sys.getenv(""emailAddress""), + to = c(Sys.getenv(""emailAddress"")), + smtp = list(host.name = Sys.getenv(""emailHost""), port = 25, + user.name = Sys.getenv(""emailAddress""), + passwd = Sys.getenv(""emailPassword""), ssl = FALSE), + authenticate = FALSE, + send = TRUE) + +connectionDetails <- DatabaseConnector::createConnectionDetails(dbms = Sys.getenv(""dbms""), + server = Sys.getenv(""server""), + port = as.numeric(Sys.getenv(""port"")), + user = NULL, + password = NULL) + +cohortDefinitionSchema <- ""scratch.dbo"" +cohortDefinitionTable <- ""epi535_cohort_universe"" +codeListSchema <- ""scratch.dbo"" +codeListTable <- ""epi535_code_list"" +vocabularyDatabaseSchema <- ""vocabulary_20171201.dbo"" +studyFolder <- ""S:/StudyResults/epi_535_4"" + + +# MDCR settings ---------------------------------------------------------------- +cdmDatabaseSchema = ""cdm_truven_mdcr_v698.dbo"" +databaseName <- ""MDCR"" +outputFolder <- file.path(studyFolder, databaseName) +cohortDatabaseSchema <- ""scratch.dbo"" +cohortTable <- ""epi535_cohorts_mdcr"" + +# CCAE settings ---------------------------------------------------------------- +cdmDatabaseSchema <- ""cdm_truven_ccae_v697.dbo"" +databaseName <- ""CCAE"" +outputFolder <- file.path(studyFolder, databaseName) +cohortDatabaseSchema = ""scratch.dbo"" +cohortTable = ""epi535_cohorts_ccae"" + +# MDCD settings ---------------------------------------------------------------- +cdmDatabaseSchema = ""cdm_truven_mdcd_v699.dbo"" +databaseName <- ""MDCD"" +outputFolder <- file.path(studyFolder, databaseName) +cohortDatabaseSchema <- ""scratch.dbo"" +cohortTable <- ""epi535_cohorts_mdcd"" + +# Optum SES settings ----------------------------------------------------------- +cdmDatabaseSchema = ""cdm_optum_extended_ses_v694.dbo"" +databaseName <- ""Optum"" +outputFolder <- file.path(studyFolder, databaseName) +cohortDatabaseSchema <- ""scratch.dbo"" +cohortTable <- ""epi535_cohorts_optum_ses"" + + +# Database-specific execution--------------------------------------------------- +OhdsiRTools::runAndNotify(expression = { + sglt2iDka::execute(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + cohortDatabaseSchema = cohortDatabaseSchema, + cohortTable = cohortTable, + oracleTempSchema = NULL, + outputFolder = outputFolder, + codeListSchema = codeListSchema, + codeListTable = codeListTable, + vocabularyDatabaseSchema = vocabularyDatabaseSchema, + databaseName = databaseName, + runAnalyses = FALSE, + getMultiTherapyData = FALSE, + runDiagnostics = TRUE, + packageResults = FALSE, + runIrSensitivity = FALSE, + packageIrSensitivityResults = FALSE, + runIrDose = FALSE, + packageIrDose = FALSE, + maxCores = maxCores, + minCellCount = 5) +}, mailSettings = mailSettings, label = paste0(""EPI535_"", databaseName), stopOnWarning = FALSE) + + +# execute meta analysis -------------------------------------------------------- +OhdsiRTools::runAndNotify(expression = { + sglt2iDka::doMetaAnalysis(outputFolders = c(file.path(studyFolder, ""CCAE""), + file.path(studyFolder, ""MDCD""), + file.path(studyFolder, ""MDCR""), + file.path(studyFolder, ""Optum"")), + maOutputFolder = file.path(studyFolder, ""metaAnalysis""), + maxCores = maxCores) +}, mailSettings = mailSettings, label = ""EPI535_MetaAnalysis"", stopOnWarning = FALSE) + + +# generate report tables ------------------------------------------------------- +OhdsiRTools::runAndNotify(expression = { + sglt2iDka::createTableAndFiguresForReport(outputFolders = c(file.path(studyFolder, ""CCAE""), + file.path(studyFolder, ""MDCD""), + file.path(studyFolder, ""MDCR""), + file.path(studyFolder, ""Optum"")), + databaseNames = c(""CCAE"", ""MDCD"", ""MDCR"", ""Optum""), + maOutputFolder = file.path(studyFolder, ""metaAnalysis""), + reportFolder = file.path(studyFolder, ""report2"")) +}, mailSettings = mailSettings, label = ""EPI535_ReportTables"", stopOnWarning = FALSE) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/extras/EvidenceExplorer/global.R",".R","5228","89","blind <- FALSE + +fileNames <- list.files(path = ""data"", pattern = ""resultsHois_.*.rds"", full.names = TRUE) +resultsHois <- lapply(fileNames, readRDS) +allColumns <- unique(unlist(lapply(resultsHois, colnames))) +addMissingColumns <- function(results) { + presentCols <- colnames(results) + missingCols <- allColumns[!(allColumns %in% presentCols)] + for (missingCol in missingCols) { + results[, missingCol] <- rep(NA, nrow(results)) + } + return(results) +} +resultsHois <- lapply(resultsHois, addMissingColumns) +resultsHois <- do.call(rbind, resultsHois) +resultsHois <- resultsHois[, -c(41:312)] # drop TAR distribution columns + +fileNames <- list.files(path = ""data"", pattern = ""resultsNcs_.*.rds"", full.names = TRUE) +resultsNcs <- lapply(fileNames, readRDS) +resultsNcs <- do.call(rbind, resultsNcs) + +fileNames <- list.files(path = ""data"", pattern = ""covarNames_.*.rds"", full.names = TRUE) +covarNames <- lapply(fileNames, readRDS) +covarNames <- do.call(rbind, covarNames) +covarNames <- unique(covarNames) + +formatDrug <- function(x) { + x <- sub(""-90"", """", x) + x <- sub(""Insulinotropic"", ""Insul."", x) +} +resultsHois$targetDrug <- formatDrug(resultsHois$targetName) +resultsHois$comparatorDrug <- formatDrug(resultsHois$comparatorName) + +resultsHois$tOrder <- match(resultsHois$targetName, c(""SGLT2i-BROAD-90"", + ""SGLT2i-NARROW-90"", + ""Canagliflozin-BROAD-90"", + ""Canagliflozin-NARROW-90"", + ""Dapagliflozin-BROAD-90"", + ""Dapagliflozin-NARROW-90"", + ""Empagliflozin-BROAD-90"", + ""Empagliflozin-NARROW-90"")) +resultsHois$cOrder <- match(resultsHois$comparatorName, c(""SU-BROAD-90"", + ""SU-NARROW-90"", + ""DPP-4i-BROAD-90"", + ""DPP-4i-NARROW-90"", + ""GLP-1a-BROAD-90"", + ""GLP-1a-NARROW-90"", + ""TZDs-BROAD-90"", + ""TZDs-NARROW-90"", + ""Insulin-BROAD-90"", + ""Insulin-NARROW-90"", + ""Metformin-BROAD-90"", + ""Metformin-NARROW-90"", + ""Insulinotropic AHAs-BROAD-90"", + ""Insulinotropic AHAs-NARROW-90"", + ""Other AHAs-BROAD-90"", + ""Other AHAs-NARROW-90"")) +resultsHois$dbOrder <- match(resultsHois$database, c(""CCAE"", ""MDCD"",""MDCR"", ""Optum"", ""Meta-analysis"")) + +resultsHois <- resultsHois[order(resultsHois$tOrder, resultsHois$cOrder, resultsHois$dbOrder), ] + +resultsHois$rr[resultsHois$eventsTreated == 0 | resultsHois$eventsComparator == 0 | is.na(resultsHois$seLogRr) | is.infinite(resultsHois$seLogRr)] <- NA +resultsHois$ci95lb[resultsHois$eventsTreated == 0 | resultsHois$eventsComparator == 0 | is.na(resultsHois$seLogRr) | is.infinite(resultsHois$seLogRr)] <- NA +resultsHois$ci95ub[resultsHois$eventsTreated == 0 | resultsHois$eventsComparator == 0 | is.na(resultsHois$seLogRr) | is.infinite(resultsHois$seLogRr)] <- NA + +resultsHois$comparison <- paste(resultsHois$targetDrug, resultsHois$comparatorDrug, sep = "" vs. "") +comparisons <- unique(resultsHois$comparison) +outcomes <- unique(resultsHois$outcomeName) + +outcomes[outcomes == ""DKA (IP & ER)""] <- ""DKA (IP or ER)"" +resultsHois$outcomeName[resultsHois$outcomeName == ""DKA (IP & ER)""] <- ""DKA (IP or ER)"" + +resultsHois$timeAtRisk[resultsHois$analysisDescription == ""Time to First Post Index Event Intent to Treat Matching""] <- ""Intent-to-Treat"" +resultsHois$timeAtRisk[resultsHois$analysisDescription == ""Time to First Post Index Event Per Protocol Matching""] <- ""Per-Protocol"" +timeAtRisks <- unique(resultsHois$timeAtRisk) +timeAtRisks <- timeAtRisks[order(timeAtRisks)] +dbs <- unique(resultsHois$database) + +heterogeneous <- resultsHois[resultsHois$database == ""Meta-analysis"" & !is.na(resultsHois$i2) & resultsHois$i2 > 0.4, c(""targetId"", ""comparatorId"", ""outcomeId"", ""analysisId"")] +heterogeneous$heterogeneous <- ""yes"" +resultsHois <- merge(resultsHois, heterogeneous, all.x = TRUE) +resultsHois$heterogeneous[is.na(resultsHois$heterogeneous)] <- """" + +dbInfoHtml <- readChar(""DataSources.html"", file.info(""DataSources.html"")$size) +comparisonsInfoHtml <- readChar(""Comparisons.html"", file.info(""Comparisons.html"")$size) +outcomesInfoHtml <- readChar(""Outcomes.html"", file.info(""Outcomes.html"")$size) +tarInfoHtml <- readChar(""Tar.html"", file.info(""Tar.html"")$size) + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/extras/EvidenceExplorer/server.R",".R","20832","525","library(shiny) +library(DT) +library(ggplot2) +source(""global.R"") +source(""functions.R"") +source(""Table1.R"") + +mainColumns <- c(""database"", + ""timeAtRisk"", + ""heterogeneous"", + ""rr"", + ""ci95lb"", + ""ci95ub"", + ""p"", + ""calP"") + +mainColumnNames <- c(""Data source"", + ""Time at risk"", + "" 0.4)?\"">Ht."", + ""HR"", + ""CI95LB"", + ""CI95UB"", + ""P"", + ""Cal. P"") + +powerColumns <- c(""treated"", + ""comparator"", + ""treatedDays"", + ""comparatorDays"", + ""eventsTreated"", + ""eventsComparator"", + ""irTreated"", + ""irComparator"", + ""mdrr"") + +powerColumnNames <- c(""Target subjects"", + ""Comparator subjects"", + ""Target days"", + ""Comparator days"", + ""Target events"", + ""Comparator events"", + ""Target IR (per 1,000 PY)"", + ""Comparator IR (per 1,000 PY)"", + ""MDRR"") + +shinyServer(function(input, output) { + + tableSubset <- reactive({ + idx <- resultsHois$comparison == input$comparison & + resultsHois$outcomeName == input$outcome & + resultsHois$timeAtRisk %in% input$timeAtRisk & + resultsHois$database %in% input$db + resultsHois[idx, ] + }) + + selectedRow <- reactive({ + idx <- input$mainTable_rows_selected + if (is.null(idx)) { + return(NULL) + } else { + return(tableSubset()[idx, ]) + } + }) + + forestPlotSubset <- reactive({ + row <- selectedRow() + if (is.null(row)) { + return(NULL) + } else { + subset <- resultsHois[resultsHois$comparison == row$comparison & + resultsHois$outcomeId == row$outcomeId, ] + subset$dbOrder <- match(subset$database, c(""CCAE"", ""MDCD"",""MDCR"", ""Optum"", ""Meta-analysis"")) + subset$timeAtRiskOrder <- match(subset$timeAtRisk, c(""Intent-to-Treat"", + ""Per-Protocol"")) + + subset <- subset[order(subset$dbOrder, + subset$timeAtRiskOrder), ] + subset$rr[is.na(subset$seLogRr)] <- NA + subset$database <- factor(subset$database, levels = c(""CCAE"", ""MDCD"",""MDCR"", ""Optum"", ""Meta-analysis"")) + subset$timeAtRisk <- factor(subset$timeAtRisk, levels = c(""Intent-to-Treat"", ""Per-Protocol"")) + subset$displayOrder <- nrow(subset):1 + return(subset) + } + }) + + output$rowIsSelected <- reactive({ + return(!is.null(selectedRow())) + }) + outputOptions(output, ""rowIsSelected"", suspendWhenHidden = FALSE) + + output$isMetaAnalysis <- reactive({ + row <- selectedRow() + isMetaAnalysis <- !is.null(row) && row$database == ""Meta-analysis"" + if (isMetaAnalysis) { + hideTab(""tabsetPanel"", ""Population characteristics"") + hideTab(""tabsetPanel"", ""Propensity scores"") + hideTab(""tabsetPanel"", ""Covariate balance"") + hideTab(""tabsetPanel"", ""Kaplan-Meier"") + } else { + showTab(""tabsetPanel"", ""Population characteristics"") + showTab(""tabsetPanel"", ""Propensity scores"") + showTab(""tabsetPanel"", ""Covariate balance"") + showTab(""tabsetPanel"", ""Kaplan-Meier"") + } + return(isMetaAnalysis) + }) + outputOptions(output, ""isMetaAnalysis"", suspendWhenHidden = FALSE) + + balance <- reactive({ + row <- selectedRow() + if (is.null(row) || row$database == ""Meta-analysis"") { + return(NULL) + } else { + fileName <- paste0(""bal_a"", row$analysisId, + ""_t"", row$targetId, + ""_c"", row$comparatorId, + ""_o"", row$outcomeId, + ""_"", row$database,"".rds"") + data <- readRDS(file.path(""data"", fileName)) + data$absBeforeMatchingStdDiff <- abs(data$beforeMatchingStdDiff) + data$absAfterMatchingStdDiff <- abs(data$afterMatchingStdDiff) + data <- merge(data, covarNames) + return(data) + } + }) + + output$mainTable <- renderDataTable({ + table <- tableSubset()[, mainColumns] + if (nrow(table) == 0) + return(NULL) + table$rr[table$rr > 100] <- NA + table$rr <- formatC(table$rr, digits = 2, format = ""f"") + table$ci95lb <- formatC(table$ci95lb, digits = 2, format = ""f"") + table$ci95ub <- formatC(table$ci95ub, digits = 2, format = ""f"") + table$p <- formatC(table$p, digits = 2, format = ""f"") + table$calP <- formatC(table$calP, digits = 2, format = ""f"") + colnames(table) <- mainColumnNames + options = list(pageLength = 15, + searching = FALSE, + lengthChange = TRUE, + ordering = TRUE, + paging = TRUE) + selection = list(mode = ""single"", target = ""row"") + table <- datatable(table, + options = options, + selection = selection, + rownames = FALSE, + escape = FALSE, + class = ""stripe nowrap compact"") + return(table) + }) + + output$powerTableCaption <- renderUI({ + row <- selectedRow() + if (!is.null(row)) { + text <- ""Table 1a. Number of subjects, follow-up time (in days), number of outcome + events, and event incidence rate (IR) per 1,000 patient years (PY) in the target (%s) and + comparator (%s) group after matching, as well as the minimum detectable relative risk (MDRR). + Note that the IR does not account for any stratification."" + return(HTML(sprintf(text, row$targetDrug, row$comparatorDrug))) + } else { + return(NULL) + } + }) + + output$powerTable <- renderTable({ + table <- selectedRow() + if (!is.null(table)) { + table$irTreated <- formatC(1000 * table$eventsTreated / (table$treatedDays / 365.25), digits = 2, format = ""f"") + table$irComparator <- formatC(1000 * table$eventsComparator / (table$comparatorDays / 365.25), digits = 2, format = ""f"") + + table$treated <- formatC(table$treated, big.mark = "","", format = ""d"") + table$comparator <- formatC(table$comparator, big.mark = "","", format = ""d"") + table$treatedDays <- formatC(table$treatedDays, big.mark = "","", format = ""d"") + table$comparatorDays <- formatC(table$comparatorDays, big.mark = "","", format = ""d"") + table$eventsTreated <- formatC(table$eventsTreated, big.mark = "","", format = ""d"") + table$eventsComparator <- formatC(table$eventsComparator, big.mark = "","", format = ""d"") + table$mdrr <- formatC(table$mdrr, digits = 2, format = ""f"") + if (table$database == ""Meta-analysis"") { + table <- table[, c(powerColumns, ""i2"")] + colnames(table) <- c(powerColumnNames, ""I2"") + } else { + table <- table[, powerColumns] + colnames(table) <- powerColumnNames + } + return(table) + } else { + return(table) + } + }) + + output$timeAtRiskTableCaption <- renderUI({ + row <- selectedRow() + if (!is.null(row)) { + text <- ""Table 1b. Time (days) at risk distribution expressed as mean, standard deviation (SD), + minimum (min), median, and maximum (max) in the target + (%s) and comparator (%s) cohort after matching."" + return(HTML(sprintf(text, row$targetDrug, row$comparatorDrug))) + } else { + return(NULL) + } + }) + + output$timeAtRiskTable <- renderTable({ + row <- selectedRow() + if (!is.null(table)) { + table <- data.frame(Cohort = c(""Target"", ""Comparator""), + Mean = formatC(c(row$tarTargetMean, row$tarComparatorMean), digits = 1, format = ""f""), + SD = formatC(c(row$tarTargetSd, row$tarComparatorSd), digits = 1, format = ""f""), + Min = formatC(c(row$tarTargetMin, row$tarComparatorMin), big.mark = "","", format = ""d""), + Median = formatC(c(row$tarTargetMedian, row$tarComparatorMedian), big.mark = "","", format = ""d""), + Max = formatC(c(row$tarTargetMax, row$tarComparatorMax), big.mark = "","", format = ""d"")) + return(table) + } else { + return(table) + } + }) + + output$table1Caption <- renderUI({ + bal <- balance() + if (!is.null(bal)) { + row <- selectedRow() + text <- ""Table 2. Select characteristics before and after matching, showing the + percentage of subjects with the characteristics in the target (%s) and comparator (%s) group, as + well as the standardized difference of the means."" + return(HTML(sprintf(text, row$targetDrug, row$comparatorDrug))) + } else { + return(NULL) + } + }) + + output$table1Table <- renderDataTable({ + bal <- balance() + if (!is.null(bal)) { + row <- selectedRow() + fileName <- paste0(""multiTherBal_a"", row$analysisId, + ""_t"", row$targetId, + ""_c"", row$comparatorId, + ""_o"", row$outcomeId, + ""_"", row$database,"".rds"") + multiTherapyBalance <- readRDS(file.path(""data"", fileName)) + bal$absBeforeMatchingStdDiff <- NULL + bal$absAfterMatchingStdDiff <- NULL + multiTherapyBalance <- multiTherapyBalance[, colnames(bal)] + bal <- rbind(bal, multiTherapyBalance) + table1 <- prepareTable1(bal, + beforeTargetPopSize = row$treatedBefore, + beforeComparatorPopSize = row$comparatorBefore, + afterTargetPopSize = row$treated, + afterComparatorPopSize = row$comparator, + beforeLabel = ""Before matching"", + afterLabel = ""After matching"") + container <- htmltools::withTags(table( + class = 'display', + thead( + tr( + th(rowspan = 3, ""Characteristic""), + th(colspan = 3, class = ""dt-center"", ""Before matching""), + th(colspan = 3, class = ""dt-center"", ""After matching"") + ), + tr( + lapply(table1[1, 2:ncol(table1)], th) + ), + tr( + lapply(table1[2, 2:ncol(table1)], th) + ) + ) + )) + options <- list(columnDefs = list(list(className = 'dt-right', targets = 1:6)), + searching = FALSE, + ordering = FALSE, + paging = FALSE, + bInfo = FALSE) + table1 <- datatable(table1[3:nrow(table1), ], + options = options, + rownames = FALSE, + escape = FALSE, + container = container, + class = ""stripe nowrap compact"") + return(table1) + } else { + return(NULL) + } + }) + + output$psPlot <- renderPlot({ + row <- selectedRow() + if (!is.null(row) && row$database != ""Meta-analysis"") { + fileName <- paste0(""ps_a"", row$analysisId, + ""_t"", row$targetId, + ""_c"", row$comparatorId, + ""_"", row$database,"".rds"") + data <- readRDS(file.path(""data"", fileName)) + data$GROUP <- row$targetDrug + data$GROUP[data$treatment == 0] <- row$comparatorDrug + data$GROUP <- factor(data$GROUP, levels = c(row$targetDrug, + row$comparatorDrug)) + plot <- ggplot2::ggplot(data, ggplot2::aes(x = preferenceScore, y = y, color = GROUP, group = GROUP, fill = GROUP)) + + ggplot2::geom_area(position = ""identity"") + + ggplot2::scale_fill_manual(values = c(rgb(0.8, 0, 0, alpha = 0.5), rgb(0, 0, 0.8, alpha = 0.5))) + + ggplot2::scale_color_manual(values = c(rgb(0.8, 0, 0, alpha = 0.5), rgb(0, 0, 0.8, alpha = 0.5))) + + ggplot2::scale_x_continuous(""Preference score"", limits = c(0, 1)) + + ggplot2::scale_y_continuous(""Density"") + + ggplot2::theme(legend.title = ggplot2::element_blank(), + legend.position = ""top"", + legend.direction = ""horizontal"", + text = ggplot2::element_text(size = 15)) + return(plot) + } else { + return(NULL) + } + }) + + output$balancePlotCaption <- renderUI({ + bal <- balance() + if (!is.null(bal)) { + row <- selectedRow() + text <- ""Figure 2. Covariate balance before and after matching. Each dot represents + the standardizes difference of means for a single covariate before and after matching on the propensity + score. Move the mouse arrow over a dot for more details."" + return(HTML(sprintf(text))) + } else { + return(NULL) + } + }) + + output$balancePlot <- renderPlot({ + bal <- balance() + if (!is.null(bal)) { + row <- selectedRow() + plotBalance(bal, + beforeLabel = ""Std. diff. before matching"", + afterLabel = ""Std. diff. after matching"") + } else { + return(NULL) + } + }) + + output$hoverInfoBalanceScatter <- renderUI({ + # Hover-over adapted from https://gitlab.com/snippets/16220 + bal <- balance() + if (is.null(bal)) + return(NULL) + row <- selectedRow() + hover <- input$plotHoverBalanceScatter + point <- nearPoints(bal, hover, threshold = 5, maxpoints = 1, addDist = TRUE) + if (nrow(point) == 0) return(NULL) + + # calculate point position INSIDE the image as percent of total dimensions + # from left (horizontal) and from top (vertical) + left_pct <- (hover$x - hover$domain$left) / (hover$domain$right - hover$domain$left) + top_pct <- (hover$domain$top - hover$y) / (hover$domain$top - hover$domain$bottom) + + # calculate distance from left and bottom side of the picture in pixels + left_px <- hover$range$left + left_pct * (hover$range$right - hover$range$left) + top_px <- hover$range$top + top_pct * (hover$range$bottom - hover$range$top) + + # create style property fot tooltip + # background color is set so tooltip is a bit transparent + # z-index is set so we are sure are tooltip will be on top + style <- paste0(""position:absolute; z-index:100; background-color: rgba(245, 245, 245, 0.85); "", + ""left:"", left_px - 251, ""px; top:"", top_px - 150, ""px; width:500px;"") + + # actual tooltip created as wellPanel + beforeMatchingStdDiff <- formatC(point$beforeMatchingStdDiff, digits = 2, format = ""f"") + afterMatchingStdDiff <- formatC(point$afterMatchingStdDiff, digits = 2, format = ""f"") + div( + style=""position: relative; width: 0; height: 0"", + wellPanel( + style = style, + p(HTML(paste0("" Covariate: "", point$covariateName, ""
"", + "" Std. diff before matching: "", beforeMatchingStdDiff, ""
"", + "" Std. diff after matching: "", afterMatchingStdDiff))) + ) + ) + }) + + output$negativeControlPlot <- renderPlot({ + row <- selectedRow() + if (!is.null(row)) { + ncs <- resultsNcs[resultsNcs$targetId == row$targetId & + resultsNcs$comparatorId == row$comparatorId & + resultsNcs$analysisId == row$analysisId & + resultsNcs$database == row$database, ] + fileName <- paste0(""null_a"", row$analysisId, + ""_t"", row$targetId, + ""_c"", row$comparatorId, + ""_"",row$database,"".rds"") + if (file.exists(file.path(""data"", fileName))) { + null <- readRDS(file.path(""data"", fileName)) + } else { + null <- NULL + } + plot <- EmpiricalCalibration::plotCalibrationEffect(logRrNegatives = ncs$logRr, + seLogRrNegatives = ncs$seLogRr, + logRrPositives = row$logRr, + seLogRrPositives = row$seLogRr, + null = null, + xLabel = ""Hazard ratio"", + showCis = !is.null(null)) + plot <- plot + ggplot2::theme(text = ggplot2::element_text(size = 15)) + return(plot) + } else { + return(NULL) + } + }) + + output$kaplanMeierPlot <- renderPlot({ + row <- selectedRow() + if (!is.null(row)) { + fileName <- paste0(""km_a"", row$analysisId, + ""_t"", row$targetId, + ""_c"", row$comparatorId, + ""_o"", row$outcomeId, + ""_"",row$database,"".rds"") + if (file.exists(file.path(""data"", fileName))) { + plot <- readRDS(file.path(""data"", fileName)) + return(grid::grid.draw(plot)) + } + } + return(NULL) + }, res = 100) + + output$kmPlotCaption <- renderUI({ + bal <- balance() + if (!is.null(bal)) { + row <- selectedRow() + text <- ""Table 5. Kaplan Meier plot, showing survival as a function of time. This plot + is adjusted for the propensity score matching: The target curve (%s) shows the actual observed survival. The + comparator curve (%s) applies reweighting to approximate the counterfactual of what the target survival + would look like had the target cohort been exposed to the comparator instead. The shaded area denotes + the 95 percent confidence interval."" + return(HTML(sprintf(text, row$targetDrug, row$comparatorDrug))) + } else { + return(NULL) + } + }) + + output$forestPlot <- renderPlot({ + row <- selectedRow() + if (!is.null(row)) { + subset <- forestPlotSubset() + return(plotForest(subset, row)) + } + return(NULL) + }, height = 500) + + output$hoverInfoForestPlot <- renderUI({ + # Hover-over adapted from https://gitlab.com/snippets/16220 + subset <- forestPlotSubset() + if (is.null(subset)) + return(NULL) + hover <- input$plotHoverForestPlot + point <- nearPoints(subset, hover, threshold = 5, maxpoints = 1, addDist = TRUE) + if (nrow(point) == 0) return(NULL) + # calculate point position INSIDE the image as percent of total dimensions + # from left (horizontal) and from top (vertical) + left_pct <- (hover$x - hover$domain$left) / (hover$domain$right - hover$domain$left) + top_pct <- (hover$domain$top - hover$y) / (hover$domain$top - hover$domain$bottom) + + # calculate distance from left and bottom side of the picture in pixels + left_px <- hover$range$left + left_pct * (hover$range$right - hover$range$left) + top_px <- hover$range$top + top_pct * (hover$range$bottom - hover$range$top) + + # create style property fot tooltip + # background color is set so tooltip is a bit transparent + # z-index is set so we are sure are tooltip will be on top + style <- paste0(""position:absolute; z-index:100; background-color: rgba(245, 245, 245, 0.85); "", + ""left:100px; top:"", top_px - 200, ""px; width:500px;"") + + # actual tooltip created as wellPanel + hr <- sprintf(""%.2f (%.2f - %.2f)"", point$rr, point$ci95lb, point$ci95ub) + div( + style=""position: relative; width: 0; height: 0"", + wellPanel( + style = style, + p(HTML(paste0("" Database: "", point$database, ""
"", + "" Time at risk: "", point$timeAtRisk, ""
"", + "" Harard ratio (95% CI): "", hr, ""
""))) + ) + ) + }) + + observeEvent(input$dbInfo, { + showModal(modalDialog( + title = ""Data sources"", + easyClose = TRUE, + footer = NULL, + size = ""l"", + HTML(dbInfoHtml) + )) + }) + + observeEvent(input$comparisonsInfo, { + showModal(modalDialog( + title = ""Comparisons"", + easyClose = TRUE, + footer = NULL, + size = ""l"", + HTML(comparisonsInfoHtml) + )) + }) + + observeEvent(input$outcomesInfo, { + showModal(modalDialog( + title = ""Outcomes"", + easyClose = TRUE, + footer = NULL, + size = ""l"", + HTML(outcomesInfoHtml) + )) + }) + + observeEvent(input$tarInfo, { + showModal(modalDialog( + title = ""Time-at-risk"", + easyClose = TRUE, + footer = NULL, + size = ""l"", + HTML(tarInfoHtml) + )) + }) + +}) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/extras/EvidenceExplorer/functions.R",".R","3522","55","plotBalance <- function(balance, + beforeLabel = ""Before matching"", + afterLabel = ""After matching"") { + limits <- c(min(c(balance$absBeforeMatchingStdDiff, balance$absAfterMatchingStdDiff), na.rm = TRUE), + max(c(balance$absBeforeMatchingStdDiff, balance$absAfterMatchingStdDiff), na.rm = TRUE)) + plot <- ggplot2::ggplot(balance, + ggplot2::aes(x = absBeforeMatchingStdDiff, y = absAfterMatchingStdDiff)) + + ggplot2::geom_point(color = rgb(0, 0, 0.8, alpha = 0.3), shape = 16, size = 2) + + ggplot2::geom_abline(slope = 1, intercept = 0, linetype = ""dashed"") + + ggplot2::geom_hline(yintercept = 0) + + ggplot2::geom_vline(xintercept = 0) + + ggplot2::scale_x_continuous(beforeLabel, limits = limits) + + ggplot2::scale_y_continuous(afterLabel, limits = limits) + + ggplot2::theme(text = ggplot2::element_text(size = 15)) + return(plot) +} + +plotForest <- function(subset, row) { + comparatorName <- row$comparatorDrug + breaks <- c(0.1, 0.25, 0.5, 1, 2, 4, 6, 8, 10) + labels <- c(0.1, paste(""0.25\nFavors"" , row$targetDrug), 0.5, 1, 2, paste(""4\nFavors"" , row$comparatorDrug), 6, 8, 10) + col <- c(rgb(0, 0, 0.8, alpha = 1), rgb(0.8, 0.4, 0, alpha = 1)) + colFill <- c(rgb(0, 0, 1, alpha = 0.5), rgb(1, 0.4, 0, alpha = 0.5)) + highlight <- subset[subset$targetId == row$targetId & + subset$comparatorId == row$comparatorId & + subset$outcomeId == row$outcomeId & + subset$analysisId == row$analysisId & + subset$database == row$database, ] + plot <- ggplot2::ggplot(subset, ggplot2::aes(x = rr, + y = displayOrder, + xmin = ci95lb, + xmax = ci95ub, + fill = timeAtRisk), environment = environment()) + + ggplot2::geom_vline(xintercept = breaks, colour = ""#AAAAAA"", lty = 1, size = 0.2) + + ggplot2::geom_vline(xintercept = 1, colour = ""#000000"", lty = 1, size = 0.5) + + ggplot2::geom_errorbarh(height = 0, alpha = 0.7, size = 1.5, aes(colour = timeAtRisk)) + + ggplot2::geom_point(shape = 18, size = 5, alpha = 0.7, aes(colour = timeAtRisk)) + + ggplot2::geom_errorbarh(height = 0, alpha = 1, size = 1.5, color = rgb(0,0,0), data = highlight, show.legend = FALSE) + + ggplot2::geom_point(shape = 18, size = 5, color = rgb(0,0,0), alpha = 1, data = highlight, show.legend = FALSE) + + ggplot2::coord_cartesian(xlim = c(0.1, 10), clip = ""off"") + + ggplot2::scale_x_continuous(""Hazard ratio"", trans = ""log10"", breaks = breaks, labels = labels) + + ggplot2::scale_y_discrete() + + ggplot2::facet_grid(database ~ ., scales = ""free_y"", space = ""free"") + + ggplot2::labs(color = ""Time-at-risk"", fill = ""Time-at-risk"") + + ggplot2::theme(text = ggplot2::element_text(size = 15), + panel.grid.minor = ggplot2::element_blank(), + panel.background = ggplot2::element_rect(fill = ""gray93"", colour = NA), # ""#FAFAFA"" + panel.grid.major = ggplot2::element_line(colour = ""#EEEEEE""), + axis.ticks = ggplot2::element_blank(), + axis.title.y = ggplot2::element_blank(), + axis.title.x = ggplot2::element_blank(), + axis.text.y = ggplot2::element_blank(), + legend.position = ""top"") + return(plot) +}","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/extras/EvidenceExplorer/ui.R",".R","11286","93","library(shiny) +library(DT) + +shinyUI(fluidPage(style = 'width:1500px;', + titlePanel(HTML(paste(""

Diabetic Ketoacidosis in Patients With Type 2 Diabetes Treated With Sodium Glucose Co-transporter 2 Inhibitors Versus Other Antihyperglycemic Agents: An Observational Study of Four US Administrative Claims Databases

"", if(blind){""*Blinded*""}else{""""})), windowTitle = ""Comparison of SGLT2is vs. Other AHAs""), + tags$head(tags$style(type=""text/css"", "" + #loadmessage { + position: fixed; + top: 0px; + left: 0px; + width: 100%; + padding: 5px 0px 5px 0px; + text-align: center; + font-weight: bold; + font-size: 100%; + color: #000000; + background-color: #ADD8E6; + z-index: 105; + } + "")), + conditionalPanel(condition=""$('html').hasClass('shiny-busy')"", + tags$div(""Procesing..."",id=""loadmessage"")), + + tabsetPanel(id = ""mainTabsetPanel"", + tabPanel(""About"", + HTML(""
""), + div(p(""These research results are from a retrospective, real-world observational study to evaluate the risk of diabetic ketoacidosis among patients with type 2 diabetes mellitus treated with antihyperglycemic agents. This web-based application provides an interactive platform to explore all analysis results generated as part of this study, as a supplement to a full manuscript which has been submitted to peer-reviewed, scientific journal. During the review period, these results are considered under embargo and should not be disclosed without explicit permission and consent from the authors.""), style=""border: 1px solid black; padding: 5px;""), + HTML(""
""), + HTML(""
""), + p(""Below is the abstract of the submitted manuscript that summarizes the collective findings:""), + HTML(""
""), + p(tags$strong(""Purpose:""), ""To compare the incidence of diabetic ketoacidosis (DKA) among patients with type 2 diabetes mellitus (T2DM) who were new users of sodium glucose co-transporter 2 inhibitors (SGLT2i) versus other classes of antihyperglycemic agents (AHAs).""), + p(tags$strong(""Methods:""), ""Patients were identified from four large US claims databases using broad (all T2DM patients) and narrow (intended to exclude patients with T1DM or secondary diabetes misclassified as T2DM) definitions of T2DM. New users of SGLT2i and seven groups of comparator AHAs were matched (1:1) on exposure propensity scores to adjust for imbalances in baseline covariates. Cox proportional hazards regression models, conditioned on propensity score-matched pairs, were used to estimate hazard ratios (HRs) of DKA for new users of SGLT2i versus other AHAs. When I2 <40%, a combined HR across the four databases was estimated.""), + p(tags$strong(""Results:""), ""Using the broad definition of T2DM, new users of SGLT2i had an increased risk of DKA versus sulfonylureas (HR[95%CI]: 1.53[1.31-1.79]), DPP-4i (1.28[1.11-1.47]), GLP-1 receptor agonists (1.34[1.12-1.60]), metformin (1.31[1.11-1.54]), and insulinotropic AHAs (1.38[1.15-1.66]). Using the narrow definition of T2DM, new users of SGLT2i had an increased risk of DKA only versus sulfonylureas (1.43[1.01-2.01]). New users of SGLT2i had a lower risk of DKA versus insulin and a similar risk as thiazolidinediones, regardless of T2DM definition.""), + p(tags$strong(""Conclusions:""), ""Increased risk of DKA was observed for new users of SGLT2i versus several non-SGLT2i AHAs when T2DM was defined broadly. When T2DM was defined narrowly to exclude possible misclassified T1DM patients, an increased risk of DKA with SGLT2i was observed compared to sulfonylureas.""), + HTML(""
""), + HTML(""
""), + HTML(""

Below are links for study-related artifacts that have been made available as part of this study:

""), + HTML("""") + ), + tabPanel(""Explore results"", + fluidRow( + column(4, + selectInput(""comparison"", div(""Comparison:"", actionLink(""comparisonsInfo"", """", icon = icon(""info-circle""))), comparisons, selected = ""SGLT2i-BROAD vs. DPP-4i-BROAD"", width = '85%'), + selectInput(""outcome"", div(""Outcome:"", actionLink(""outcomesInfo"", """", icon = icon(""info-circle""))), outcomes, selected = ""DKA (IP or ER)"", width = '85%'), + checkboxGroupInput(""timeAtRisk"", div(""Time at risk:"", actionLink(""tarInfo"", """", icon = icon(""info-circle""))), timeAtRisks, selected = ""Intent-to-Treat"", width = '85%'), + checkboxGroupInput(""db"", div(""Data source:"", actionLink(""dbInfo"", """", icon = icon(""info-circle""))), dbs, selected = dbs, width = '85%') + ), + column(8, + dataTableOutput(""mainTable""), + conditionalPanel(""output.rowIsSelected == true"", + tabsetPanel(id = ""tabsetPanel"", + tabPanel(""Power"", + uiOutput(""powerTableCaption""), + tableOutput(""powerTable""), + conditionalPanel(""output.isMetaAnalysis == false"", + uiOutput(""timeAtRiskTableCaption""), + tableOutput(""timeAtRiskTable""))), + tabPanel(""Population characteristics"", + uiOutput(""table1Caption""), + dataTableOutput(""table1Table"")), + tabPanel(""Propensity scores"", + plotOutput(""psPlot""), + div(strong(""Figure 1.""),""Preference score distribution. The preference score is a transformation of the propensity score that adjusts for differences in the sizes of the two treatment groups. A higher overlap indicates subjects in the two groups were more similar in terms of their predicted probability of receiving one treatment over the other."")), + tabPanel(""Covariate balance"", + uiOutput(""hoverInfoBalanceScatter""), + plotOutput(""balancePlot"", + hover = hoverOpts(""plotHoverBalanceScatter"", delay = 100, delayType = ""debounce"")), + uiOutput(""balancePlotCaption"")), + tabPanel(""Systematic error"", + plotOutput(""negativeControlPlot""), + div(strong(""Figure 3.""),""Negative control estimates. Each blue dot represents the estimated hazard ratio and standard error (related to the width of the confidence interval) of each of the negative control outcomes. The yellow diamond indicated the outcome of interest. Estimates below the dashed line have uncalibrated p < .05. Estimates in the orange area have calibrated p < .05. The red band indicated the 95% credible interval around the boundary of the orange area. "")), + tabPanel(""Sensitivity"", + uiOutput(""hoverInfoForestPlot""), + plotOutput(""forestPlot"", height = 500, hover = hoverOpts(""plotHoverForestPlot"", delay = 100, delayType = ""debounce"")), + div(strong(""Figure 4.""),""Forest plot of effect estimates from all sensitivity analyses across databases and time-at-risk periods. Black indicates the estimate selected by the user."")), + tabPanel(""Kaplan-Meier"", + plotOutput(""kaplanMeierPlot"", height = 550), + uiOutput(""kmPlotCaption"")) + ) + ) + + ) + ) + ) + ) +) +) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/extras/EvidenceExplorer/Table1.R",".R","7998","135","prepareTable1 <- function(balance, + beforeTargetPopSize, + beforeComparatorPopSize, + afterTargetPopSize, + afterComparatorPopSize, + beforeLabel = ""Before matching"", + afterLabel = ""After matching"", + targetLabel = ""Target"", + comparatorLabel = ""Comparator"", + percentDigits = 1, + stdDiffDigits = 2) { + pathToCsv <- ""Table1Specs.csv"" + specifications <- read.csv(pathToCsv, stringsAsFactors = FALSE) + + fixCase <- function(label) { + idx <- (toupper(label) == label) + if (any(idx)) { + label[idx] <- paste0(substr(label[idx], 1, 1), + tolower(substr(label[idx], 2, nchar(label[idx])))) + } + return(label) + } + + formatPercent <- function(x) { + result <- format(round(100 * x, percentDigits), digits = percentDigits+1, justify = ""right"") + result <- gsub(""NA"", """", result) + result <- gsub("" "", "" "", result) + return(result) + } + + formatStdDiff <- function(x) { + result <- format(round(x, stdDiffDigits), digits = stdDiffDigits+1, justify = ""right"") + result <- gsub(""NA"", """", result) + result <- gsub("" "", "" "", result) + return(result) + } + + resultsTable <- data.frame() + for (i in 1:nrow(specifications)) { + if (specifications$analysisId[i] == """") { + resultsTable <- rbind(resultsTable, + data.frame(Characteristic = specifications$label[i], value = """")) + } else { + idx <- balance$analysisId == specifications$analysisId[i] + if (any(idx)) { + if (specifications$covariateIds[i] != """") { + covariateIds <- as.numeric(strsplit(specifications$covariateIds[i], "","")[[1]]) + idx <- balance$covariateId %in% covariateIds + } else { + covariateIds <- NULL + } + if (any(idx)) { + balanceSubset <- balance[idx, ] + if (is.null(covariateIds)) { + balanceSubset <- balanceSubset[order(balanceSubset$covariateId), ] + } else { + balanceSubset <- merge(balanceSubset, data.frame(covariateId = covariateIds, + rn = 1:length(covariateIds))) + balanceSubset <- balanceSubset[order(balanceSubset$rn, + balanceSubset$covariateId), ] + } + balanceSubset$covariateName <- fixCase(gsub(""^.*: "", + """", + balanceSubset$covariateName)) + balanceSubset$covariateName[balanceSubset$covariateId == 20003] <- ""100-104"" + if (specifications$covariateIds[i] == """" || length(covariateIds) > 1) { + resultsTable <- rbind(resultsTable, data.frame(Characteristic = specifications$label[i], + beforeMatchingMeanTreated = NA, + beforeMatchingMeanComparator = NA, + beforeMatchingStdDiff = NA, + afterMatchingMeanTreated = NA, + afterMatchingMeanComparator = NA, + afterMatchingStdDiff = NA, + stringsAsFactors = FALSE)) + resultsTable <- rbind(resultsTable, + data.frame(Characteristic = paste0(""    "", balanceSubset$covariateName), + beforeMatchingMeanTreated = balanceSubset$beforeMatchingMeanTreated, + beforeMatchingMeanComparator = balanceSubset$beforeMatchingMeanComparator, + beforeMatchingStdDiff = balanceSubset$beforeMatchingStdDiff, + afterMatchingMeanTreated = balanceSubset$afterMatchingMeanTreated, + afterMatchingMeanComparator = balanceSubset$afterMatchingMeanComparator, + afterMatchingStdDiff = balanceSubset$afterMatchingStdDiff, + stringsAsFactors = FALSE)) + } else { + resultsTable <- rbind(resultsTable, data.frame(Characteristic = specifications$label[i], + beforeMatchingMeanTreated = balanceSubset$beforeMatchingMeanTreated, + beforeMatchingMeanComparator = balanceSubset$beforeMatchingMeanComparator, + beforeMatchingStdDiff = balanceSubset$beforeMatchingStdDiff, + afterMatchingMeanTreated = balanceSubset$afterMatchingMeanTreated, + afterMatchingMeanComparator = balanceSubset$afterMatchingMeanComparator, + afterMatchingStdDiff = balanceSubset$afterMatchingStdDiff, + stringsAsFactors = FALSE)) + } + } + } + } + } + + idx <- resultsTable$Characteristic == ""CHADS2Vasc (mean)"" | resultsTable$Characteristic == ""Charlson comorbidity index (mean)"" | resultsTable$Characteristic == ""DCSI (mean)"" + resultsTable$beforeMatchingMeanTreated[idx] <- resultsTable$beforeMatchingMeanTreated[idx] / 100 + resultsTable$beforeMatchingMeanComparator[idx] <- resultsTable$beforeMatchingMeanComparator[idx] / 100 + resultsTable$afterMatchingMeanTreated[idx] <- resultsTable$afterMatchingMeanTreated[idx] / 100 + resultsTable$afterMatchingMeanComparator[idx] <- resultsTable$afterMatchingMeanComparator[idx] / 100 + + resultsTable$beforeMatchingMeanTreated <- formatPercent(resultsTable$beforeMatchingMeanTreated) + resultsTable$beforeMatchingMeanComparator <- formatPercent(resultsTable$beforeMatchingMeanComparator) + resultsTable$beforeMatchingStdDiff <- formatStdDiff(resultsTable$beforeMatchingStdDiff) + resultsTable$afterMatchingMeanTreated <- formatPercent(resultsTable$afterMatchingMeanTreated) + resultsTable$afterMatchingMeanComparator <- formatPercent(resultsTable$afterMatchingMeanComparator) + resultsTable$afterMatchingStdDiff <- formatStdDiff(resultsTable$afterMatchingStdDiff) + + headerRow <- as.data.frame(t(rep("""", ncol(resultsTable)))) + colnames(headerRow) <- colnames(resultsTable) + headerRow$beforeMatchingMeanTreated <- targetLabel + headerRow$beforeMatchingMeanComparator <- comparatorLabel + headerRow$afterMatchingMeanTreated <- targetLabel + headerRow$afterMatchingMeanComparator <- comparatorLabel + + subHeaderRow <- as.data.frame(t(rep("""", ncol(resultsTable)))) + colnames(subHeaderRow) <- colnames(resultsTable) + subHeaderRow$Characteristic <- ""Characteristic"" + subHeaderRow$beforeMatchingMeanTreated <- paste0(""% (n = "", format(beforeTargetPopSize, big.mark = "",""), "")"") + subHeaderRow$beforeMatchingMeanComparator <- paste0(""% (n = "", format(beforeComparatorPopSize, big.mark = "",""), "")"") + subHeaderRow$beforeMatchingStdDiff <- ""Std. diff"" + subHeaderRow$afterMatchingMeanTreated <- paste0(""% (n = "", format(afterTargetPopSize, big.mark = "",""), "")"") + subHeaderRow$afterMatchingMeanComparator <- paste0(""% (n = "", format(afterComparatorPopSize, big.mark = "",""), "")"") + subHeaderRow$afterMatchingStdDiff <- ""Std. diff"" + + resultsTable <- rbind(headerRow, subHeaderRow, resultsTable) + + colnames(resultsTable) <- rep("""", ncol(resultsTable)) + colnames(resultsTable)[2] <- beforeLabel + colnames(resultsTable)[5] <- afterLabel + return(resultsTable) +}","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Sglt2iDka/programs/sglt2iDka/extras/AllResultsToPdf/AllResultsToPdf.R",".R","15574","367","studyFolder <- ""S:/StudyResults/epi_535_4"" +shinyDataFolder <- file.path(getwd(), ""data"") +appendixFolder <- file.path(studyFolder, ""report2"", ""appendix"") +tempFolder <- ""S:/temp"" +Sys.setenv(PATH = paste(Sys.getenv(""PATH""), ""C:\\Program Files\\MiKTeX 2.9\\miktex\\bin\\x64\\"", sep="";"")) + +wd <- getwd() +setwd("".."") +toPdfFolder <- file.path(getwd(), ""AllResultsToPdf"") +setwd(wd) + +if (!file.exists(appendixFolder)) + dir.create(appendixFolder) +if (!file.exists(tempFolder)) + dir.create(tempFolder) + +OhdsiRTools::addDefaultFileLogger(file.path(appendixFolder, ""log.txt"")) +source(""global.R"") + +# Appendix A ------------------------------------------------------------------- +convertToPdf <- function(appendixFolder, rmdFile) { + wd <- setwd(appendixFolder) + pdfFile <- gsub("".Rmd$"", "".pdf"", rmdFile) + on.exit(setwd(wd)) + rmarkdown::render(rmdFile, + output_file = pdfFile, + rmarkdown::pdf_document(latex_engine = ""pdflatex"")) +} + +mainColumns <- c(""database"", + ""timeAtRisk"", + ""rr"", + ""ci95lb"", + ""ci95ub"", + ""p"", + ""calP"", + ""targetId"", + ""comparatorId"", + ""outcomeId"", + ""analysisId"") +mainColumnNames <- c(""Data source"", + ""Time-at-risk"", + ""HR (95% CI)"", + ""P"", + ""Cal. P"", + ""App."") + +template <- SqlRender::readSql(file.path(toPdfFolder, ""hazardRatioTableTemplate.rmd"")) +aNumber <- 1 +bNumber <- 1 +aAppendices <- data.frame() +bAppendices <- data.frame() + +for (comparison in comparisons) { + for (outcome in outcomes) { + table <- resultsHois[resultsHois$comparison == comparison & resultsHois$outcomeName == outcome, mainColumns] + table$dbOrder <- match(table$database, c(""CCAE"", ""MDCD"",""MDCR"", ""Optum"", ""Meta-analysis"")) + table$timeAtRiskOrder <- match(table$timeAtRisk, c(""Intent-to-Treat"", ""Per-Protocol"")) + table <- table[order(table$timeAtRisk, table$dbOrder), ] + table$dbOrder <- NULL + table$timeAtRiskOrder <- NULL + table$rr[table$rr > 100] <- NA + table$ci95ub[table$ci95ub > 100] <- NA + table$rr <- sprintf(""%.2f (%.2f - %.2f)"", table$rr, table$ci95lb, table$ci95ub) + table$ci95lb <- NULL + table$ci95ub <- NULL + table$p <- formatC(table$p, digits = 2, format = ""f"") + table$p <- gsub(""NA"", """", table$p) + table$calP <- formatC(table$calP, digits = 2, format = ""f"") + table$calP <- gsub(""NA"", """", table$calP) + table$appendix <- sprintf(""b%05d"", bNumber:(bNumber + nrow(table) - 1)) + bAppendices <- rbind(bAppendices, data.frame(targetId = table$targetId, + comparatorId = table$comparatorId, + outcomeId = table$outcomeId, + analysisId = table$analysisId, + database = table$database, + appendix = table$appendix)) + table$targetId <- NULL + table$comparatorId <- NULL + table$outcomeId <- NULL + table$analysisId <- NULL + colnames(table) <- mainColumnNames + saveRDS(table, file.path(tempFolder, ""temp.rds"")) + + rmd <- template + rmd <- gsub(""%number%"", sprintf(""A%02d"", aNumber), rmd) + rmd <- gsub(""%comparison%"", comparison, rmd) + rmd <- gsub(""%outcome%"", outcome, rmd) + rmdFile <- sprintf(""appendix-a%02d.Rmd"", aNumber) + sink(file.path(appendixFolder, rmdFile)) + writeLines(rmd) + sink() + convertToPdf(appendixFolder, rmdFile) + + aNumber <- aNumber + 1 + bNumber <- bNumber + nrow(table) + + # Cleanup + unlink(file.path(appendixFolder, rmdFile)) + unlink(list.files(tempFolder, pattern = ""^temp"")) + } +} +saveRDS(bAppendices, file.path(appendixFolder, ""bAppendices.rds"")) + + +# Annex: list of Appendix A supporting documents ------------------------------- +aNumber <- 1 +appendicesFile <- file.path(appendixFolder, ""aAppendices.txt"") +sink(appendicesFile) + +for (comparison in comparisons) { + for (outcome in outcomes) { + title <- ""%number%. Appendix %appendixNumber%: Estimates for the comparison of %comparison% for the outcome of %outcome%"" + title <- gsub(""%number%"", aNumber, title) + title <- gsub(""%appendixNumber%"", sprintf(""a%02d"", aNumber), title) + title <- gsub(""%comparison%"", comparison, title) + title <- gsub(""%outcome%"", outcome, title) + print(title, quote = FALSE) + aNumber <- aNumber + 1 + } +} +sink() + + +# Appendix B ------------------------------------------------------------------- +bAppendices <- readRDS(file.path(appendixFolder, ""bAppendices.rds"")) + +generateAppendixB <- function(i) { + pdfFile <- sprintf(""appendix%s.pdf"", bAppendices$appendix[i]) + if (!file.exists(file.path(appendixFolder, pdfFile))) { + OhdsiRTools::logInfo(""Generating "", pdfFile) + + tempFolder <- paste0(""S:/temp/cana"",i) + dir.create(tempFolder) + source(""Table1.R"") + + + convertToPdf <- function(appendixFolder, rmdFile) { + wd <- setwd(appendixFolder) + pdfFile <- gsub("".Rmd$"", "".pdf"", rmdFile) + on.exit(setwd(wd)) + rmarkdown::render(rmdFile, + output_file = pdfFile, + rmarkdown::pdf_document(latex_engine = ""pdflatex"")) + } + + row <- resultsHois[resultsHois$targetId == bAppendices$targetId[i] & + resultsHois$comparatorId == bAppendices$comparatorId[i] & + resultsHois$outcomeId == bAppendices$outcomeId[i] & + resultsHois$analysisId == bAppendices$analysisId[i] & + resultsHois$database == bAppendices$database[i], ] + isMetaAnalysis <- row$database == ""Meta-analysis"" + + # Power table + powerColumns <- c(""treated"", + ""comparator"", + ""treatedDays"", + ""comparatorDays"", + ""eventsTreated"", + ""eventsComparator"", + ""irTreated"", + ""irComparator"", + ""mdrr"") + powerColumnNames <- c(""Target"", + ""Comparator"", + ""Target"", + ""Comparator"", + ""Target"", + ""Comparator"", + ""Target"", + ""Comparator"", + ""MDRR"") + table <- row + table$irTreated <- formatC(1000 * table$eventsTreated / (table$treatedDays / 365.25), digits = 2, format = ""f"") + table$irComparator <- formatC(1000 * table$eventsComparator / (table$comparatorDays / 365.25), digits = 2, format = ""f"") + table$treated <- formatC(table$treated, big.mark = "","", format = ""d"") + table$comparator <- formatC(table$comparator, big.mark = "","", format = ""d"") + table$treatedDays <- formatC(table$treatedDays, big.mark = "","", format = ""d"") + table$comparatorDays <- formatC(table$comparatorDays, big.mark = "","", format = ""d"") + table$eventsTreated <- formatC(table$eventsTreated, big.mark = "","", format = ""d"") + table$eventsComparator <- formatC(table$eventsComparator, big.mark = "","", format = ""d"") + table$mdrr <- formatC(table$mdrr, digits = 2, format = ""f"") + if (table$database == ""Meta-analysis"") { + table <- table[, c(powerColumns, ""i2"")] + colnames(table) <- c(powerColumnNames, ""I2"") + } else { + table <- table[, powerColumns] + colnames(table) <- powerColumnNames + } + saveRDS(table, file.path(tempFolder, ""tempPower.rds"")) + + # Follow-up table + if (!isMetaAnalysis) { + table <- data.frame(Cohort = c(""Target"", ""Comparator""), + Mean = formatC(c(row$tarTargetMean, row$tarComparatorMean), digits = 1, format = ""f""), + SD = formatC(c(row$tarTargetSd, row$tarComparatorSd), digits = 1, format = ""f""), + Min = formatC(c(row$tarTargetMin, row$tarComparatorMin), big.mark = "","", format = ""d""), + Median = formatC(c(row$tarTargetMedian, row$tarComparatorMedian), big.mark = "","", format = ""d""), + Max = formatC(c(row$tarTargetMax, row$tarComparatorMax), big.mark = "","", format = ""d"")) + saveRDS(table, file.path(tempFolder, ""tempTar.rds"")) + } + + # Population characteristics + if (!isMetaAnalysis) { + fileName <- paste0(""bal_a"", row$analysisId, + ""_t"", row$targetId, + ""_c"", row$comparatorId, + ""_o"", row$outcomeId, + ""_"", row$database,"".rds"") + bal <- readRDS(file.path(shinyDataFolder, fileName)) + bal$absBeforeMatchingStdDiff <- abs(bal$beforeMatchingStdDiff) + bal$absAfterMatchingStdDiff <- abs(bal$afterMatchingStdDiff) + bal <- merge(bal, covarNames) + fileName <- paste0(""multiTherBal_a"", row$analysisId, + ""_t"", row$targetId, + ""_c"", row$comparatorId, + ""_o"", row$outcomeId, + ""_"", row$database,"".rds"") + multiTherBalance <- readRDS(file.path(shinyDataFolder, fileName)) + bal$absBeforeMatchingStdDiff <- NULL + bal$absAfterMatchingStdDiff <- NULL + multiTherBalance <- multiTherBalance[, colnames(bal)] + bal <- rbind(bal, multiTherBalance) + bal$covariateName <- as.character(bal$covariateName) + bal$covariateName[bal$covariateId == 20003] <- ""age group: 100-104"" + bal <- bal[order(nchar(bal$covariateName), bal$covariateName), ] + table <- prepareTable1(bal, + beforeTargetPopSize = row$treatedBefore, + beforeComparatorPopSize = row$comparatorBefore, + afterTargetPopSize = row$treated, + afterComparatorPopSize = row$comparator, + beforeLabel = ""Before matching"", + afterLabel = ""After matching"") + table <- cbind(apply(table, 2, function(x) gsub("" "", "" "", x))) + colnames(table) <- table[2, ] + table <- table[3:nrow(table), ] + saveRDS(table, file.path(tempFolder, ""tempPopChar.rds"")) + + fileName <- paste0(""ps_a"", row$analysisId, + ""_t"", row$targetId, + ""_c"", row$comparatorId, + ""_"", row$database, "".rds"") + data <- readRDS(file.path(shinyDataFolder, fileName)) + data$GROUP <- row$targetDrug + data$GROUP[data$treatment == 0] <- row$comparatorDrug + data$GROUP <- factor(data$GROUP, levels = c(row$targetDrug, row$comparatorDrug)) + saveRDS(data, file.path(tempFolder, ""tempPs.rds"")) + } + + # Covariate balance + if (!isMetaAnalysis) { + fileName <- paste0(""bal_a"", row$analysisId, + ""_t"", row$targetId, + ""_c"", row$comparatorId, + ""_o"", row$outcomeId, + ""_"", row$database, "".rds"") + bal <- readRDS(file.path(shinyDataFolder, fileName)) + bal$absBeforeMatchingStdDiff <- abs(bal$beforeMatchingStdDiff) + bal$absAfterMatchingStdDiff <- abs(bal$afterMatchingStdDiff) + saveRDS(bal, file.path(tempFolder, ""tempBalance.rds"")) + } + + # Negative controls + ncs <- resultsNcs[resultsNcs$targetId == row$targetId & + resultsNcs$comparatorId == row$comparatorId & + resultsNcs$analysisId == row$analysisId & + resultsNcs$database == row$database, ] + saveRDS(ncs, file.path(tempFolder, ""tempNcs.rds"")) + + # Kaplan Meier + if (!isMetaAnalysis) { + fileName <- paste0(""km_a"", row$analysisId, + ""_t"", row$targetId, + ""_c"", row$comparatorId, + ""_o"", row$outcomeId, + ""_"", row$database,"".rds"") + plot <- readRDS(file.path(shinyDataFolder, fileName)) + saveRDS(plot, file.path(tempFolder, ""tempKm.rds"")) + } + + wd <- getwd() + setwd("".."") + template <- SqlRender::readSql(""AllResultsToPdf/detailsTemplate.rmd"") + setwd(wd) + rmd <- template + rmd <- gsub(""%tempFolder%"", tempFolder, rmd) + rmd <- gsub(""%number%"", bAppendices$appendix[i], rmd) + rmd <- gsub(""%comparison%"", row$comparison, rmd) + rmd <- gsub(""%outcome%"", row$outcomeName, rmd) + rmd <- gsub(""%target%"", row$targetDrug, rmd) + rmd <- gsub(""%comparator%"", row$comparatorDrug, rmd) + rmd <- gsub(""%logRr%"", if (is.na(row$logRr)) 999 else row$logRr, rmd) + rmd <- gsub(""%seLogRr%"", if (is.na(row$seLogRr)) 999 else row$seLogRr, rmd) + rmd <- gsub(""%timeAtRisk%"", row$timeAtRisk, rmd) + rmd <- gsub(""%database%"", row$database, rmd) + rmd <- gsub(""%isMetaAnalysis%"", isMetaAnalysis, rmd) + + rmdFile <- sprintf(""appendix-%s.Rmd"", bAppendices$appendix[i]) + sink(file.path(appendixFolder, rmdFile)) + writeLines(rmd) + sink() + convertToPdf(appendixFolder, rmdFile) + + # Cleanup + unlink(file.path(appendixFolder, rmdFile)) + unlink(tempFolder, recursive = TRUE) + } +} + +nThreads <- 15 +cluster <- OhdsiRTools::makeCluster(nThreads) +setGlobalVars <- function(i, bAppendices, resultsHois, resultsNcs, covarNames, appendixFolder, shinyDataFolder){ + bAppendices <<- bAppendices + resultsHois <<- resultsHois + resultsNcs <<- resultsNcs + covarNames <<- covarNames + appendixFolder <<- appendixFolder + shinyDataFolder <<- shinyDataFolder +} +dummy <- OhdsiRTools::clusterApply(cluster = cluster, + x = 1:nThreads, + fun = setGlobalVars, + bAppendices = bAppendices, + resultsHois = resultsHois, + resultsNcs = resultsNcs, + covarNames = covarNames, + appendixFolder = appendixFolder, + shinyDataFolder = shinyDataFolder) +n <- nrow(bAppendices) +# when running clusterApply, the context of a function (in this case the global environment) +# is also transmitted with every function call. Making sure it doesn't contain anything big: +bAppendices <- NULL +resultsHois <- NULL +resultsNcs <- NULL +covarNames <- NULL +appendixFolder <- NULL +heterogeneous <- NULL +dummy <- NULL + +dummy <- OhdsiRTools::clusterApply(cluster = cluster, + x = 1:n, + fun = generateAppendixB) + +OhdsiRTools::stopCluster(cluster) + +# Post processing using GhostScript ------------------------------------------------------------- +# gsPath <- ""\""C:/Program Files/gs/gs9.23/bin/gswin64.exe\"""" +# studyFolder <- ""r:/AhasHfBkleAmputation"" +# appendixFolder <- file.path(studyFolder, ""report"", ""appendix"") +# tempFolder <- file.path(appendixFolder, ""optimized"") +# if (!file.exists(tempFolder)) +# dir.create(tempFolder) +# +# fileName <- ""AppendixA01.pdf"" +# fileName <- ""AppendixB00001.pdf"" +# files <- list.files(appendixFolder, pattern = "".*\\.pdf"", recursive = FALSE) +# +# for (fileName in files) { +# args <- ""-dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dFastWebView -sOutputFile=%s %s %s"" +# command <- paste(gsPath, sprintf(args, file.path(tempFolder, fileName), file.path(appendixFolder, fileName), file.path(getwd(), ""extras/AllResultsToPdf/pdfmarks""))) +# shell(command) +# } +# +# unlink(file.path(appendixFolder, files)) +# file.rename(from = file.path(tempFolder, files), to = file.path(appendixFolder, files)) +# unlink(tempFolder, recursive = TRUE) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Study 2 - Treatment Pathways 12mo/R Version/HelperFunctions.R",".R","1881","38","renderStudySpecificSql <- function(studyName, minCellCount, cdmSchema, resultsSchema, sourceName, dbms){ + if (studyName == ""HTN12mo""){ + TxList <- '21600381,21601461,21601560,21601664,21601744,21601782' + DxList <- '316866' + ExcludeDxList <- '444094' + } else if (studyName == ""T2DM12mo""){ + TxList <- '21600712,21500148' + DxList <- '201820' + ExcludeDxList <- '444094,35506621' + } else if (studyName == ""Depression12mo""){ + TxList <- '21604686, 21500526' + DxList <- '440383' + ExcludeDxList <- '444094,432876,435783' + } + + inputFile <- ""TxPath parameterized.sql"" + outputFile <- paste(""TxPath autoTranslate "", dbms,"" "", studyName, "".sql"",sep="""") + + parameterizedSql <- readSql(inputFile) + renderedSql <- renderSql(parameterizedSql, cdmSchema=cdmSchema, resultsSchema=resultsSchema, studyName = studyName, sourceName=sourceName, txlist=TxList, dxlist=DxList, excludedxlist=ExcludeDxList, smallcellcount = minCellCount)$sql + translatedSql <- translateSql(renderedSql, sourceDialect = ""sql server"", targetDialect = dbms)$sql + writeSql(translatedSql,outputFile) + writeLines(paste(""Created file '"",outputFile,""'"",sep="""")) + return(outputFile) + } + + extractAndWriteToFile <- function(connection, tableName, resultsSchema, sourceName, studyName, dbms){ + parameterizedSql <- ""SELECT * FROM @resultsSchema.dbo.@studyName_@sourceName_@tableName"" + renderedSql <- renderSql(parameterizedSql, cdmSchema=cdmSchema, resultsSchema=resultsSchema, studyName=studyName, sourceName=sourceName, tableName=tableName)$sql + translatedSql <- translateSql(renderedSql, sourceDialect = ""sql server"", targetDialect = dbms)$sql + data <- querySql(connection, translatedSql) + outputFile <- paste(studyName,""_"",sourceName,""_"",tableName,"".csv"",sep='') + write.csv(data,file=outputFile) + writeLines(paste(""Created file '"",outputFile,""'"",sep="""")) + } + + + ","R" +"Pharmacogenetics","OHDSI/StudyProtocols","Study 2 - Treatment Pathways 12mo/R Version/MainAnalysis.R",".R","3638","86","########################################################### +# R script for creating SQL files (and sending the SQL # +# commands to the server) for the treatment pattern # +# studies for these diseases: # +# - Hypertension (HTN) # +# - Type 2 Diabetes (T2DM) # +# - Depression # +# # +# Requires: R and Java 1.6 or higher # +########################################################### + +# Install necessary packages if needed +install.packages(""devtools"") +library(devtools) +install_github(""ohdsi/SqlRender"") +install_github(""ohdsi/DatabaseConnector"") + +# Load libraries +library(SqlRender) +library(DatabaseConnector) + +########################################################### +# Parameters: Please change these to the correct values: # +########################################################### + +folder = ""F:/Documents/OHDSI/StudyProtocols/Study 2 - Treatment Pathways 12mo/R Version"" # Folder containing the R and SQL files, use forward slashes +minCellCount = 1 # the smallest allowable cell count, 1 means all counts are allowed +cdmSchema = ""cdm_schema"" +resultsSchema = ""results_schema"" +sourceName = ""source_name"" +dbms = ""sql server"" # Should be ""sql server"", ""oracle"", ""postgresql"" or ""redshift"" + +# If you want to use R to run the SQL and extract the results tables, please create a connectionDetails +# object. See ?createConnectionDetails for details on how to configure for your DBMS. + + + +user <- NULL +pw <- NULL +server <- ""server_name"" +port <- NULL + +connectionDetails <- createConnectionDetails(dbms=dbms, + server=server, + user=user, + password=pw, + schema=cdmSchema, + port=port) + + +########################################################### +# End of parameters. Make no changes after this # +########################################################### + +setwd(folder) + +source(""HelperFunctions.R"") + +# Create the parameterized SQL files: +htnSqlFile <- renderStudySpecificSql(""HTN12mo"",minCellCount,cdmSchema,resultsSchema,sourceName,dbms) +t2dmSqlFile <- renderStudySpecificSql(""T2DM12mo"",minCellCount,cdmSchema,resultsSchema,sourceName,dbms) +depSqlFile <- renderStudySpecificSql(""Depression12mo"",minCellCount,cdmSchema,resultsSchema,sourceName,dbms) + +# Execute the SQL: +conn <- connect(connectionDetails) +executeSql(conn,readSql(htnSqlFile)) +executeSql(conn,readSql(t2dmSqlFile)) +executeSql(conn,readSql(depSqlFile)) + +# Extract tables to CSV files: +extractAndWriteToFile(conn, ""summary"", resultsSchema, sourceName, ""HTN12mo"", dbms) +extractAndWriteToFile(conn, ""person_cnt"", resultsSchema, sourceName, ""HTN12mo"", dbms) +extractAndWriteToFile(conn, ""seq_cnt"", resultsSchema, sourceName, ""HTN12mo"", dbms) + +extractAndWriteToFile(conn, ""summary"", resultsSchema, sourceName, ""T2DM12mo"", dbms) +extractAndWriteToFile(conn, ""person_cnt"", resultsSchema, sourceName, ""T2DM12mo"", dbms) +extractAndWriteToFile(conn, ""seq_cnt"", resultsSchema, sourceName, ""T2DM12mo"", dbms) + +extractAndWriteToFile(conn, ""summary"", resultsSchema, sourceName, ""Depression12mo"", dbms) +extractAndWriteToFile(conn, ""person_cnt"", resultsSchema, sourceName, ""Depression12mo"", dbms) +extractAndWriteToFile(conn, ""seq_cnt"", resultsSchema, sourceName, ""Depression12mo"", dbms) + +dbDisconnect(conn) + + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CiCalibration/R/EmpiricalCalibration.R",".R","10464","195","# Copyright 2017 Observational Health Data Sciences and Informatics +# +# This file is part of CiCalibration +# +# 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. + + +#' Perform empirical calibration +#' +#' @details +#' Performs empirical calibration of confidence intervals and p-values using the negative and positive +#' control outcomes. +#' +#' @param workFolder The path to the output folder containing the results. +#' +#' @export +doEmpiricalCalibration <- function(workFolder, study) { + if (study == ""Southworth"") { + results <- read.csv(file.path(workFolder, ""cmSummarySouthworth.csv"")) + + # positive control outcomes: + positiveControls <- read.csv(file.path(workFolder, ""SignalInjectionSummary_Southworth.csv"")) + positiveControls <- data.frame(outcomeId = positiveControls$newOutcomeId, + trueLogRr = log(positiveControls$targetEffectSize), + oldOutcomeId = positiveControls$outcomeId) + results <- merge(results, positiveControls, all.x = TRUE) + + # outcome of interest: + pathToHoi <- system.file(""settings"", ""cmHypothesisOfInterestSouthworth.txt"", package = ""CiCalibration"") + hoi <- CohortMethod::loadDrugComparatorOutcomesList(pathToHoi)[[1]]$outcomeId + + # negative control outcomes: + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""CiCalibration"") + negativeControls <- read.csv(pathToCsv) + negativeControls <- negativeControls[negativeControls$study == ""Southworth"", ] + negativeControls <- negativeControls$conceptId + results$trueLogRr[results$outcomeId %in% negativeControls] <- 0 + + .empiricalCalibration(workFolder = workFolder, results = results, study = study, design = ""cohort_method"") + } else if (study == ""Graham"") { + results <- read.csv(file.path(workFolder, ""cmSummaryGraham.csv"")) + + # positive control outcomes: + positiveControls <- read.csv(file.path(workFolder, ""SignalInjectionSummary_Graham.csv"")) + positiveControls <- data.frame(outcomeId = positiveControls$newOutcomeId, + trueLogRr = log(positiveControls$targetEffectSize), + oldOutcomeId = positiveControls$outcomeId) + results <- merge(results, positiveControls, all.x = TRUE) + + # outcome of interest: + pathToHoi <- system.file(""settings"", ""cmHypothesisOfInterestGraham.txt"", package = ""CiCalibration"") + hoi <- CohortMethod::loadDrugComparatorOutcomesList(pathToHoi)[[1]]$outcomeId + + # negative control outcomes: + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""CiCalibration"") + negativeControls <- read.csv(pathToCsv) + negativeControls <- negativeControls[negativeControls$study == ""Graham"", ] + negativeControls <- negativeControls$conceptId + results$trueLogRr[results$outcomeId %in% negativeControls] <- 0 + + .empiricalCalibration(workFolder = workFolder, results = results, study = study, design = ""cohort_method"") + } else if (study == ""Tata"") { + # Case-control + results <- read.csv(file.path(workFolder, ""ccSummary.csv"")) + + # positive control outcomes: + positiveControls <- read.csv(file.path(workFolder, ""SignalInjectionSummary_Tata.csv"")) + positiveControls <- data.frame(outcomeId = positiveControls$newOutcomeId, + trueLogRr = log(positiveControls$targetEffectSize), + oldOutcomeId = positiveControls$outcomeId) + results <- merge(results, positiveControls, all.x = TRUE) + + # outcome of interest: + pathToHoi <- system.file(""settings"", ""ccHypothesisOfInterest.txt"", package = ""CiCalibration"") + hoi <- CaseControl::loadExposureOutcomeNestingCohortList(pathToHoi)[[1]]$outcomeId + + # negative control outcomes: + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""CiCalibration"") + negativeControls <- read.csv(pathToCsv) + negativeControls <- negativeControls[negativeControls$study == ""Tata"", ] + negativeControls <- negativeControls$conceptId + results$trueLogRr[results$outcomeId %in% negativeControls] <- 0 + + .empiricalCalibration(workFolder = workFolder, results = results, study = study, design = ""case_control"") + + + # Self-Controlled Case Series + results <- read.csv(file.path(workFolder, ""sccsSummary.csv"")) + results$logRr <- results$logRr.Exposure.of.interest. + results$seLogRr <- results$seLogRr.Exposure.of.interest. + results$rr <- results$rr.Exposure.of.interest. + results$ci95lb <- results$ci95lb.Exposure.of.interest. + results$ci95ub <- results$ci95ub.Exposure.of.interest. + + # positive control outcomes: + positiveControls <- read.csv(file.path(workFolder, ""SignalInjectionSummary_Tata.csv"")) + positiveControls <- data.frame(outcomeId = positiveControls$newOutcomeId, + trueLogRr = log(positiveControls$targetEffectSize), + oldOutcomeId = positiveControls$outcomeId) + results <- merge(results, positiveControls, all.x = TRUE) + + # outcome of interest: + pathToHoi <- system.file(""settings"", ""sccsHypothesisOfInterest.txt"", package = ""CiCalibration"") + hoi <- SelfControlledCaseSeries::loadExposureOutcomeList(pathToHoi)[[1]]$outcomeId + + # negative control outcomes: + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""CiCalibration"") + negativeControls <- read.csv(pathToCsv) + negativeControls <- negativeControls[negativeControls$study == ""Tata"", ] + negativeControls <- negativeControls$conceptId + results$trueLogRr[results$outcomeId %in% negativeControls] <- 0 + + .empiricalCalibration(workFolder = workFolder, results = results, study = study, design = ""sccs"") + + } +} + +.empiricalCalibration <- function(workFolder, results, study, design) { + calibrationFolder = file.path(workFolder, paste0(""calibration_"", study, ""_"", design)) + if (!file.exists(calibrationFolder)) + dir.create(calibrationFolder) + + negativeControls <- results[!is.na(results$trueLogRr) & results$trueLogRr == 0,] + positiveControls <- results[!is.na(results$trueLogRr) & results$trueLogRr > 0,] + allControls <- rbind(negativeControls, positiveControls) + hoi <- results[is.na(results$trueLogRr),] + + null <- EmpiricalCalibration::fitMcmcNull(negativeControls$logRr, negativeControls$seLogRr) + + calibratedP <- EmpiricalCalibration::calibrateP(null, results$logRr, results$seLogRr) + + results$calibratedP <- calibratedP$p + results$calibratedP_lb95ci <- calibratedP$lb95ci + results$calibratedP_ub95ci <- calibratedP$ub95ci + mcmc <- attr(null, ""mcmc"") + results$null_mean <- mean(mcmc$chain[, 1]) + results$null_sd <- 1/sqrt(mean(mcmc$chain[, 2])) + + fileName <- file.path(calibrationFolder, ""pValueCalibration.png"") + EmpiricalCalibration::plotCalibration(negativeControls$logRr, negativeControls$seLogRr, fileName = fileName) + + fileName <- file.path(calibrationFolder, ""pValueCalEffect.png"") + EmpiricalCalibration::plotCalibrationEffect(negativeControls$logRr, negativeControls$seLogRr, hoi$logRr, hoi$seLogRr, fileName = fileName) + + # fileName <- file.path(calibrationFolder, ""pValueCalEffectWithCis.png"") + # EmpiricalCalibration::plotCalibrationEffect(negativeControls$logRr, negativeControls$seLogRr, hoi$logRr, hoi$seLogRr, fileName = fileName, showCis = TRUE) + + fileName <- file.path(calibrationFolder, ""mcmcTrace.png"") + EmpiricalCalibration::plotMcmcTrace(null, fileName = fileName) + + errorModel <- EmpiricalCalibration::fitSystematicErrorModel(logRr = allControls$logRr, + seLogRr = allControls$seLogRr, + trueLogRr = allControls$trueLogRr) + calibratedCi <- EmpiricalCalibration::calibrateConfidenceInterval(logRr = results$logRr, + seLogRr = results$seLogRr, + model = errorModel) + results$calibratedRr <- exp(calibratedCi$logRr) + results$calibratedCi95lb <- exp(calibratedCi$logLb95Rr) + results$calibratedCi95ub <- exp(calibratedCi$logUb95Rr) + results$calibratedSe <- exp(calibratedCi$seLogRr) + results$calibratedLogRr <- calibratedCi$logRr + results$calibratedSeLogRr <- calibratedCi$seLogRr + + fileName <- file.path(calibrationFolder, ""ciCalibration.png"") + EmpiricalCalibration::plotCiCalibration(logRr = allControls$logRr, + seLogRr = allControls$seLogRr, + trueLogRr = allControls$trueLogRr, + fileName = fileName) + + fileName <- file.path(calibrationFolder, ""trueAndObserved.png"") + EmpiricalCalibration::plotTrueAndObserved(logRr = allControls$logRr, + seLogRr = allControls$seLogRr, + trueLogRr = allControls$trueLogRr, + fileName = fileName) + + allControls <- results[results$outcomeId %in% allControls$outcomeId, ] + fileName <- file.path(calibrationFolder, ""trueAndObservedCalibrated.png"") + EmpiricalCalibration::plotTrueAndObserved(logRr = allControls$calibratedLogRr, + seLogRr = allControls$calibratedSeLogRr, + trueLogRr = allControls$trueLogRr, + fileName = fileName) + + write.csv(results, file.path(workFolder, paste0(""Calibrated_"", study, ""_"", design,"".csv"")), row.names = FALSE) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CiCalibration/R/Main.R",".R","6608","143","# Copyright 2017 Observational Health Data Sciences and Informatics +# +# This file is part of CiCalibration +# +# 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. + +#' @title +#' Execute OHDSI Celecoxib versus non-selective NSAIDs study +#' +#' @details +#' This function executes the OHDSI Celecoxib versus non-selective NSAIDs study. +#' +#' @return +#' TODO +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param workDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param studyCohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param cdmVersion Version of the CDM. Can be ""4"" or ""5"" +#' @param workFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' +#' @examples +#' \dontrun{ +#' connectionDetails <- createConnectionDetails(dbms = ""postgresql"", +#' user = ""joe"", +#' password = ""secret"", +#' server = ""myserver"") +#' +#' execute(connectionDetails, +#' cdmDatabaseSchema = ""cdm_data"", +#' workDatabaseSchema = ""results"", +#' oracleTempSchema = NULL, +#' workFolder = ""c:/temp/study_results"", +#' cdmVersion = ""5"") +#' +#' } +#' +#' @export +execute <- function(connectionDetails, + cdmDatabaseSchema, + workDatabaseSchema = cdmDatabaseSchema, + studyCohortTable = ""ohdsi_ci_calibration"", + oracleTempSchema = NULL, + cdmVersion = 5, + study, + workFolder, + createCohorts = TRUE, + injectSignals = TRUE, + runAnalyses = TRUE, + empiricalCalibration = TRUE, + packageResultsForSharing = TRUE, + maxCores = 4) { + if (cdmVersion == 4) { + stop(""CDM version 4 not supported"") + } + if (study != ""Southworth"" && study != ""Graham"" && study != ""Tata"") + stop(""Study must be 'Southworth', 'Graham', or 'Tata'"") + + if (!file.exists(workFolder)) + dir.create(workFolder) + + if (createCohorts) { + writeLines(""Creating exposure and outcome cohorts"") + createCohorts(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + workDatabaseSchema = workDatabaseSchema, + studyCohortTable = studyCohortTable, + study = study, + workFolder = workFolder) + } + if (injectSignals) { + injectSignals(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + workDatabaseSchema = workDatabaseSchema, + studyCohortTable = studyCohortTable, + study = study, + workFolder = workFolder, + maxCores = maxCores) + } + if (runAnalyses) { + writeLines(""Running analyses"") + if (study == ""Southworth"") { + runCohortMethodSouthworth(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + workDatabaseSchema = workDatabaseSchema, + studyCohortTable = studyCohortTable, + oracleTempSchema = oracleTempSchema, + maxCores = maxCores) + + } else if (study == ""Graham"") { + runCohortMethodGraham(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + workDatabaseSchema = workDatabaseSchema, + studyCohortTable = studyCohortTable, + oracleTempSchema = oracleTempSchema, + maxCores = maxCores) + } else if (study == ""Tata"") { + runSccs(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + workDatabaseSchema = workDatabaseSchema, + studyCohortTable = studyCohortTable, + oracleTempSchema = oracleTempSchema, + maxCores = maxCores) + runCaseControl(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + workDatabaseSchema = workDatabaseSchema, + studyCohortTable = studyCohortTable, + oracleTempSchema = oracleTempSchema, + maxCores = maxCores) + } + } + + if (empiricalCalibration) { + writeLines(""Performing empirical calibration"") + doEmpiricalCalibration(workFolder = workFolder, study = study) + } + +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CiCalibration/R/CreateCohorts.R",".R","7178","128","# Copyright 2017 Observational Health Data Sciences and Informatics +# +# This file is part of CiCalibration +# +# 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. + +#' Create the exposure and outcome cohorts +#' +#' @details +#' This function will create the exposure and outcome cohorts following the definitions included in +#' this package. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param workDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param studyCohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param study For which study should the cohorts be created? Options are ""SSRIs"" and +#' ""Dabigatran"". +#' @param workFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' +#' @export +createCohorts <- function(connectionDetails, + cdmDatabaseSchema, + workDatabaseSchema, + studyCohortTable = ""ohdsi_ci_calibration"", + oracleTempSchema, + study = ""Tata"", + workFolder) { + if (study != ""Southworth"" && study != ""Graham"" && study != ""Tata"") + stop(""Study must be 'Southworth', 'Graham', or 'Tata'"") + conn <- DatabaseConnector::connect(connectionDetails) + + sql <- SqlRender::loadRenderTranslateSql(""CreateCohortTable.sql"", + ""CiCalibration"", + dbms = connectionDetails$dbms, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable) + DatabaseConnector::executeSql(conn, sql, progressBar = FALSE, reportOverallTime = FALSE) + + pathToCsv <- system.file(""settings"", ""CohortsToCreate.csv"", package = ""CiCalibration"") + cohortsToCreate <- read.csv(pathToCsv) + cohortsToCreate <- cohortsToCreate[cohortsToCreate$study == study, ] + for (i in 1:nrow(cohortsToCreate)) { + writeLines(paste(""Creating cohort:"", cohortsToCreate$name[i])) + sql <- SqlRender::loadRenderTranslateSql(paste0(cohortsToCreate$name[i], "".sql""), + ""CiCalibration"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable, + target_cohort_id = cohortsToCreate$cohortId[i]) + DatabaseConnector::executeSql(conn, sql) + } + + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""CiCalibration"") + negativeControls <- read.csv(pathToCsv) + negativeControls <- negativeControls[negativeControls$study == study, ] + if (nrow(negativeControls) == 0) { + writeLines(""- No negative controls to create!"") + } else { + writeLines(""- Creating negative control outcome cohort"") + sql <- SqlRender::loadRenderTranslateSql(""NegativeControls.sql"", + ""CiCalibration"", + dbms = connectionDetails$dbms, + oracleTempSchema = oracleTempSchema, + cdm_database_schema = cdmDatabaseSchema, + target_database_schema = workDatabaseSchema, + target_cohort_table = studyCohortTable, + outcome_ids = negativeControls$conceptId) + DatabaseConnector::executeSql(conn, sql) + } + # Check number of subjects per cohort: + sql <- ""SELECT cohort_definition_id, COUNT(*) AS count FROM @work_database_schema.@study_cohort_table GROUP BY cohort_definition_id"" + sql <- SqlRender::renderSql(sql, + work_database_schema = workDatabaseSchema, + study_cohort_table = studyCohortTable)$sql + sql <- SqlRender::translateSql(sql, targetDialect = connectionDetails$dbms)$sql + counts <- DatabaseConnector::querySql(conn, sql) + RJDBC::dbDisconnect(conn) + + names(counts) <- SqlRender::snakeCaseToCamelCase(names(counts)) + counts <- merge(counts, + cohortsToCreate[, + c(""cohortId"", ""name"")], + by.x = ""cohortDefinitionId"", + by.y = ""cohortId"", + all.x = TRUE) + counts <- merge(counts, + negativeControls[, + c(""conceptId"", ""name"")], + by.x = ""cohortDefinitionId"", + by.y = ""conceptId"", + all.x = TRUE) + counts$cohortName <- as.character(counts$name.x) + counts$cohortName[is.na(counts$name.x)] <- as.character(counts$name.y[is.na(counts$name.x)]) + counts$name.x <- NULL + counts$name.y <- NULL + write.csv(counts, file.path(workFolder, + paste0(""CohortCounts_"", study, "".csv"")), row.names = FALSE) + print(counts) +} + + +# DatabaseConnector::querySql(conn, 'SELECT max(cohort_start_date) FROM +# scratch.dbo.mschuemie_ci_calibration_cohorts_mdcd WHERE cohort_definition_id = 4') +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CiCalibration/R/CohortMethod.R",".R","11364","180","# Copyright 2017 Observational Health Data Sciences and Informatics +# +# This file is part of CiCalibration +# +# 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. + +#' Run the Southworth study replication +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param workDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param studyCohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param maxCores How many parallel cores should be used? If more cores are made available +#' this can speed up the analyses. +#' +#' @export +runCohortMethodSouthworth <- function(connectionDetails, + cdmDatabaseSchema, + workDatabaseSchema = cdmDatabaseSchema, + studyCohortTable = ""ohdsi_ci_calibration"", + oracleTempSchema = NULL, + maxCores = 4) { + cmFolder <- file.path(workFolder, ""cmOutputSouthworth"") + if (!file.exists(cmFolder)) + dir.create(cmFolder) + + writeLines(""Running cohort analyses"") + cmAnalysisListFile <- system.file(""settings"", ""cmAnalysisListSouthworth.txt"", package = ""CiCalibration"") + cmAnalysisList <- CohortMethod::loadCmAnalysisList(cmAnalysisListFile) + + pathToHoi <- system.file(""settings"", ""cmHypothesisOfInterestSouthworth.txt"", package = ""CiCalibration"") + hypothesesOfInterest <- CohortMethod::loadDrugComparatorOutcomesList(pathToHoi) + + # Add negative control outcomes: + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""CiCalibration"") + negativeControls <- read.csv(pathToCsv) + negativeControls <- negativeControls[negativeControls$study == ""Southworth"", ] + hypothesesOfInterest[[1]]$outcomeIds <- c(hypothesesOfInterest[[1]]$outcomeIds, negativeControls$conceptId) + + # Add positive control outcomes: + summ <- read.csv(file.path(workFolder, ""SignalInjectionSummary_Southworth.csv"")) + hypothesesOfInterest[[1]]$outcomeIds <- c(hypothesesOfInterest[[1]]$outcomeIds, summ$newOutcomeId) + + cmResult <- CohortMethod::runCmAnalyses(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + exposureDatabaseSchema = workDatabaseSchema, + exposureTable = studyCohortTable, + outcomeDatabaseSchema = workDatabaseSchema, + outcomeTable = studyCohortTable, + outputFolder = cmFolder, + cmAnalysisList = cmAnalysisList, + cdmVersion = ""5"", + drugComparatorOutcomesList = hypothesesOfInterest, + getDbCohortMethodDataThreads = 1, + createStudyPopThreads = min(4, maxCores), + createPsThreads = max(1, round(maxCores/6)), + psCvThreads = min(10, maxCores), + trimMatchStratifyThreads = min(4, maxCores), + fitOutcomeModelThreads = min(4, maxCores), + outcomeCvThreads = min(4, maxCores), + refitPsForEveryOutcome = FALSE) + # cmResult <- readRDS(file.path(cmFolder, ""outcomeModelReference.rds"")) + cmSummary <- CohortMethod::summarizeAnalyses(cmResult) + write.csv(cmSummary, file.path(workFolder, ""cmSummarySouthworth.csv""), row.names = FALSE) + + studyPopFile <- cmResult$studyPopFile[cmResult$outcomeId == hypothesesOfInterest[[1]]$outcomeIds[1]] + studyPop <- readRDS(studyPopFile) + mdrr <- CohortMethod::computeMdrr(population = studyPop, modelType = ""cox"") + write.csv(mdrr, file.path(workFolder, ""cmMdrrSouthworth.csv""), row.names = FALSE) +} + +#' Run the Graham study replication +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param workDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param studyCohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param maxCores How many parallel cores should be used? If more cores are made available +#' this can speed up the analyses. +#' +#' @export +runCohortMethodGraham <- function(connectionDetails, + cdmDatabaseSchema, + workDatabaseSchema = cdmDatabaseSchema, + studyCohortTable = ""ohdsi_ci_calibration"", + oracleTempSchema = NULL, + maxCores = 4) { + cmFolder <- file.path(workFolder, ""cmOutputGraham"") + if (!file.exists(cmFolder)) + dir.create(cmFolder) + + writeLines(""Running cohort analyses"") + cmAnalysisListFile <- system.file(""settings"", ""cmAnalysisListGraham.txt"", package = ""CiCalibration"") + cmAnalysisList <- CohortMethod::loadCmAnalysisList(cmAnalysisListFile) + + pathToHoi <- system.file(""settings"", ""cmHypothesisOfInterestGraham.txt"", package = ""CiCalibration"") + hypothesesOfInterest <- CohortMethod::loadDrugComparatorOutcomesList(pathToHoi) + + # Add negative control outcomes: + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""CiCalibration"") + negativeControls <- read.csv(pathToCsv) + negativeControls <- negativeControls[negativeControls$study == ""Graham"", ] + hypothesesOfInterest[[1]]$outcomeIds <- c(hypothesesOfInterest[[1]]$outcomeIds, negativeControls$conceptId) + + # Add positive control outcomes: + summ <- read.csv(file.path(workFolder, ""SignalInjectionSummary_Graham.csv"")) + hypothesesOfInterest[[1]]$outcomeIds <- c(hypothesesOfInterest[[1]]$outcomeIds, summ$newOutcomeId) + + cmResult <- CohortMethod::runCmAnalyses(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + exposureDatabaseSchema = workDatabaseSchema, + exposureTable = studyCohortTable, + outcomeDatabaseSchema = workDatabaseSchema, + outcomeTable = studyCohortTable, + outputFolder = cmFolder, + cmAnalysisList = cmAnalysisList, + cdmVersion = ""5"", + drugComparatorOutcomesList = hypothesesOfInterest, + getDbCohortMethodDataThreads = 1, + createStudyPopThreads = min(4, maxCores), + createPsThreads = max(1, round(maxCores/6)), + psCvThreads = min(10, maxCores), + trimMatchStratifyThreads = min(4, maxCores), + fitOutcomeModelThreads = min(4, maxCores), + outcomeCvThreads = min(4, maxCores), + refitPsForEveryOutcome = FALSE) + cmSummary <- CohortMethod::summarizeAnalyses(cmResult) + write.csv(cmSummary, file.path(workFolder, ""cmSummaryGraham.csv""), row.names = FALSE) + + # cmResult <- readRDS(file.path(cmFolder, ""outcomeModelReference.rds"")) + ps <- readRDS(cmResult$sharedPsFile[1]) + fileName <- file.path(cmFolder, ""ps.png"") + CohortMethod::plotPs(ps, fileName = fileName) + + strata <- readRDS(cmResult$strataFile[1]) + cohortMethodData <- CohortMethod::loadCohortMethodData(cmResult$cohortMethodDataFolder[1]) + balance <- CohortMethod::computeCovariateBalance(population = strata, + cohortMethodData = cohortMethodData) + fileName <- file.path(cmFolder, ""balanceScatterplot.png"") + CohortMethod::plotCovariateBalanceScatterPlot(balance = balance, fileName = fileName) + fileName <- file.path(cmFolder, ""balanceTopVarsplot.png"") + CohortMethod::plotCovariateBalanceOfTopVariables(balance = balance, fileName = fileName) + + studyPopFile <- cmResult$studyPopFile[cmResult$outcomeId == hypothesesOfInterest[[1]]$outcomeIds[1]] + studyPop <- readRDS(studyPopFile) + mdrr <- CohortMethod::computeMdrr(population = studyPop, modelType = ""cox"") + write.csv(mdrr, file.path(workFolder, ""cmMdrrGraham.csv""), row.names = FALSE) +} + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CiCalibration/R/SampleSizeAndPower.R",".R","728","22","# Copyright 2017 Observational Health Data Sciences and Informatics +# +# This file is part of CiCalibration +# +# 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. + +#' @export +computeSampleSizeAndPower <- function(workFolder, study) { + + +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CiCalibration/R/TestCode.R",".R","1632","46",".testCode <- function() { + # library(CelecoxibVsNsNSAIDs) + options(fftempdir = ""s:/FFtemp"") + + dbms <- ""pdw"" + user <- NULL + pw <- NULL + server <- ""JRDUSAPSCTL01"" + port <- 17001 + connectionDetails <- DatabaseConnector::createConnectionDetails(dbms = dbms, + server = server, + user = user, + password = pw, + port = port) + cdmDatabaseSchema <- ""cdm_truven_mdcd_v5.dbo"" + workDatabaseSchema <- ""scratch.dbo"" + studyCohortTable <- ""ohdsi_celecoxib_vs_nsnsaids"" + oracleTempSchema <- NULL + cdmVersion <- ""5"" + outputFolder <- ""S:/temp/CelecoxibVsNsNSAIDs_MDCD"" + + + cdmDatabaseSchema <- ""cdm_truven_ccae_v5.dbo"" + workDatabaseSchema <- ""scratch.dbo"" + studyCohortTable <- ""ohdsi_celecoxib_vs_nsnsaids_ccae"" + oracleTempSchema <- NULL + cdmVersion <- ""5"" + outputFolder <- ""S:/temp/CelecoxibVsNsNSAIDs_CCAE"" + + cdmDatabaseSchema <- ""cdm_truven_mdcr_v5.dbo"" + workDatabaseSchema <- ""scratch.dbo"" + studyCohortTable <- ""ohdsi_celecoxib_vs_nsnsaids_mdcr"" + oracleTempSchema <- NULL + cdmVersion <- ""5"" + outputFolder <- ""S:/temp/CelecoxibVsNsNSAIDs_MDCR"" + + execute(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + workDatabaseSchema = workDatabaseSchema, + studyCohortTable = studyCohortTable, + oracleTempSchema = oracleTempSchema, + cdmVersion = cdmVersion, + outputFolder = outputFolder) + +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CiCalibration/R/PackageResultsForSharing.R",".R","4617","91","# Copyright 2017 Observational Health Data Sciences and Informatics +# +# This file is part of CelecoxibVsNsNSAIDs +# +# 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. + +#' Package the results for sharing with OHDSI researchers +#' +#' @details +#' This function packages the results. +#' +#' @param outputFolder Name of local folder to place results; make sure to use forward slashes (/) +#' +#' @export +packageResults <- function(outputFolder) { + exportFolder <- file.path(outputFolder, ""export"") + + if (!file.exists(exportFolder)) + dir.create(exportFolder) + + outcomeReference <- readRDS(file.path(outputFolder, ""outcomeModelReference.rds"")) + analysisSummary <- read.csv(file.path(outputFolder, ""Results.csv"")) + + ### Write main results table ### + write.csv(analysisSummary, file.path(exportFolder, ""Results.csv""), row.names = FALSE) + + ### Main propensity score plot ### + psFileName <- outcomeReference$sharedPsFile[outcomeReference$sharedPsFile != """"][1] + ps <- readRDS(psFileName) + CohortMethod::plotPs(ps, fileName = file.path(exportFolder, ""PS_pref_scale.png"")) + CohortMethod::plotPs(ps, scale = ""propensity"", fileName = file.path(exportFolder, ""PS.png"")) + + ### Covariate balance table ### + balFileName <- outcomeReference$covariateBalanceFile[outcomeReference$covariateBalanceFile != """"][1] + balance <- readRDS(balFileName) + + write.csv(balance, file.path(exportFolder, ""Balance.csv""), row.names = FALSE) + + ### Two covariate balance plots ### + CohortMethod::plotCovariateBalanceScatterPlot(balance, fileName = file.path(exportFolder, + ""Balance_scatterplot.png"")) + CohortMethod::plotCovariateBalanceOfTopVariables(balance, fileName = file.path(exportFolder, + ""Balance_topVars.png"")) + + ### Empiricial calibration plots ### + negControlCohortIds <- unique(analysisSummary$outcomeId[analysisSummary$outcomeId > 100]) + for (analysisId in unique(analysisSummary$analysisId)) { + negControlSubset <- analysisSummary[analysisSummary$analysisId == analysisId & analysisSummary$outcomeId %in% + negControlCohortIds, ] + negControlSubset <- negControlSubset[!is.na(negControlSubset$logRr) & negControlSubset$logRr != + 0, ] + posControlSubset <- analysisSummary[analysisSummary$analysisId == analysisId & !(analysisSummary$outcomeId %in% + negControlCohortIds), ] + posControlSubset <- posControlSubset[!is.na(posControlSubset$logRr) & posControlSubset$logRr != + 0, ] + + if (nrow(negControlSubset) > 10) { + EmpiricalCalibration::plotCalibrationEffect(negControlSubset$logRr, + negControlSubset$seLogRr, + posControlSubset$logRr, + posControlSubset$seLogRr, + fileName = file.path(exportFolder, paste(""CalEffect_a"", + analysisId, + "".png"", + sep = """"))) + EmpiricalCalibration::plotCalibration(negControlSubset$logRr, + negControlSubset$seLogRr, + useMcmc = TRUE, + fileName = file.path(exportFolder, paste(""Calibration_a"", + analysisId, + "".png"", + sep = """"))) + } + } + + ### Add all to zip file ### + zipName <- file.path(exportFolder, ""StudyResults.zip"") + OhdsiSharing::compressFolder(exportFolder, zipName) + writeLines(paste(""\nStudy results are ready for sharing at:"", zipName)) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CiCalibration/R/CreateStudyAnalysesDetails.R",".R","19483","274","# Copyright 2017 Observational Health Data Sciences and Informatics +# +# This file is part of CiCalibration +# +# 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. + +#' Create the analyses details +#' +#' @details +#' This function creates files specifying the analyses that will be performed. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param workFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' +#' @export +createAnalysesDetails <- function(connectionDetails, cdmDatabaseSchema, workFolder) { + + # Southworh study ----------------------------------------------------- + + covariateSettings <- FeatureExtraction::createCovariateSettings(useCovariateDemographics = TRUE, useCovariateDemographicsGender = TRUE) + + getDbCmDataArgs <- CohortMethod::createGetDbCohortMethodDataArgs(excludeDrugsFromCovariates = FALSE, + covariateSettings = covariateSettings) + + createStudyPopArgsSouthworth <- CohortMethod::createCreateStudyPopulationArgs(removeSubjectsWithPriorOutcome = TRUE, + minDaysAtRisk = 1, + riskWindowStart = 0, + addExposureDaysToStart = FALSE, + riskWindowEnd = 0, + addExposureDaysToEnd = TRUE) + + fitOutcomeModelArgsSouthworth <- CohortMethod::createFitOutcomeModelArgs(modelType = ""poisson"", + useCovariates = FALSE, + stratified = FALSE) + + cmAnalysisSouthworth <- CohortMethod::createCmAnalysis(analysisId = 1, + description = ""Southworth replication"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = createStudyPopArgsSouthworth, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgsSouthworth) + + cmAnalysisListSouthworth <- list(cmAnalysisSouthworth) + + CohortMethod::saveCmAnalysisList(cmAnalysisListSouthworth, file.path(workFolder, ""cmAnalysisListSouthworth.txt"")) + + dco <- CohortMethod::createDrugComparatorOutcomes(targetId = 1, + comparatorId = 2, + outcomeIds = 3) + dcos <- list(dco) + CohortMethod::saveDrugComparatorOutcomesList(dcos, file.path(workFolder, ""cmHypothesisOfInterestSouthworth.txt"")) + + # Graham study ------------------------------------------------------ + + # Get drugs and descendants to exclude from covariates: + conn <- DatabaseConnector::connect(connectionDetails) + sql <- ""SELECT concept_id FROM @cdmDatabaseSchema.concept_ancestor INNER JOIN @cdmDatabaseSchema.concept ON descendant_concept_id = concept_id WHERE ancestor_concept_id IN (1310149, 40228152)"" + sql <- SqlRender::renderSql(sql, cdmDatabaseSchema = cdmDatabaseSchema)$sql + sql <- SqlRender::translateSql(sql, targetDialect = connectionDetails$dbms)$sql + excludeConceptIds <- DatabaseConnector::querySql(conn, sql) + excludeConceptIds <- excludeConceptIds$CONCEPT_ID + RJDBC::dbDisconnect(conn) + + covarSettings <- FeatureExtraction::createCovariateSettings(useCovariateDemographics = TRUE, + useCovariateDemographicsGender = TRUE, + useCovariateDemographicsRace = TRUE, + useCovariateDemographicsEthnicity = TRUE, + useCovariateDemographicsAge = TRUE, + useCovariateDemographicsYear = TRUE, + useCovariateDemographicsMonth = TRUE, + useCovariateConditionOccurrence = TRUE, + useCovariateConditionOccurrence365d = TRUE, + useCovariateConditionOccurrence30d = TRUE, + useCovariateConditionOccurrenceInpt180d = TRUE, + useCovariateConditionEra = TRUE, + useCovariateConditionEraEver = TRUE, + useCovariateConditionEraOverlap = TRUE, + useCovariateConditionGroup = TRUE, + useCovariateConditionGroupMeddra = TRUE, + useCovariateConditionGroupSnomed = TRUE, + useCovariateDrugExposure = TRUE, + useCovariateDrugExposure365d = TRUE, + useCovariateDrugExposure30d = TRUE, + useCovariateDrugEra = TRUE, + useCovariateDrugEra365d = TRUE, + useCovariateDrugEra30d = TRUE, + useCovariateDrugEraOverlap = TRUE, + useCovariateDrugEraEver = TRUE, + useCovariateDrugGroup = TRUE, + useCovariateProcedureOccurrence = TRUE, + useCovariateProcedureOccurrence365d = TRUE, + useCovariateProcedureOccurrence30d = TRUE, + useCovariateProcedureGroup = TRUE, + useCovariateObservation = TRUE, + useCovariateObservation365d = TRUE, + useCovariateObservation30d = TRUE, + useCovariateObservationCount365d = TRUE, + useCovariateMeasurement = TRUE, + useCovariateMeasurement365d = TRUE, + useCovariateMeasurement30d = TRUE, + useCovariateMeasurementCount365d = TRUE, + useCovariateMeasurementBelow = TRUE, + useCovariateMeasurementAbove = TRUE, + useCovariateConceptCounts = TRUE, + useCovariateRiskScores = TRUE, + useCovariateRiskScoresCharlson = TRUE, + useCovariateRiskScoresDCSI = TRUE, + useCovariateRiskScoresCHADS2 = TRUE, + useCovariateRiskScoresCHADS2VASc = TRUE, + useCovariateInteractionYear = FALSE, + useCovariateInteractionMonth = FALSE, + excludedCovariateConceptIds = excludeConceptIds, + deleteCovariatesSmallCount = 100) + + getDbCmDataArgs <- CohortMethod::createGetDbCohortMethodDataArgs(excludeDrugsFromCovariates = FALSE, + covariateSettings = covarSettings) + + createStudyPopArgsGraham <- CohortMethod::createCreateStudyPopulationArgs(removeSubjectsWithPriorOutcome = TRUE, + minDaysAtRisk = 1, + riskWindowStart = 1, + addExposureDaysToStart = FALSE, + riskWindowEnd = 0, + addExposureDaysToEnd = TRUE) + + createPsArgs <- CohortMethod::createCreatePsArgs() + + matchOnPsArgs <- CohortMethod::createMatchOnPsArgs(caliper = 0.25, + caliperScale = ""standardized"", + maxRatio = 1) + + fitOutcomeModelArgsGraham <- CohortMethod::createFitOutcomeModelArgs(modelType = ""cox"", + stratified = FALSE, + useCovariates = FALSE) + + cmAnalysisGraham <- CohortMethod::createCmAnalysis(analysisId = 1, + description = ""Graham replication"", + getDbCohortMethodDataArgs = getDbCmDataArgs, + createStudyPopArgs = createStudyPopArgsGraham, + createPs = TRUE, + createPsArgs = createPsArgs, + matchOnPs = TRUE, + matchOnPsArgs = matchOnPsArgs, + fitOutcomeModel = TRUE, + fitOutcomeModelArgs = fitOutcomeModelArgsGraham) + + cmAnalysisListGraham <- list(cmAnalysisGraham) + + CohortMethod::saveCmAnalysisList(cmAnalysisListGraham, file.path(workFolder, ""cmAnalysisListGraham.txt"")) + + dco <- CohortMethod::createDrugComparatorOutcomes(targetId = 4, + comparatorId = 5, + outcomeIds = 6) + dcos <- list(dco) + CohortMethod::saveDrugComparatorOutcomesList(dcos, file.path(workFolder, ""cmHypothesisOfInterestGraham.txt"")) + + # Tata study Case Control -------------------------------------------------------------- + + getDbCaseDataArgs <- CaseControl::createGetDbCaseDataArgs(getVisits = FALSE, + useNestingCohort = FALSE, + studyStartDate = ""19900101"", + studyEndDate = ""20031101"") + + selectControlsArgs <- CaseControl::createSelectControlsArgs(firstOutcomeOnly = TRUE, + washoutPeriod = 180, + controlsPerCase = 6, + matchOnAge = TRUE, + ageCaliper = 1, + matchOnGender = TRUE, + matchOnCareSite = TRUE, + minAge = 18) + + getDbExposureDataArgs <- CaseControl::createGetDbExposureDataArgs() + + createCaseControlDataArgs <- CaseControl::createCreateCaseControlDataArgs(firstExposureOnly = FALSE, + riskWindowStart = -30, + riskWindowEnd = 0) + + fitCaseControlModelArgs <- CaseControl::createFitCaseControlModelArgs() + + ccAnalysis <- CaseControl::createCcAnalysis(analysisId = 1, + description = ""Tata case-control replication"", + getDbCaseDataArgs = getDbCaseDataArgs, + selectControlsArgs = selectControlsArgs, + getDbExposureDataArgs = getDbExposureDataArgs, + createCaseControlDataArgs = createCaseControlDataArgs, + fitCaseControlModelArgs = fitCaseControlModelArgs) + + ccAnalysisList <- list(ccAnalysis) + + CaseControl::saveCcAnalysisList(ccAnalysisList, file.path(workFolder, ""ccAnalysisList.txt"")) + + eon <- CaseControl::createExposureOutcomeNestingCohort(exposureId = 11, + outcomeId = 14) + + eons <- list(eon) + CaseControl::saveExposureOutcomeNestingCohortList(eons, file.path(workFolder, ""ccHypothesisOfInterest.txt"")) + + # Tata study SCCS --------------------------------------------------------- + + getDbSccsDataArgs <- SelfControlledCaseSeries::createGetDbSccsDataArgs(studyStartDate = ""19900101"", + studyEndDate = ""20031101"", + exposureIds = c(""exposureId"", 12, 13)) + + covarExposureOfInt <- SelfControlledCaseSeries::createCovariateSettings(label = ""Exposure of interest"", + includeCovariateIds = ""exposureId"", + start = 0, + end = 0, + addExposedDaysToEnd = TRUE) + + covarNsaids <- SelfControlledCaseSeries::createCovariateSettings(label = ""NSAIDs"", + includeCovariateIds = 12, + start = 0, + end = 0, + addExposedDaysToEnd = TRUE) + + covarTcas <- SelfControlledCaseSeries::createCovariateSettings(label = ""TCAs"", + includeCovariateIds = 13, + start = 0, + end = 0, + addExposedDaysToEnd = TRUE) + + covarPreExposure <- SelfControlledCaseSeries::createCovariateSettings(label = ""Pre-exposure"", + includeCovariateIds = ""exposureId"", + start = -30, + end = -1) + + ageSettings <- SelfControlledCaseSeries::createAgeSettings(includeAge = TRUE, + ageKnots = 5, + minAge = 18) + + createSccsEraDataArgs <- SelfControlledCaseSeries::createCreateSccsEraDataArgs(naivePeriod = 180, + firstOutcomeOnly = FALSE, + covariateSettings = list(covarExposureOfInt, + covarNsaids, + covarTcas, + covarPreExposure), + ageSettings = ageSettings) + + fitSccsModelArgs <- SelfControlledCaseSeries::createFitSccsModelArgs() + + sccsAnalysis <- SelfControlledCaseSeries::createSccsAnalysis(analysisId = 1, + description = ""Tata SCCS replication"", + getDbSccsDataArgs = getDbSccsDataArgs, + createSccsEraDataArgs = createSccsEraDataArgs, + fitSccsModelArgs = fitSccsModelArgs) + + sccsAnalysisList <- list(sccsAnalysis) + + SelfControlledCaseSeries::saveSccsAnalysisList(sccsAnalysisList, + file.path(workFolder, ""sccsAnalysisList.txt"")) + + eo <- SelfControlledCaseSeries::createExposureOutcome(exposureId = 11, + outcomeId = 14) + eos <- list(eo) + SelfControlledCaseSeries::saveExposureOutcomeList(eos, file.path(workFolder, ""sccsHypothesisOfInterest.txt"")) +} + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CiCalibration/R/SignalInjection.R",".R","13880","186","# Copyright 2017 Observational Health Data Sciences and Informatics +# +# This file is part of CiCalibration +# +# 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. + +#' Inject outcomes on top of negative controls +#' +#' @details +#' This function injects outcomes on top of negative controls to create controls with predefined relative risks greater than one. +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param workDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param studyCohortTable The name of the study cohort table in the work database schema. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param study For which study should the cohorts be created? Options are ""SSRIs"" and ""Dabigatran"". +#' @param workFolder Name of local folder to place results; make sure to use forward slashes +#' (/) +#' @param maxCores How many parallel cores should be used? If more cores are made available +#' this can speed up the analyses. +#' +#' @export +injectSignals <- function(connectionDetails, + cdmDatabaseSchema, + workDatabaseSchema, + studyCohortTable = ""ohdsi_ci_calibration"", + oracleTempSchema, + study, + workFolder, + maxCores = 4) { + signalInjectionFolder <- file.path(workFolder, ""signalInjection"") + if (!file.exists(signalInjectionFolder)) + dir.create(signalInjectionFolder) + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""CiCalibration"") + negativeControls <- read.csv(pathToCsv) + negativeControls <- negativeControls[negativeControls$study == study, ] + + if (study == ""Tata"") { + modelType <- ""poisson"" + firstOutcomeOnly <- FALSE + removePeopleWithPriorOutcomes <- FALSE + firstExposureOnly <- FALSE + riskWindowEnd <- 30 + + pathToHoi <- system.file(""settings"", ""sccsHypothesisOfInterest.txt"", package = ""CiCalibration"") + hypothesesOfInterest <- SelfControlledCaseSeries::loadExposureOutcomeList(pathToHoi) + exposureOutcomePairs <- data.frame(exposureId = hypothesesOfInterest[[1]]$exposureId, + outcomeId = negativeControls$conceptId) + } else if (study == ""Southworth"") { + modelType <- ""survival"" + firstOutcomeOnly <- TRUE + removePeopleWithPriorOutcomes <- TRUE + firstExposureOnly <- TRUE + riskWindowEnd <- 0 + + pathToHoi <- system.file(""settings"", ""cmHypothesisOfInterestSouthworth.txt"", package = ""CiCalibration"") + hypothesesOfInterest <- CohortMethod::loadDrugComparatorOutcomesList(pathToHoi) + exposureOutcomePairs <- data.frame(exposureId = hypothesesOfInterest[[1]]$targetId, + outcomeId = negativeControls$conceptId) + } else if (study == ""Graham"") { + modelType <- ""survival"" + firstOutcomeOnly <- TRUE + removePeopleWithPriorOutcomes <- TRUE + firstExposureOnly <- TRUE + riskWindowEnd <- 0 + + pathToHoi <- system.file(""settings"", ""cmHypothesisOfInterestGraham.txt"", package = ""CiCalibration"") + hypothesesOfInterest <- CohortMethod::loadDrugComparatorOutcomesList(pathToHoi) + exposureOutcomePairs <- data.frame(exposureId = hypothesesOfInterest[[1]]$targetId, + outcomeId = negativeControls$conceptId) + } + covariateSettings <- FeatureExtraction::createCovariateSettings(useCovariateDemographics = TRUE, + useCovariateDemographicsGender = TRUE, + useCovariateDemographicsRace = TRUE, + useCovariateDemographicsEthnicity = TRUE, + useCovariateDemographicsAge = TRUE, + useCovariateDemographicsYear = TRUE, + useCovariateDemographicsMonth = TRUE, + useCovariateConditionOccurrence = TRUE, + useCovariateConditionOccurrenceLongTerm = TRUE, + useCovariateConditionOccurrenceShortTerm = TRUE, + useCovariateConditionOccurrenceInptMediumTerm = TRUE, + useCovariateConditionEra = TRUE, + useCovariateConditionEraEver = TRUE, + useCovariateConditionEraOverlap = TRUE, + useCovariateConditionGroup = TRUE, + useCovariateConditionGroupMeddra = TRUE, + useCovariateConditionGroupSnomed = TRUE, + useCovariateDrugExposure = TRUE, + useCovariateDrugExposureLongTerm = TRUE, + useCovariateDrugExposureShortTerm = TRUE, + useCovariateDrugEra = TRUE, + useCovariateDrugEraLongTerm = TRUE, + useCovariateDrugEraShortTerm = TRUE, + useCovariateDrugEraOverlap = TRUE, + useCovariateDrugEraEver = TRUE, + useCovariateDrugGroup = TRUE, + useCovariateProcedureOccurrence = TRUE, + useCovariateProcedureOccurrenceLongTerm = TRUE, + useCovariateProcedureOccurrenceShortTerm = TRUE, + useCovariateProcedureGroup = TRUE, + useCovariateObservation = TRUE, + useCovariateObservationLongTerm = TRUE, + useCovariateObservationShortTerm = TRUE, + useCovariateObservationCountLongTerm = TRUE, + useCovariateMeasurement = TRUE, + useCovariateMeasurementLongTerm = TRUE, + useCovariateMeasurementShortTerm = TRUE, + useCovariateMeasurementCountLongTerm = TRUE, + useCovariateMeasurementBelow = TRUE, + useCovariateMeasurementAbove = TRUE, + useCovariateConceptCounts = TRUE, + useCovariateRiskScores = TRUE, + useCovariateRiskScoresCharlson = TRUE, + useCovariateRiskScoresDCSI = TRUE, + useCovariateRiskScoresCHADS2 = TRUE, + useCovariateRiskScoresCHADS2VASc = TRUE, + useCovariateInteractionYear = FALSE, + useCovariateInteractionMonth = FALSE, + excludedCovariateConceptIds = c(), + includedCovariateConceptIds = c(), + deleteCovariatesSmallCount = 100, + longTermDays = 180, + mediumTermDays = 180, + shortTermDays = 30) + + summ <- MethodEvaluation::injectSignals(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = cdmDatabaseSchema, + exposureDatabaseSchema = workDatabaseSchema, + exposureTable = studyCohortTable, + outcomeDatabaseSchema = workDatabaseSchema, + outcomeTable = studyCohortTable, + outputDatabaseSchema = workDatabaseSchema, + outputTable = studyCohortTable, + createOutputTable = FALSE, + exposureOutcomePairs = exposureOutcomePairs, + modelType = modelType, + buildOutcomeModel = TRUE, + buildModelPerExposure = FALSE, + covariateSettings = covariateSettings, + minOutcomeCountForModel = 100, + minOutcomeCountForInjection = 25, + prior = Cyclops::createPrior(""laplace"", exclude = 0, useCrossValidation = TRUE), + control = Cyclops::createControl(cvType = ""auto"", + startingVariance = 0.01, + tolerance = 2e-07, + cvRepetitions = 1, + noiseLevel = ""silent"", + threads = min(10, maxCores)), + firstExposureOnly = firstExposureOnly, + washoutPeriod = 180, + riskWindowStart = 0, + riskWindowEnd = riskWindowEnd, + addExposureDaysToEnd = TRUE, + firstOutcomeOnly = firstOutcomeOnly, + removePeopleWithPriorOutcomes = removePeopleWithPriorOutcomes, + maxSubjectsForModel = 250000, + effectSizes = c(1.5, 2, 4), + precision = 0.01, + outputIdOffset = 10000, + workFolder = signalInjectionFolder, + cdmVersion = ""5"", + modelThreads = max(1, round(maxCores/8)), + generationThreads = min(6, maxCores)) + write.csv(summ, file.path(workFolder, paste0(""SignalInjectionSummary_"", study, "".csv"")), row.names = FALSE) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CiCalibration/R/Sccs.R",".R","5617","92","# Copyright 2017 Observational Health Data Sciences and Informatics +# +# This file is part of CiCalibration +# +# 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. + +#' Run the self-controlled case series +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param workDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param studyCohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param maxCores How many parallel cores should be used? If more cores are made available +#' this can speed up the analyses. +#' +#' @export +runSccs <- function(connectionDetails, + cdmDatabaseSchema, + workDatabaseSchema = cdmDatabaseSchema, + studyCohortTable = ""ohdsi_ci_calibration"", + oracleTempSchema = NULL, + maxCores = 4) { + sccsFolder <- file.path(workFolder, ""sccsOutput"") + if (!file.exists(sccsFolder)) + dir.create(sccsFolder) + + writeLines(""Running self-controlled case series"") + sccsAnalysisListFile <- system.file(""settings"", ""sccsAnalysisList.txt"", package = ""CiCalibration"") + sccsAnalysisList <- SelfControlledCaseSeries::loadSccsAnalysisList(sccsAnalysisListFile) + + pathToHoi <- system.file(""settings"", ""sccsHypothesisOfInterest.txt"", package = ""CiCalibration"") + hypothesesOfInterest <- SelfControlledCaseSeries::loadExposureOutcomeList(pathToHoi) + + # Add negative control outcomes: + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""CiCalibration"") + negativeControls <- read.csv(pathToCsv) + negativeControls <- negativeControls[negativeControls$study == ""Tata"", ] + for (outcomeId in negativeControls$conceptId) { + hoi <- SelfControlledCaseSeries::createExposureOutcome(exposureId = hypothesesOfInterest[[1]]$exposureId, + outcomeId = outcomeId) + hypothesesOfInterest[[length(hypothesesOfInterest) + 1]] <- hoi + } + + # Add positive control outcomes: + summ <- read.csv(file.path(workFolder, ""SignalInjectionSummary_Tata.csv"")) + for (outcomeId in summ$newOutcomeId) { + hoi <- SelfControlledCaseSeries::createExposureOutcome(exposureId = hypothesesOfInterest[[1]]$exposureId, + outcomeId = outcomeId) + hypothesesOfInterest[[length(hypothesesOfInterest) + 1]] <- hoi + } + + sccsResult <- SelfControlledCaseSeries::runSccsAnalyses(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + exposureDatabaseSchema = workDatabaseSchema, + exposureTable = studyCohortTable, + outcomeDatabaseSchema = workDatabaseSchema, + outcomeTable = studyCohortTable, + sccsAnalysisList = sccsAnalysisList, + exposureOutcomeList = hypothesesOfInterest, + cdmVersion = 5, + outputFolder = sccsFolder, + combineDataFetchAcrossOutcomes = TRUE, + getDbSccsDataThreads = 1, + createSccsEraDataThreads = min(3, maxCores), + fitSccsModelThreads = max(1, round(maxCores/6)), + cvThreads = min(10, maxCores)) + sccsSummary <- SelfControlledCaseSeries::summarizeSccsAnalyses(sccsResult) + write.csv(sccsSummary, file.path(workFolder, ""sccsSummary.csv""), row.names = FALSE) +} + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CiCalibration/R/CaseControl.R",".R","5793","99","# Copyright 2017 Observational Health Data Sciences and Informatics +# +# This file is part of CiCalibration +# +# 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. + +#' Run case control +#' +#' @param connectionDetails An object of type \code{connectionDetails} as created using the +#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the +#' DatabaseConnector package. +#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides. +#' Note that for SQL Server, this should include both the database and +#' schema name, for example 'cdm_data.dbo'. +#' @param workDatabaseSchema Schema name where intermediate data can be stored. You will need to have +#' write priviliges in this schema. Note that for SQL Server, this should +#' include both the database and schema name, for example 'cdm_data.dbo'. +#' @param studyCohortTable The name of the table that will be created in the work database schema. +#' This table will hold the exposure and outcome cohorts used in this +#' study. +#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write +#' priviliges for storing temporary tables. +#' @param maxCores How many parallel cores should be used? If more cores are made available +#' this can speed up the analyses. +#' +#' @export +runCaseControl <- function(connectionDetails, + cdmDatabaseSchema, + workDatabaseSchema = cdmDatabaseSchema, + studyCohortTable = ""ohdsi_ci_calibration"", + oracleTempSchema = NULL, + maxCores = 4) { + ccFolder <- file.path(workFolder, ""ccOutput"") + if (!file.exists(ccFolder)) + dir.create(ccFolder) + + writeLines(""Running case-control"") + ccAnalysisListFile <- system.file(""settings"", ""ccAnalysisList.txt"", package = ""CiCalibration"") + ccAnalysisList <- CaseControl::loadCcAnalysisList(ccAnalysisListFile) + + pathToHoi <- system.file(""settings"", ""ccHypothesisOfInterest.txt"", package = ""CiCalibration"") + hypothesesOfInterest <- CaseControl::loadExposureOutcomeNestingCohortList(pathToHoi) + + # Add negative control outcomes: + pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""CiCalibration"") + negativeControls <- read.csv(pathToCsv) + negativeControls <- negativeControls[negativeControls$study == ""Tata"", ] + for (outcomeId in negativeControls$conceptId) { + hoi <- CaseControl::createExposureOutcomeNestingCohort(exposureId = hypothesesOfInterest[[1]]$exposureId, + outcomeId = outcomeId) + hypothesesOfInterest[[length(hypothesesOfInterest) + 1]] <- hoi + } + + # Add positive control outcomes: + summ <- read.csv(file.path(workFolder, ""SignalInjectionSummary_Tata.csv"")) + for (outcomeId in summ$newOutcomeId) { + hoi <- CaseControl::createExposureOutcomeNestingCohort(exposureId = hypothesesOfInterest[[1]]$exposureId, + outcomeId = outcomeId) + hypothesesOfInterest[[length(hypothesesOfInterest) + 1]] <- hoi + } + + ccResult <- CaseControl::runCcAnalyses(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + exposureDatabaseSchema = workDatabaseSchema, + exposureTable = studyCohortTable, + outcomeDatabaseSchema = workDatabaseSchema, + outcomeTable = studyCohortTable, + ccAnalysisList = ccAnalysisList, + exposureOutcomeNestingCohortList = hypothesesOfInterest, + outputFolder = ccFolder, + prefetchExposureData = TRUE, + getDbCaseDataThreads = 1, + selectControlsThreads = min(3, maxCores), + getDbExposureDataThreads = min(3, maxCores), + createCaseControlDataThreads = min(5, maxCores), + fitCaseControlModelThreads = min(5, maxCores), + cvThreads = min(2, maxCores)) + ccSummary <- CaseControl::summarizeCcAnalyses(ccResult) + write.csv(ccSummary, file.path(workFolder, ""ccSummary.csv""), row.names = FALSE) + + # ccResult <- readRDS(file.path(ccFolder, ""outcomeModelReference.rds"")) + + caseControlDataFile <- ccResult$caseControlDataFile[ccResult$outcomeId == hypothesesOfInterest[[1]]$outcomeId] + caseControlData <- readRDS(caseControlDataFile) + mdrr <- CaseControl::computeMdrr(caseControlData = caseControlData) + write.csv(mdrr, file.path(workFolder, ""ccMdrrTata.csv""), row.names = FALSE) +} +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CiCalibration/extras/PlotsForWgMeeting.R",".R","7648","174","library(ggplot2) + +results <- data.frame() + +result <- data.frame(group = ""From literature"", + topic = ""Dabigatran, warfarin and GI bleed"", + study = ""Southworth"", + label = ""From literature"", + estimate = ""Uncalibrated"", + rr = 1.6 / 3.5, + lb = 1.6 / 3.5, + ub = 1.6 / 3.5) +results <- rbind(results, result) + +result <- data.frame(group = ""From literature"", + topic = ""Dabigatran, warfarin and GI bleed"", + study = ""Graham"", + label = ""From literature"", + estimate = ""Uncalibrated"", + rr = 1.28, + lb = 1.14, + ub = 1.44) +results <- rbind(results, result) + +cal <- read.csv(""S:/Temp/CiCalibration_Optum/Calibrated_Southworth_cohort_method.csv"") +cal <- cal[is.na(cal$trueLogRr), ] +result <- data.frame(group = ""Our replication"", + topic = ""Dabigatran, warfarin and GI bleed"", + study = ""Southworth"", + label = ""Our replication (uncalibrated)"", + estimate = ""Uncalibrated"", + rr = cal$rr, + lb = cal$ci95lb, + ub = cal$ci95ub) +results <- rbind(results, result) + +result <- data.frame(group = ""Our replication"", + topic = ""Dabigatran, warfarin and GI bleed"", + study = ""Southworth"", + label = ""Our replication (calibrated)"", + estimate = ""Calibrated"", + rr = cal$calibratedRr, + lb = cal$calibratedCi95lb, + ub = cal$calibratedCi95ub) +results <- rbind(results, result) + +cal <- read.csv(""S:/Temp/CiCalibration_Mdcr/Calibrated_Graham_cohort_method.csv"") +cal <- cal[is.na(cal$trueLogRr), ] +result <- data.frame(group = ""Our replication"", + topic = ""Dabigatran, warfarin and GI bleed"", + study = ""Graham"", + label = ""Our replication (uncalibrated)"", + estimate = ""Uncalibrated"", + rr = cal$rr, + lb = cal$ci95lb, + ub = cal$ci95ub) +results <- rbind(results, result) + +result <- data.frame(group = ""Our replication"", + topic = ""Dabigatran, warfarin and GI bleed"", + study = ""Graham"", + label = ""Our replication (calibrated)"", + estimate = ""Calibrated"", + rr = cal$calibratedRr, + lb = cal$calibratedCi95lb, + ub = cal$calibratedCi95ub) +results <- rbind(results, result) + +results$label <- factor(results$label, + levels = c(""Our replication (calibrated)"",""Our replication (uncalibrated)"",""From literature"")) + +breaks <- c(0.25, 0.5, 1, 2, 4, 6, 8, 10) +theme <- element_text(colour = ""#000000"", size = 10) +themeRA <- element_text(colour = ""#000000"", size = 10, hjust = 1) + + +ggplot(results[results$label == ""From literature"", ], + aes(x = label, + y = rr, + ymin = lb, + ymax = ub), + environment = environment()) + + geom_hline(yintercept = breaks, colour = ""#AAAAAA"", lty = 1, size = 0.2) + + geom_hline(yintercept = 1, size = 0.5) + + geom_pointrange(shape = 23, color = rgb(0,0,0.2), fill = rgb(0,0,0.2), alpha = 0.5) + + coord_flip(ylim = c(0.25, 10)) + + scale_y_continuous(""Relative risk"", trans = ""log10"", breaks = breaks, labels = breaks) + + facet_grid(study~topic) + + theme(panel.grid.minor = element_blank(), + panel.background = element_rect(fill = ""#FAFAFA"", colour = NA), + panel.grid.major = element_line(colour = ""#EEEEEE""), + axis.ticks = element_blank(), + axis.title.y = element_blank(), + axis.text.y = themeRA, + axis.text.x = theme, + legend.key = element_blank(), + strip.text.x = theme, + strip.background = element_blank(), + legend.position = ""none"") +ggsave(file.path(""s:/temp/DabiWarfarinOriginal.png""), width = 6, height = 2.1, dpi = 300) + +ggplot(results[results$label != ""Our replication (calibrated)"", ], + aes(x = label, + y = rr, + ymin = lb, + ymax = ub), + environment = environment()) + + geom_hline(yintercept = breaks, colour = ""#AAAAAA"", lty = 1, size = 0.2) + + geom_hline(yintercept = 1, size = 0.5) + + geom_pointrange(shape = 23, color = rgb(0,0,0.2), fill = rgb(0,0,0.2), alpha = 0.5) + + coord_flip(ylim = c(0.25, 10)) + + scale_y_continuous(""Relative risk"", trans = ""log10"", breaks = breaks, labels = breaks) + + facet_grid(study~topic) + + theme(panel.grid.minor = element_blank(), + panel.background = element_rect(fill = ""#FAFAFA"", colour = NA), + panel.grid.major = element_line(colour = ""#EEEEEE""), + axis.ticks = element_blank(), + axis.title.y = element_blank(), + axis.text.y = themeRA, + axis.text.x = theme, + legend.key = element_blank(), + strip.text.x = theme, + strip.background = element_blank(), + legend.position = ""none"") +ggsave(file.path(""s:/temp/DabiWarfarinReplication.png""), width = 6, height = 2.1, dpi = 300) + +ggplot(results, + aes(x = label, + y = rr, + ymin = lb, + ymax = ub), + environment = environment()) + + geom_hline(yintercept = breaks, colour = ""#AAAAAA"", lty = 1, size = 0.2) + + geom_hline(yintercept = 1, size = 0.5) + + geom_pointrange(shape = 23, color = rgb(0,0,0.2), fill = rgb(0,0,0.2), alpha = 0.5) + + coord_flip(ylim = c(0.25, 10)) + + scale_y_continuous(""Relative risk"", trans = ""log10"", breaks = breaks, labels = breaks) + + facet_grid(study~topic) + + theme(panel.grid.minor = element_blank(), + panel.background = element_rect(fill = ""#FAFAFA"", colour = NA), + panel.grid.major = element_line(colour = ""#EEEEEE""), + axis.ticks = element_blank(), + axis.title.y = element_blank(), + axis.text.y = themeRA, + axis.text.x = theme, + legend.key = element_blank(), + strip.text.x = theme, + strip.background = element_blank(), + legend.position = ""none"") +ggsave(file.path(""s:/temp/DabiWarfarin.png""), width = 6, height = 2.2, dpi = 300) + +# Ingrowing nail + positive controls estimates + CIs +cal <- read.csv(""S:/Temp/CiCalibration_Optum/Calibrated_Southworth_cohort_method.csv"") +cal <- cal[cal$outcomeId == 139099 | (!is.na(cal$oldOutcomeId) & cal$oldOutcomeId == 139099), ] +cal[, c(""rr"", ""ci95lb"", ""ci95ub"", ""trueLogRr"")] + +# Coverage Southworth +cal <- read.csv(""S:/Temp/CiCalibration_Optum/Calibrated_Southworth_cohort_method.csv"") +cal <- cal[!is.na(cal$trueLogRr), ] +cal$trueRr <- exp(cal$trueLogRr) +cal$coverage <- cal$ci95lb <= cal$trueRr & cal$ci95ub >= cal$trueRr +aggregate(coverage ~ trueRr, data = cal, mean) +cal$coverage <- cal$calibratedCi95lb <= cal$trueRr & cal$calibratedCi95ub >= cal$trueRr +aggregate(coverage ~ trueRr, data = cal, mean) + +# Error model Southworth + before and after calibration +results <- read.csv(""S:/Temp/CiCalibration_Optum/Calibrated_Southworth_cohort_method.csv"") +results[is.na(results$trueLogRr),] +controls <- results[!is.na(results$trueLogRr),] +errorModel <- EmpiricalCalibration::fitSystematicErrorModel(logRr = controls$logRr, + seLogRr = controls$seLogRr, + trueLogRr = controls$trueLogRr) +errorModel +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CiCalibration/extras/PackageMaintenance.R",".R","1989","49","# Copyright 2017 Observational Health Data Sciences and Informatics +# +# This file is part of CiCalibration +# +# 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. + +# Format and check code ---- +OhdsiRTools::formatRFolder() +OhdsiRTools::checkUsagePackage(""CiCalibration"") +OhdsiRTools::updateCopyrightYearFolder() + +# Create manual and vignette ---- +shell(""CiCalibration.pdf"") +shell(""R CMD Rd2pdf ./ --output=extras/CiCalibration.pdf"") + +# Insert cohort definitions into package ---- +pathToCsv <- system.file(""settings"", ""CohortsToCreate.csv"", package = ""CiCalibration"") +cohortsToCreate <- read.csv(pathToCsv) +for (i in 1:nrow(cohortsToCreate)) { + writeLines(paste(""Inserting cohort:"", cohortsToCreate$name[i])) + OhdsiRTools::insertCohortDefinitionInPackage(cohortsToCreate$atlasId[i], cohortsToCreate$name[i]) +} + + +# Create analysis details ---- +connectionDetails <- DatabaseConnector::createConnectionDetails(dbms = ""pdw"", + server = ""JRDUSAPSCTL01"", + user = NULL, + password = NULL, + port = 17001) +cdmDatabaseSchema <- ""cdm_truven_ccae_v483.dbo"" +createAnalysesDetails(connectionDetails, cdmDatabaseSchema, ""inst/settings/"") + +# Store environment in which the study was executed ---- +OhdsiRTools::insertEnvironmentSnapshotInPackage(""CiCalibration"") + + + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CiCalibration/extras/PrepareDataForPaper.R",".R","27864","574","require(ggplot2) + +mdcrFolder <- ""S:/Temp/CiCalibration_Mdcr"" +optumFolder <- ""S:/Temp/CiCalibration_Optum"" +cprdFolder <- ""S:/Temp/CiCalibration_Cprd"" + +paperFolder <- ""S:/temp/CiCalibrationPaper/data"" +if (!file.exists(paperFolder)) + dir.create(paperFolder, recursive = TRUE) + +# Ingrowing nail model and performance ------------------------------------ + +modelFile <- file.path(optumFolder, ""signalInjection"", ""model_o139099"", ""betas.rds"") +model <- readRDS(modelFile) +model$id <- NULL +saveRDS(model, file.path(paperFolder, ""ingrownNailModel.rds"")) + +predictionFile <- file.path(optumFolder, ""signalInjection"", ""model_o139099"", ""prediction.rds"") +prediction <- readRDS(predictionFile) +exposuresFile <- file.path(optumFolder, ""signalInjection"", ""exposures.rds"") +exposures <- readRDS(exposuresFile) +m <- merge(prediction, exposures[, c(""rowId"", ""personId"", ""cohortStartDate"")]) +m$subjectId <- m$personId + +studyPopFile <- file.path(optumFolder, ""cmOutputSouthworth"", ""StudyPop_l1_s1_t1_c2_o139099.rds"") +studyPop <- readRDS(studyPopFile) +studyPop$y <- 0 +studyPop$y[studyPop$daysToEvent <= 365] <- 1 +m <- merge(studyPop[,c(""subjectId"",""cohortStartDate"", ""y"")], m) +m$propensityScore <- m$prediction +m$treatment <- m$y +auc <- CohortMethod::computePsAuc(m) +saveRDS(auc, file.path(paperFolder, ""ingrownNailAuc.rds"")) + +# Ingrowing nail estimates ------------------------------------------------ + +calibratedFile <- file.path(optumFolder, ""Calibrated_Southworth_cohort_method.csv"") +calibrated <- read.csv(calibratedFile) +ign <- calibrated[calibrated$outcomeId == 139099 | (!is.na(calibrated$oldOutcomeId) & calibrated$oldOutcomeId == 139099), ] +ign$trueRr <- exp(ign$trueLogRr) +ign <- ign[, c(""rr"", ""ci95lb"" ,""ci95ub"", ""trueRr"")] +saveRDS(ign, file.path(paperFolder, ""ingrownNailEstimates.rds"")) + +# Estimates for controls (calibrated and uncalibrated) -------------------------------- + +estimates <- data.frame() + +calibratedFile <- file.path(optumFolder, ""Calibrated_Southworth_cohort_method.csv"") +calibrated <- read.csv(calibratedFile) +calibrated$outcomeId[!is.na(calibrated$oldOutcomeId)] <- calibrated$oldOutcomeId[!is.na(calibrated$oldOutcomeId)] +calibrated <- calibrated[!is.na(calibrated$trueLogRr), c(""outcomeId"", ""trueLogRr"", ""rr"", ""ci95lb"", ""ci95ub"", ""logRr"", ""seLogRr"", ""calibratedRr"", ""calibratedCi95lb"", ""calibratedCi95ub"", ""calibratedLogRr"", ""calibratedSeLogRr"")] +calibrated$study <- ""Southworth"" +estimates <- rbind(estimates, calibrated) + +calibratedFile <- file.path(mdcrFolder, ""Calibrated_Graham_cohort_method.csv"") +calibrated <- read.csv(calibratedFile) +calibrated$outcomeId[!is.na(calibrated$oldOutcomeId)] <- calibrated$oldOutcomeId[!is.na(calibrated$oldOutcomeId)] +calibrated <- calibrated[!is.na(calibrated$trueLogRr), c(""outcomeId"", ""trueLogRr"", ""rr"", ""ci95lb"", ""ci95ub"", ""logRr"", ""seLogRr"", ""calibratedRr"", ""calibratedCi95lb"", ""calibratedCi95ub"", ""calibratedLogRr"", ""calibratedSeLogRr"")] +calibrated$study <- ""Graham"" +estimates <- rbind(estimates, calibrated) + +calibratedFile <- file.path(cprdFolder, ""Calibrated_Tata_case_control.csv"") +calibrated <- read.csv(calibratedFile) +calibrated$outcomeId[!is.na(calibrated$oldOutcomeId)] <- calibrated$oldOutcomeId[!is.na(calibrated$oldOutcomeId)] +calibrated <- calibrated[!is.na(calibrated$trueLogRr), c(""outcomeId"", ""trueLogRr"", ""rr"", ""ci95lb"", ""ci95ub"", ""logRr"", ""seLogRr"", ""calibratedRr"", ""calibratedCi95lb"", ""calibratedCi95ub"", ""calibratedLogRr"", ""calibratedSeLogRr"")] +calibrated$study <- ""Tata - CC"" +estimates <- rbind(estimates, calibrated) + +calibratedFile <- file.path(cprdFolder, ""Calibrated_Tata_sccs.csv"") +calibrated <- read.csv(calibratedFile) +calibrated$outcomeId[!is.na(calibrated$oldOutcomeId)] <- calibrated$oldOutcomeId[!is.na(calibrated$oldOutcomeId)] +calibrated <- calibrated[!is.na(calibrated$trueLogRr), c(""outcomeId"", ""trueLogRr"", ""rr"", ""ci95lb"", ""ci95ub"", ""logRr"", ""seLogRr"", ""calibratedRr"", ""calibratedCi95lb"", ""calibratedCi95ub"", ""calibratedLogRr"", ""calibratedSeLogRr"")] +calibrated$study <- ""Tata - SCCS"" +estimates <- rbind(estimates, calibrated) + +saveRDS(estimates, file.path(paperFolder, ""controlEstimates.rds"")) + + +# Leave one out cross validation ------------------------------------------ + +estimates <- readRDS(file.path(paperFolder, ""controlEstimates.rds"")) + +library(EmpiricalCalibration) +prepareCalibration <- function(logRr, + seLogRr, + trueLogRr, + strata = as.factor(trueLogRr), + crossValidationGroup = 1:length(logRr), + legendPosition = ""top"", + title, + fileName = NULL) { + if (!is.null(strata) && !is.factor(strata)) + stop(""Strata argument should be a factor (or null)"") + if (is.null(strata)) + strata = as.factor(-1) + data <- data.frame(logRr = logRr, + seLogRr = seLogRr, + trueLogRr = trueLogRr, + strata = strata, + crossValidationGroup = crossValidationGroup) + if (any(is.infinite(data$seLogRr))) { + warning(""Estimate(s) with infinite standard error detected. Removing before fitting error model"") + data <- data[!is.infinite(seLogRr), ] + } + if (any(is.infinite(data$logRr))) { + warning(""Estimate(s) with infinite logRr detected. Removing before fitting error model"") + data <- data[!is.infinite(logRr), ] + } + if (any(is.na(data$seLogRr))) { + warning(""Estimate(s) with NA standard error detected. Removing before fitting error model"") + data <- data[!is.na(seLogRr), ] + } + if (any(is.na(data$logRr))) { + warning(""Estimate(s) with NA logRr detected. Removing before fitting error model"") + data <- data[!is.na(logRr), ] + } + computeCoverage <- function(j, subResult, dataLeftOut, model) { + subset <- dataLeftOut[dataLeftOut$strata == subResult$strata[j],] + if (nrow(subset) == 0) + return(0) + #writeLines(paste0(""ciWidth: "", subResult$ciWidth[j], "", strata: "", subResult$strata[j], "", model: "", paste(model, collapse = "",""))) + #writeLines(paste0(""ciWidth: "", subResult$ciWidth[j], "", logRr: "", paste(subset$logRr, collapse = "",""), "", seLogRr:"", paste(subset$seLogRr, collapse = "",""), "", model: "", paste(model, collapse = "",""))) + ci <- EmpiricalCalibration::calibrateConfidenceInterval(logRr = subset$logRr, + seLogRr = subset$seLogRr, + ciWidth = subResult$ciWidth[j], + model = model) + below <- sum(subset$trueLogRr < ci$logLb95Rr) + within <- sum(ci$logLb95Rr <= subset$trueLogRr & ci$logUb95Rr >= subset$trueLogRr) + above <- sum(subset$trueLogRr > ci$logUb95Rr) + return(c(below, within, above)) + } + + computeTheoreticalCoverage <- function(j, subResult, dataLeftOut) { + subset <- dataLeftOut[dataLeftOut$strata == subResult$strata[j],] + ciWidth <- subResult$ciWidth[j] + logLb95Rr <- subset$logRr + qnorm((1-ciWidth)/2)*subset$seLogRr + logUb95Rr <- subset$logRr - qnorm((1-ciWidth)/2)*subset$seLogRr + below <- sum(subset$trueLogRr < logLb95Rr) + within <- sum(subset$trueLogRr >= logLb95Rr & subset$trueLogRr <= logUb95Rr) + above <- sum(subset$trueLogRr > logUb95Rr) + return(c(below, within, above)) + } + + computeLooCoverage <- function(leaveOutGroup, data) { + dataLeaveOneOut <- data[data$crossValidationGroup != leaveOutGroup, ] + dataLeftOut <- data[data$crossValidationGroup == leaveOutGroup, ] + if (nrow(dataLeaveOneOut) == 0 || nrow(dataLeftOut) == 0) + return(data.frame()) + + model <- fitSystematicErrorModel(logRr = dataLeaveOneOut$logRr, + seLogRr = dataLeaveOneOut$seLogRr, + trueLogRr = dataLeaveOneOut$trueLogRr, + estimateCovarianceMatrix = FALSE) + + strata <- unique(dataLeftOut$strata) + ciWidth <- seq(0.01, 0.99, by = 0.01) + subResult <- expand.grid(strata, ciWidth) + names(subResult) <- c(""strata"", ""ciWidth"") + coverage <- sapply(1:nrow(subResult), computeCoverage, subResult = subResult, dataLeftOut = dataLeftOut, model = model) + subResult$below <- coverage[1,] + subResult$within <- coverage[2,] + subResult$above <- coverage[3,] + theoreticalCoverage <- sapply(1:nrow(subResult), computeTheoreticalCoverage, subResult = subResult, dataLeftOut = dataLeftOut) + subResult$theoreticalBelow <- theoreticalCoverage[1, ] + subResult$theoreticalWithin <- theoreticalCoverage[2, ] + subResult$theoreticalAbove <- theoreticalCoverage[3, ] + return(subResult) + } + writeLines(""Fitting error models within leave-one-out cross-validation"") + coverages <- lapply(unique(data$crossValidationGroup), computeLooCoverage, data = data) + coverage <- do.call(""rbind"", coverages) + data$count <- 1 + counts <- aggregate(count ~ strata, data = data, sum) + belowCali <- aggregate(below ~ strata + ciWidth, data = coverage, sum) + belowCali <- merge(belowCali, counts, by = ""strata"") + belowCali$coverage <- belowCali$below / belowCali$count + belowCali$label <- ""Below confidence interval"" + belowCali$type <- ""Calibrated"" + withinCali <- aggregate(within ~ strata + ciWidth, data = coverage, sum) + withinCali <- merge(withinCali, counts, by = ""strata"") + withinCali$coverage <- withinCali$within / withinCali$count + withinCali$label <- ""Within confidence interval"" + withinCali$type <- ""Calibrated"" + aboveCali <- aggregate(above ~ strata + ciWidth, data = coverage, sum) + aboveCali <- merge(aboveCali, counts, by = ""strata"") + aboveCali$coverage <- aboveCali$above / aboveCali$count + aboveCali$label <- ""Above confidence interval"" + aboveCali$type <- ""Calibrated"" + belowUncali <- aggregate(theoreticalBelow ~ strata + ciWidth, data = coverage, sum) + belowUncali <- merge(belowUncali, counts, by = ""strata"") + belowUncali$coverage <- belowUncali$theoreticalBelow / belowUncali$count + belowUncali$label <- ""Below confidence interval"" + belowUncali$type <- ""Uncalibrated"" + withinUncali <- aggregate(theoreticalWithin ~ strata + ciWidth, data = coverage, sum) + withinUncali <- merge(withinUncali, counts, by = ""strata"") + withinUncali$coverage <- withinUncali$theoreticalWithin / withinUncali$count + withinUncali$label <- ""Within confidence interval"" + withinUncali$type <- ""Uncalibrated"" + aboveUncali <- aggregate(theoreticalAbove ~ strata + ciWidth, data = coverage, sum) + aboveUncali <- merge(aboveUncali, counts, by = ""strata"") + aboveUncali$coverage <- aboveUncali$theoreticalAbove / aboveUncali$count + aboveUncali$label <- ""Above confidence interval"" + aboveUncali$type <- ""Uncalibrated"" + vizData <- rbind(belowCali[, c(""strata"", ""label"", ""type"", ""ciWidth"", ""coverage"")], + withinCali[, c(""strata"", ""label"", ""type"", ""ciWidth"", ""coverage"")], + aboveCali[, c(""strata"", ""label"", ""type"", ""ciWidth"", ""coverage"")], + belowUncali[, c(""strata"", ""label"", ""type"", ""ciWidth"", ""coverage"")], + withinUncali[, c(""strata"", ""label"", ""type"", ""ciWidth"", ""coverage"")], + aboveUncali[, c(""strata"", ""label"", ""type"", ""ciWidth"", ""coverage"")]) + names(vizData)[names(vizData) == ""type""] <- ""Confidence interval calculation"" + vizData$trueRr <- as.factor(exp(as.numeric(as.character(vizData$strata)))) + return(vizData) +} + +allCali <- data.frame() +for (study in unique(estimates$study)) { + print(study) + studyData <- estimates[estimates$study == study, ] + cali <- prepareCalibration(logRr = studyData$logRr, + seLogRr = studyData$seLogRr, + trueLogRr = studyData$trueLogRr, + crossValidationGroup = studyData$outcomeId) + cali$study <- study + allCali <- rbind(allCali, cali) +} +saveRDS(allCali, file.path(paperFolder, ""calibration.rds"")) + + +# Estimates for HOIs ------------------------------------------------------ + +results <- data.frame() + +result <- data.frame(group = ""Original study"", + topic = ""Dabigatran, warfarin and GI bleed"", + study = ""Southworth"", + label = ""Original study"", + estimate = ""Uncalibrated"", + rr = 1.6 / 3.5, + lb = 1.6 / 3.5, + ub = 1.6 / 3.5) +results <- rbind(results, result) + +result <- data.frame(group = ""Original study"", + topic = ""Dabigatran, warfarin and GI bleed"", + study = ""Graham"", + label = ""Original study"", + estimate = ""Uncalibrated"", + rr = 1.28, + lb = 1.14, + ub = 1.44) +results <- rbind(results, result) + +cal <- read.csv(file.path(optumFolder, ""Calibrated_Southworth_cohort_method.csv"")) +cal <- cal[is.na(cal$trueLogRr), ] +result <- data.frame(group = ""Our replication"", + topic = ""Dabigatran, warfarin and GI bleed"", + study = ""Southworth"", + label = ""Our replication"", + estimate = ""Uncalibrated"", + rr = cal$rr, + lb = cal$ci95lb, + ub = cal$ci95ub) +results <- rbind(results, result) + +result <- data.frame(group = ""Our replication"", + topic = ""Dabigatran, warfarin and GI bleed"", + study = ""Southworth"", + label = ""Our replication (calibrated)"", + estimate = ""Calibrated"", + rr = cal$calibratedRr, + lb = cal$calibratedCi95lb, + ub = cal$calibratedCi95ub) +results <- rbind(results, result) + +cal <- read.csv(file.path(mdcrFolder, ""Calibrated_Graham_cohort_method.csv"")) +cal <- cal[is.na(cal$trueLogRr), ] +result <- data.frame(group = ""Our replication"", + topic = ""Dabigatran, warfarin and GI bleed"", + study = ""Graham"", + label = ""Our replication"", + estimate = ""Uncalibrated"", + rr = cal$rr, + lb = cal$ci95lb, + ub = cal$ci95ub) +results <- rbind(results, result) + +result <- data.frame(group = ""Our replication"", + topic = ""Dabigatran, warfarin and GI bleed"", + study = ""Graham"", + label = ""Our replication (calibrated)"", + estimate = ""Calibrated"", + rr = cal$calibratedRr, + lb = cal$calibratedCi95lb, + ub = cal$calibratedCi95ub) +results <- rbind(results, result) + +results$label <- factor(results$label, + levels = c(""Our replication (calibrated)"",""Our replication"",""Original study"")) +saveRDS(results, file.path(paperFolder, ""hoiEstimatesDabi.rds"")) + +results <- data.frame() + +result <- data.frame(group = ""Original study"", + topic = ""SSRIs and upper GI bleed"", + study = ""Tata - CC"", + label = ""Original study"", + estimate = ""Uncalibrated"", + rr = 2.38, + lb = 2.08, + ub = 2.72) +results <- rbind(results, result) + +result <- data.frame(group = ""Original study"", + topic = ""SSRIs and upper GI bleed"", + study = ""Tata - SCCS"", + label = ""Original study"", + estimate = ""Uncalibrated"", + rr = 1.71, + lb = 1.48, + ub = 1.98) +results <- rbind(results, result) + +cal <- read.csv(file.path(cprdFolder, ""Calibrated_Tata_case_control.csv"")) +cal <- cal[is.na(cal$trueLogRr), ] +result <- data.frame(group = ""Our replication"", + topic = ""SSRIs and upper GI bleed"", + study = ""Tata - CC"", + label = ""Our replication"", + estimate = ""Uncalibrated"", + rr = cal$rr, + lb = cal$ci95lb, + ub = cal$ci95ub) +results <- rbind(results, result) + +result <- data.frame(group = ""Our replication"", + topic = ""SSRIs and upper GI bleed"", + study = ""Tata - CC"", + label = ""Our replication (calibrated)"", + estimate = ""Calibrated"", + rr = cal$calibratedRr, + lb = cal$calibratedCi95lb, + ub = cal$calibratedCi95ub) +results <- rbind(results, result) + +cal <- read.csv(file.path(cprdFolder, ""Calibrated_Tata_sccs.csv"")) +cal <- cal[is.na(cal$trueLogRr), ] +result <- data.frame(group = ""Our replication"", + topic = ""SSRIs and upper GI bleed"", + study = ""Tata - SCCS"", + label = ""Our replication"", + estimate = ""Uncalibrated"", + rr = cal$rr, + lb = cal$ci95lb, + ub = cal$ci95ub) +results <- rbind(results, result) + +result <- data.frame(group = ""Our replication"", + topic = ""SSRIs and upper GI bleed"", + study = ""Tata - SCCS"", + label = ""Our replication (calibrated)"", + estimate = ""Calibrated"", + rr = cal$calibratedRr, + lb = cal$calibratedCi95lb, + ub = cal$calibratedCi95ub) +results <- rbind(results, result) + +results$label <- factor(results$label, + levels = c(""Our replication (calibrated)"",""Our replication"",""Original study"")) + +saveRDS(results, file.path(paperFolder, ""hoiEstimatesTata.rds"")) + + +# Negative controls ------------------------------------------------------- + +pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""CiCalibration"") +negativeControls <- read.csv(pathToCsv) +negativeControlsSouthworth <- negativeControls[negativeControls$study == ""Southworth"", ] + +negativeControlsTata <- negativeControls[negativeControls$study == ""Tata"", ] + + +# Fitted error models ----------------------------------------------------- + +library(EmpiricalCalibration) +estimates <- readRDS(file.path(paperFolder, ""controlEstimates.rds"")) + +models <- data.frame() +for (study in unique(estimates$study)) { + print(study) + studyData <- estimates[estimates$study == study, ] + m <- fitSystematicErrorModel(logRr = studyData$logRr, + seLogRr = studyData$seLogRr, + trueLogRr = studyData$trueLogRr, + estimateCovarianceMatrix = TRUE) + model <- paste0(formatC(as.vector(m), digits = 2, format = ""f""), + "" ("", + formatC(attr(m, ""LB95CI""), digits = 2, format = ""f""), + ""-"", + formatC(attr(m, ""UB95CI""), digits = 2, format = ""f""), + "")"") + names(model) <- names(m) + model <- as.data.frame(t(model)) + model$study <- study + models <- rbind(models, model) +} +saveRDS(models, file.path(paperFolder, ""models.rds"")) + + +# Covariate counts in all studies ----------------------------------------- + +library(ffbase) +load.ffdf(file.path(cprdFolder, ""signalInjection"", ""covariates"")) +cprdCovs <- nrow(covariateRef) + +load.ffdf(file.path(optumFolder, ""signalInjection"", ""covariates"")) +optumCovs <- nrow(covariateRef) + +load.ffdf(file.path(mdcrFolder, ""signalInjection"", ""covariates"")) +mdcrCovs <- nrow(covariateRef) + +covCounts <- data.frame(study = c(""Tata - SCCS"", ""Tata - CC"", ""Southworth"", ""Graham""), + covariateCount = c(cprdCovs, cprdCovs, optumCovs, mdcrCovs)) +saveRDS(covCounts, file.path(paperFolder, ""covCounts.rds"")) + + +# Population counts ------------------------------------------------------- + + +cal <- read.csv(file.path(optumFolder, ""Calibrated_Southworth_cohort_method.csv"")) +cal <- cal[cal$outcomeId == 3, ] +southworthCounts <- c(cal$treated, cal$comparator) + +cal <- read.csv(file.path(mdcrFolder, ""Calibrated_Graham_cohort_method.csv"")) +cal <- cal[cal$outcomeId == 6, ] +grahamCounts <- c(cal$treated, cal$comparator) + +cal <- read.csv(file.path(cprdFolder, ""Calibrated_Tata_case_control.csv"")) +cal <- cal[cal$outcomeId == 14, ] +tataCcCounts <- c(cal$cases, cal$control) + +cal <- read.csv(file.path(cprdFolder, ""Calibrated_Tata_sccs.csv"")) +cal <- cal[cal$outcomeId == 14, ] +tataSccsCounts <- c(cal$caseCount) + +popCounts <- data.frame(southworthTarget = southworthCounts[1], + southworthComparator = southworthCounts[2], + grahamTarget = grahamCounts[1], + grahamComparator = grahamCounts[2], + ccCases = tataCcCounts[1], + ccControls = tataCcCounts[2], + sccsCases = tataSccsCounts[1]) +saveRDS(popCounts, file.path(paperFolder, ""popCounts.rds"")) + + +# All estimates for supporting information -------------------------------- + +pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""CiCalibration"") +negativeControls <- read.csv(pathToCsv) +pathToCsv <- system.file(""settings"", ""CohortsToCreate.csv"", package = ""CiCalibration"") +cohortsToCreate <- read.csv(pathToCsv) +idToNames <- data.frame(outcomeId = c(negativeControls$conceptId, cohortsToCreate$cohortId), + outcomeName = c(as.character(negativeControls$name), as.character(cohortsToCreate$name))) +idToNames <- unique(idToNames) +estimates <- data.frame() + +calibratedFile <- file.path(optumFolder, ""Calibrated_Southworth_cohort_method.csv"") +calibrated <- read.csv(calibratedFile) +calibrated$outcomeId[!is.na(calibrated$oldOutcomeId)] <- calibrated$oldOutcomeId[!is.na(calibrated$oldOutcomeId)] +calibrated$study <- ""Southworth replication"" +calibrated <- merge(calibrated, idToNames) +calibrated$trueRr <- exp(calibrated$trueLogRr) +calibrated <- calibrated[, c(""study"", ""outcomeName"", ""trueRr"", ""rr"", ""ci95lb"", ""ci95ub"", ""p"", ""calibratedRr"", ""calibratedCi95lb"", ""calibratedCi95ub"", ""calibratedP"")] +estimates <- rbind(estimates, calibrated) + +calibratedFile <- file.path(mdcrFolder, ""Calibrated_Graham_cohort_method.csv"") +calibrated <- read.csv(calibratedFile) +calibrated$outcomeId[!is.na(calibrated$oldOutcomeId)] <- calibrated$oldOutcomeId[!is.na(calibrated$oldOutcomeId)] +calibrated$study <- ""Graham replication"" +calibrated <- merge(calibrated, idToNames) +calibrated$trueRr <- exp(calibrated$trueLogRr) +calibrated <- calibrated[, c(""study"", ""outcomeName"", ""trueRr"", ""rr"", ""ci95lb"", ""ci95ub"", ""p"", ""calibratedRr"", ""calibratedCi95lb"", ""calibratedCi95ub"", ""calibratedP"")] +estimates <- rbind(estimates, calibrated) + +calibratedFile <- file.path(cprdFolder, ""Calibrated_Tata_case_control.csv"") +calibrated <- read.csv(calibratedFile) +calibrated$outcomeId[!is.na(calibrated$oldOutcomeId)] <- calibrated$oldOutcomeId[!is.na(calibrated$oldOutcomeId)] +calibrated$study <- ""Tata case-control replication"" +calibrated <- merge(calibrated, idToNames) +calibrated$trueRr <- exp(calibrated$trueLogRr) +calibrated <- calibrated[, c(""study"", ""outcomeName"", ""trueRr"", ""rr"", ""ci95lb"", ""ci95ub"", ""p"", ""calibratedRr"", ""calibratedCi95lb"", ""calibratedCi95ub"", ""calibratedP"")] +estimates <- rbind(estimates, calibrated) + +calibratedFile <- file.path(cprdFolder, ""Calibrated_Tata_sccs.csv"") +calibrated <- read.csv(calibratedFile) +calibrated$outcomeId[!is.na(calibrated$oldOutcomeId)] <- calibrated$oldOutcomeId[!is.na(calibrated$oldOutcomeId)] +calibrated$study <- ""Tata SCCS replication"" +calibrated <- merge(calibrated, idToNames) +calibrated$trueRr <- exp(calibrated$trueLogRr) +calibrated$p <- EmpiricalCalibration::computeTraditionalP(calibrated$logRr, calibrated$seLogRr) +calibrated <- calibrated[, c(""study"", ""outcomeName"", ""trueRr"", ""rr"", ""ci95lb"", ""ci95ub"", ""p"", ""calibratedRr"", ""calibratedCi95lb"", ""calibratedCi95ub"", ""calibratedP"")] +estimates <- rbind(estimates, calibrated) + +idx <- !is.na(estimates$trueRr) & !estimates$trueRr == 1 +estimates$outcomeName <- as.character(estimates$outcomeName) +estimates$outcomeName[idx] <- paste0(estimates$outcomeName[idx], ""(RR="", estimates$trueRr[idx], "")"") +write.csv(estimates, file.path(paperFolder, ""AllEstimates.csv""), row.names = FALSE) + + +# Sample size evaluation -------------------------------------------------- + +estimates <- readRDS(file.path(paperFolder, ""controlEstimates.rds"")) + +library(EmpiricalCalibration) +study <- ""Southworth"" +i <- 1 +outcomeId <- outcomeIds[1] +result <- expand.grid(study = unique(estimates$study), i = 1:100) + +computeCoverageForOutcomeId <- function(outcomeId, sampledOutcomeIds, subset) { + sampleOutcomeIdsWithoutControl <- sampledOutcomeIds[sampledOutcomeIds != outcomeId] + sampleWithoutControl <- subset[subset$outcomeId %in% sampleOutcomeIdsWithoutControl, ] + model <- fitSystematicErrorModel(logRr = sampleWithoutControl$logRr, + seLogRr = sampleWithoutControl$seLogRr, + trueLogRr = sampleWithoutControl$trueLogRr, + estimateCovarianceMatrix = FALSE) + control <- subset[subset$outcomeId == outcomeId, ] + ci <- calibrateConfidenceInterval(logRr = control$logRr, + seLogRr = control$seLogRr, + model = model, + ciWidth = 0.95) + ci <- ci[!is.na(ci$seLogRr), ] + return(ci$logLb95Rr < control$trueLogRr & ci$logUb95Rr > control$trueLogRr) +} + +computeCoverage <- function(i, sampleSize, outcomeIds, subset) { + sampledOutcomeIds <- outcomeIds[sample.int(length(outcomeIds), sampleSize, replace = TRUE)] + coverage <- lapply(outcomeIds, computeCoverageForOutcomeId, sampledOutcomeIds = sampledOutcomeIds, subset = subset) + coverage <- do.call(""c"", coverage) + return(mean(coverage)) +} + +computeCoverageForSampleSize <- function(sampleSize, outcomeIds, subset) { + writeLines(paste(""- Sample size ="", sampleSize)) + coverage <- sapply(1:100, computeCoverage, sampleSize = sampleSize, outcomeIds = outcomeIds, subset = subset) + return(data.frame(sampleSize = sampleSize, i = 1:100, coverage = coverage)) +} + +results <- data.frame() +for (study in unique(estimates$study)) { + writeLines(study) + subset <- estimates[estimates$study == study, ] + outcomeIds <- unique(subset$outcomeId) + result <- lapply(seq(5, length(outcomeIds), by = 5), computeCoverageForSampleSize, outcomeIds = outcomeIds, subset = subset) + result <- do.call(""rbind"", result) + result$study <- study + results <- rbind(results, result) +} +write.csv(result, file.path(paperFolder, ""powerConsiderations.csv""), row.names = FALSE) +library(ggplot2) +yBreaks <- c(0, 0.25, 0.5, 0.75, 0.95) +ggplot(results, aes(x = sampleSize, y = coverage, group = sampleSize)) + + geom_boxplot(fill = rgb(0, 0, 0.8, alpha = 0.25)) + + geom_hline(yintercept = 0.95, alpha = 0.5, linetype = ""dashed"") + + scale_x_continuous(""Number of negative controls"", limits = c(0,55), breaks = unique(results$sampleSize), labels = unique(results$sampleSize)) + + scale_y_continuous(""Coverage"", breaks = yBreaks, labels = yBreaks) + + facet_wrap(~ study) + + theme(panel.grid.minor = element_blank(), + panel.background = element_rect(fill = ""#FAFAFA"", colour = NA), panel.grid.major = ggplot2::element_blank(), + axis.ticks = element_blank(), + strip.background = element_blank(), + legend.position = ""none"") +ggsave(file.path(paperFolder, ""numberOfControls.png""), width = 7, height = 5, dpi = 400) + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CiCalibration/extras/PlotsForPaper.R",".R","12721","286","library(ggplot2) + +workFolder <- ""S:/Temp/CiCalibration_Mdcd"" + +paperFolder <- file.path(workFolder, ""papers"") +if (!file.exists(paperFolder)) { + dir.create(paperFolder) +} + + +# SSRIs and upper GI bleed ------------------------------------------------ + +results <- data.frame() + +result <- data.frame(group = ""From literature"", + topic = ""SSRIs and upper GI bleed"", + study = ""Tata - CC"", + label = ""From literature"", + estimate = ""Uncalibrated"", + rr = 2.38, + lb = 2.08, + ub = 2.72) +results <- rbind(results, result) + +result <- data.frame(group = ""From literature"", + topic = ""SSRIs and upper GI bleed"", + study = ""Tata - SCCS"", + label = ""From literature"", + estimate = ""Uncalibrated"", + rr = 1.71, + lb = 1.48, + ub = 1.98) +results <- rbind(results, result) + +cal <- read.csv(""S:/Temp/CiCalibration_Mdcd/Calibrated_Tata_case_control.csv"") +cal <- cal[is.na(cal$trueLogRr), ] +result <- data.frame(group = ""Our replication"", + topic = ""SSRIs and upper GI bleed"", + study = ""Tata - CC"", + label = ""Our replication (uncalibrated)"", + estimate = ""Uncalibrated"", + rr = cal$rr, + lb = cal$ci95lb, + ub = cal$ci95ub) +results <- rbind(results, result) + +result <- data.frame(group = ""Our replication"", + topic = ""SSRIs and upper GI bleed"", + study = ""Tata - CC"", + label = ""Our replication (calibrated)"", + estimate = ""Calibrated"", + rr = cal$calibratedRr, + lb = cal$calibratedCi95lb, + ub = cal$calibratedCi95ub) +results <- rbind(results, result) + +cal <- read.csv(""S:/Temp/CiCalibration_Mdcd/Calibrated_Tata_sccs.csv"") +cal <- cal[is.na(cal$trueLogRr), ] +result <- data.frame(group = ""Our replication"", + topic = ""SSRIs and upper GI bleed"", + study = ""Tata - SCCS"", + label = ""Our replication (uncalibrated)"", + estimate = ""Uncalibrated"", + rr = cal$rr, + lb = cal$ci95lb, + ub = cal$ci95ub) +results <- rbind(results, result) + +result <- data.frame(group = ""Our replication"", + topic = ""SSRIs and upper GI bleed"", + study = ""Tata - SCCS"", + label = ""Our replication (calibrated)"", + estimate = ""Calibrated"", + rr = cal$calibratedRr, + lb = cal$calibratedCi95lb, + ub = cal$calibratedCi95ub) +results <- rbind(results, result) + +results$label <- factor(results$label, + levels = c(""Our replication (calibrated)"",""Our replication (uncalibrated)"",""From literature"")) +# results$label <- factor(paste0(results$group, "" ("", results$estimate, "")""), +# levels = c(""Our replication (Calibrated)"",""Our replication (Uncalibrated)"",""From literature (Uncalibrated)"")) + +breaks <- c(0.25, 0.5, 1, 2, 4, 6, 8, 10) +theme <- element_text(colour = ""#000000"", size = 10) +themeRA <- element_text(colour = ""#000000"", size = 10, hjust = 1) + +ggplot(results, + aes(x = label, + y = rr, + ymin = lb, + ymax = ub), + environment = environment()) + + geom_hline(yintercept = breaks, colour = ""#AAAAAA"", lty = 1, size = 0.2) + + geom_hline(yintercept = 1, size = 0.5) + + geom_pointrange(shape = 23, color = rgb(0,0,0.2), fill = rgb(0,0,0.2), alpha = 0.5) + + coord_flip(ylim = c(0.25, 10)) + + scale_y_continuous(""Relative risk"", trans = ""log10"", breaks = breaks, labels = breaks) + + facet_grid(study~topic) + + theme(panel.grid.minor = element_blank(), + panel.background = element_rect(fill = ""#FAFAFA"", colour = NA), + panel.grid.major = element_line(colour = ""#EEEEEE""), + axis.ticks = element_blank(), + axis.title.y = element_blank(), + axis.text.y = themeRA, + axis.text.x = theme, + legend.key = element_blank(), + strip.text.x = theme, + strip.background = element_blank(), + legend.position = ""none"") +ggsave(file.path(paperFolder, ""Tata.png""), width = 6, height = 2.2, dpi = 300) + + +# Dabigatran vs warfarin for GI bleed ------------------------------------- + +results <- data.frame() + +result <- data.frame(group = ""From literature"", + topic = ""Dabigatran, warfarin and GI bleed"", + study = ""Southworth"", + label = ""From literature"", + estimate = ""Uncalibrated"", + rr = 1.6 / 3.5, + lb = 1.6 / 3.5, + ub = 1.6 / 3.5) +results <- rbind(results, result) + +result <- data.frame(group = ""From literature"", + topic = ""Dabigatran, warfarin and GI bleed"", + study = ""Graham"", + label = ""From literature"", + estimate = ""Uncalibrated"", + rr = 1.28, + lb = 1.14, + ub = 1.44) +results <- rbind(results, result) + +cal <- read.csv(""S:/Temp/CiCalibration_Optum/Calibrated_Southworth_cohort_method.csv"") +cal <- cal[is.na(cal$trueLogRr), ] +result <- data.frame(group = ""Our replication"", + topic = ""Dabigatran, warfarin and GI bleed"", + study = ""Southworth"", + label = ""Our replication (uncalibrated)"", + estimate = ""Uncalibrated"", + rr = cal$rr, + lb = cal$ci95lb, + ub = cal$ci95ub) +results <- rbind(results, result) + +result <- data.frame(group = ""Our replication"", + topic = ""Dabigatran, warfarin and GI bleed"", + study = ""Southworth"", + label = ""Our replication (calibrated)"", + estimate = ""Calibrated"", + rr = cal$calibratedRr, + lb = cal$calibratedCi95lb, + ub = cal$calibratedCi95ub) +results <- rbind(results, result) + +cal <- read.csv(""S:/Temp/CiCalibration_Mdcr/Calibrated_Graham_cohort_method.csv"") +cal <- cal[is.na(cal$trueLogRr), ] +result <- data.frame(group = ""Our replication"", + topic = ""Dabigatran, warfarin and GI bleed"", + study = ""Graham"", + label = ""Our replication (uncalibrated)"", + estimate = ""Uncalibrated"", + rr = cal$rr, + lb = cal$ci95lb, + ub = cal$ci95ub) +results <- rbind(results, result) + +result <- data.frame(group = ""Our replication"", + topic = ""Dabigatran, warfarin and GI bleed"", + study = ""Graham"", + label = ""Our replication (calibrated)"", + estimate = ""Calibrated"", + rr = cal$calibratedRr, + lb = cal$calibratedCi95lb, + ub = cal$calibratedCi95ub) +results <- rbind(results, result) + +results$label <- factor(results$label, + levels = c(""Our replication (calibrated)"",""Our replication (uncalibrated)"",""From literature"")) +# results$label <- factor(paste0(results$group, "" ("", results$estimate, "")""), +# levels = c(""Our replication (Calibrated)"",""Our replication (Uncalibrated)"",""From literature (Uncalibrated)"")) + +breaks <- c(0.25, 0.5, 1, 2, 4, 6, 8, 10) +theme <- element_text(colour = ""#000000"", size = 10) +themeRA <- element_text(colour = ""#000000"", size = 10, hjust = 1) + +ggplot(results, + aes(x = label, + y = rr, + ymin = lb, + ymax = ub), + environment = environment()) + + geom_hline(yintercept = breaks, colour = ""#AAAAAA"", lty = 1, size = 0.2) + + geom_hline(yintercept = 1, size = 0.5) + + geom_pointrange(shape = 23, color = rgb(0,0,0.2), fill = rgb(0,0,0.2), alpha = 0.5) + + coord_flip(ylim = c(0.25, 10)) + + scale_y_continuous(""Relative risk"", trans = ""log10"", breaks = breaks, labels = breaks) + + facet_grid(study~topic) + + theme(panel.grid.minor = element_blank(), + panel.background = element_rect(fill = ""#FAFAFA"", colour = NA), + panel.grid.major = element_line(colour = ""#EEEEEE""), + axis.ticks = element_blank(), + axis.title.y = element_blank(), + axis.text.y = themeRA, + axis.text.x = theme, + legend.key = element_blank(), + strip.text.x = theme, + strip.background = element_blank(), + legend.position = ""none"") +ggsave(file.path(paperFolder, ""DabiWarfarin.png""), width = 6, height = 2.2, dpi = 300) + + + +# Person counts ----------------------------------------------------------- +library(ffbase) + +sccsData <- SelfControlledCaseSeries::loadSccsData(""S:/Temp/CiCalibration_Mdcd/sccsOutput/SccsData_l1"") +sum(sccsData$eras$conceptId == 14) +sccsEraData <- SelfControlledCaseSeries::loadSccsEraData(""S:/Temp/CiCalibration_Mdcd/sccsOutput/Analysis_1/SccsEraData_e11_o14"") +length(unique(sccsEraData$outcomes$stratumId[sccsEraData$outcomes$y == 1])) +strataId <- unique(sccsEraData$outcomes$stratumId[sccsEraData$outcomes$y == 1]) +x <- sccsData$cases[sccsData$cases$observationPeriodId %in% strataId, ] +same <- x$personId[x$personId %in% ccUnmatched$personId] +notSame <- ccUnmatched[!(ccUnmatched$personId %in% ff::as.ram(x$personId)) & ccUnmatched$isCase,] + +sccsData$cases[sccsData$cases$personId == 1306285,] +sccsData$eras[sccsData$eras$observationPeriodId == 95029,] +sccsEraData$outcomes[sccsEraData$outcomes$stratumId == 3148630, ] +sccsEraData$covariates[sccsEraData$covariates$stratumId == 3317610, ] +ccData$nestingCohorts[ccData$nestingCohorts$personId == 9337461, ] +ccData$cases[ccData$cases$nestingCohortId == 3148630, ] + +ccOm <- readRDS(""S:/Temp/CiCalibration_Mdcd/ccOutput/Analysis_1/model_e11_o14.rds"") + +ccData <- CaseControl::loadCaseData(""S:/Temp/CiCalibration_Mdcd/ccOutput/caseData_cd1"") +length(unique(ccData$cases$nestingCohortId[ccData$cases$outcomeId == 14])) + +cc <- readRDS(""S:/Temp/CiCalibration_Mdcd/ccOutput/caseControls_cd1_cc1_o14.rds"") +CaseControl::getAttritionTable(cc) +ccd <- readRDS(""S:/Temp/CiCalibration_Mdcd/ccOutput/ccd_cd1_cc1_o14_ed1_e11_ccd1.rds"") +CaseControl::computeMdrr(caseControlData = ccd) + +ccUnmatched <- CaseControl::selectControls(caseData = ccData, + outcomeId = 14, + firstOutcomeOnly = TRUE, + washoutPeriod = 180, + controlsPerCase = 6, + matchOnAge = TRUE, + ageCaliper = 1, + matchOnGender = TRUE, + matchOnProvider = FALSE, + matchOnCareSite = TRUE, + matchOnVisitDate = FALSE, + removedUnmatchedCases = FALSE, + minAge = 18) +sum(ccUnmatched$isCase) + + + +options(fftempdir = ""s:/fftemp"") +sccsData <- SelfControlledCaseSeries::loadSccsData(""S:/Temp/CiCalibration_Mdcd/sccsOutput/SccsData_l1"") +covarExposureOfInt <- SelfControlledCaseSeries::createCovariateSettings(label = ""Exposure of interest"", + includeCovariateIds = 12, + start = 0, + end = 0, + addExposedDaysToEnd = TRUE) + + +ageSettings <- SelfControlledCaseSeries::createAgeSettings(includeAge = TRUE, + ageKnots = 5, + minAge = 18) + +temp <- list(cases = sccsData$cases[sccsData$cases$personId == 1306285 | sccsData$cases$personId == 651320,], + eras = sccsData$eras[sccsData$eras$observationPeriodId == 95029 | sccsData$eras$observationPeriodId == 65,], + covariateRef = sccsData$covariateRef, + metaData = sccsData$metaData) + +z <- SelfControlledCaseSeries::createSccsEraData(sccsData = temp, + naivePeriod = 180, + firstOutcomeOnly = FALSE, + covariateSettings = covarExposureOfInt) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CiCalibration/extras/PrepareDataForEmpiricalCalibrationPackage.R",".R","1849","33","# Estimates from Southworth and Graham replications ------------------------------ + +mdcrFolder <- ""S:/Temp/CiCalibration_Mdcr"" +optumFolder <- ""S:/Temp/CiCalibration_Optum"" +packageFolder <- ""C:/Users/mschuemi/git/EmpiricalCalibration/data"" + +pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""CiCalibration"") +negativeControls <- read.csv(pathToCsv) +pathToCsv <- system.file(""settings"", ""CohortsToCreate.csv"", package = ""CiCalibration"") +cohortsToCreate <- read.csv(pathToCsv) +idToNames <- data.frame(outcomeId = c(negativeControls$conceptId, cohortsToCreate$cohortId), + outcomeName = c(as.character(negativeControls$name), as.character(cohortsToCreate$name))) +idToNames <- unique(idToNames) +estimates <- data.frame() + +calibratedFile <- file.path(optumFolder, ""Calibrated_Southworth_cohort_method.csv"") +calibrated <- read.csv(calibratedFile) +calibrated$outcomeId[!is.na(calibrated$oldOutcomeId)] <- calibrated$oldOutcomeId[!is.na(calibrated$oldOutcomeId)] +calibrated$study <- ""Southworth replication"" +calibrated <- merge(calibrated, idToNames) +calibrated <- calibrated[!is.na(calibrated$seLogRr), c(""outcomeName"", ""trueLogRr"", ""logRr"", ""seLogRr"")] +southworthReplication <- calibrated +save(southworthReplication, file = file.path(packageFolder, ""southworthReplication.rda"")) + +calibratedFile <- file.path(mdcrFolder, ""Calibrated_Graham_cohort_method.csv"") +calibrated <- read.csv(calibratedFile) +calibrated$outcomeId[!is.na(calibrated$oldOutcomeId)] <- calibrated$oldOutcomeId[!is.na(calibrated$oldOutcomeId)] +calibrated$study <- ""Graham replication"" +calibrated <- merge(calibrated, idToNames) +calibrated <- calibrated[!is.na(calibrated$seLogRr), c(""outcomeName"", ""trueLogRr"", ""logRr"", ""seLogRr"")] +grahamReplication <- calibrated +save(grahamReplication, file = file.path(packageFolder, ""grahamReplication.rda"")) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CiCalibration/extras/ExtractOutcomeModelsForSupportingInfo.R",".R","1566","39","mdcrFolder <- ""S:/Temp/CiCalibration_Mdcr"" +optumFolder <- ""S:/Temp/CiCalibration_Optum"" +mdcdFolder <- ""S:/Temp/CiCalibration_Mdcd"" + +paperFolder <- ""S:/temp/CiCalibrationPaper"" +if (!file.exists(paperFolder)) + dir.create(paperFolder, recursive = TRUE) + +pathToCsv <- system.file(""settings"", ""NegativeControls.csv"", package = ""CiCalibration"") +negativeControls <- read.csv(pathToCsv) + +getModels <- function(studyFolder, study) { + signalInjectionFolder <- file.path(studyFolder, ""signalInjection"") + ncs <- negativeControls[negativeControls$study == study, ] + models <- data.frame() + for (i in 1:nrow(ncs)) { + modelFolder <- file.path(signalInjectionFolder, paste0(""model_o"", ncs$conceptId[i])) + if (file.exists(modelFolder)) { + betas <- readRDS(file.path(modelFolder, ""betas.rds"")) + models <- rbind(models, + data.frame(Study = paste(study, ""replication""), + Outcome = as.character(ncs$name[i]), + Beta = betas$beta, + Covariate = as.character(betas$covariateName), + stringsAsFactors = FALSE)) + } + } + return(models) +} + +allModels <- data.frame() +allModels <- rbind(allModels, getModels(optumFolder, ""Southworth"")) +allModels <- rbind(allModels, getModels(mdcrFolder, ""Graham"")) +allModels <- rbind(allModels, getModels(mdcdFolder, ""Tata"")) +write.csv(allModels, file.path(paperFolder, ""OutcomeModels.csv""), row.names = FALSE) +# studyFolder <- optumFolder +# study <- ""Southworth"" + +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CiCalibration/extras/PaperExecutionCode.R",".R","2592","80","# @file PaperExecutionCode.R +# +# Copyright 2017 Observational Health Data Sciences and Informatics +# +# This file is part of CiCalibration +# +# 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. + +library(CiCalibration) +# options('fftempdir' = 'R:/fftemp') +options(fftempdir = ""S:/fftemp"") + +pw <- NULL +dbms <- ""pdw"" +user <- NULL +server <- ""JRDUSAPSCTL01"" +cdmDatabaseSchema <- ""CDM_CPRD_V510.dbo"" +oracleTempSchema <- NULL +workDatabaseSchema <- ""scratch.dbo"" +studyCohortTable <- ""mschuemie_ci_calibration_cohorts_cprd"" +port <- 17001 +workFolder <- ""S:/Temp/CiCalibration_Cprd"" +maxCores <- 30 +study <- ""Tata"" + +pw <- NULL +dbms <- ""pdw"" +user <- NULL +server <- ""JRDUSAPSCTL01"" +cdmDatabaseSchema <- ""CDM_TRUVEN_MDCR_V520.dbo"" +oracleTempSchema <- NULL +workDatabaseSchema <- ""scratch.dbo"" +studyCohortTable <- ""mschuemie_ci_calibration_cohorts_mdcr"" +port <- 17001 +workFolder <- ""S:/Temp/CiCalibration_Mdcr"" +maxCores <- 10 +study <- ""Graham"" + +pw <- NULL +dbms <- ""pdw"" +user <- NULL +server <- ""JRDUSAPSCTL01"" +cdmDatabaseSchema <- ""cdm_optum_extended_ses_V515.dbo"" +oracleTempSchema <- NULL +workDatabaseSchema <- ""scratch.dbo"" +studyCohortTable <- ""mschuemie_ci_calibration_cohorts_optum"" +port <- 17001 +workFolder <- ""S:/Temp/CiCalibration_Optum"" +maxCores <- 30 +study <- ""Southworth"" + +connectionDetails <- DatabaseConnector::createConnectionDetails(dbms = dbms, + server = server, + user = user, + password = pw, + port = port) + +execute(connectionDetails = connectionDetails, + cdmDatabaseSchema = cdmDatabaseSchema, + oracleTempSchema = oracleTempSchema, + workDatabaseSchema = workDatabaseSchema, + studyCohortTable = studyCohortTable, + study = study, + workFolder = workFolder, + createCohorts = FALSE, + injectSignals = FALSE, + runAnalyses = TRUE, + empiricalCalibration = TRUE, + maxCores = maxCores) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CiCalibration/extras/PowerCalculations.R",".R","615","10","cc <- readRDS(""S:/Temp/CiCalibration_Mdcd/ccOutput/caseControls_cd1_cc1_o14.rds"") +CaseControl::getAttritionTable(cc) +ccd <- readRDS(""S:/Temp/CiCalibration_Mdcd/ccOutput/ccd_cd1_cc1_o14_ed1_e11_ccd1.rds"") +CaseControl::computeMdrr(caseControlData = ccd) + + +sccsEraData <- SelfControlledCaseSeries::loadSccsEraData(""S:/Temp/CiCalibration_Mdcd/sccsOutput/Analysis_1/SccsEraData_e11_o14"") +length(unique(sccsEraData$outcomes$stratumId[sccsEraData$outcomes$y == 1])) +# Note: a handful of subjects drop out of the SCCS because they have no contrast. This can only happen when their observation time is shorter than a month. +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CiCalibration/extras/NegativeControlEvaluationForPaper.R",".R","11810","251","# @file NegativeControlEvaluationForPaper.R +# +# Copyright 2017 Observational Health Data Sciences and Informatics +# +# This file is part of CiCalibration +# +# 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. + +# Extract data from Sherlock ---------------------------------------------- + +library(DatabaseConnector) + +server <- ""awsafinva1134"" +schema <- ""clinicaltrials"" +user <- """" +password <- """" + +connectionDetails <- createConnectionDetails(dbms = ""sql server"", + user = user, + password = password, + server = server, + schema = schema) + +conn <- connect(connectionDetails) +sql <- ""SELECT ClinicalTrialsId, + EventTerm, + EventTermPTOmopConceptId, + ArmIntervention, + InterventionOmopConceptId, + AENumberOfParticipants, + AEOther, + AESerious +FROM SubAdverseEventV +WHERE InterventionalModel = 'Parallel Assignment' + AND Allocation = 'Randomized' +ORDER BY ClinicalTrialsId, + EventTerm, + ArmIntervention;"" + +data <- querySql(conn, sql) +write.csv(data, ""data.csv"", row.names = FALSE) + + +# Prepare datasets for serious and non-serious events --------------------- + +extractData <- function(data, type = ""nonserious"") { + data <- data[data$AENUMBEROFPARTICIPANTS >= 1,] + data <- data[data$EVENTTERMPTOMOPCONCEPTID != 10060933, ] # Total, other adverse events + placeboControlled <- data$CLINICALTRIALSID[data$INTERVENTIONOMOPCONCEPTID == 19047135] # Placebo + data <- data[data$CLINICALTRIALSID %in% placeboControlled, ] + placebo <- data[!is.na(data$INTERVENTIONOMOPCONCEPTID) & data$INTERVENTIONOMOPCONCEPTID == 19047135, c(""CLINICALTRIALSID"", ""EVENTTERMPTOMOPCONCEPTID"" ,""EVENTTERM"" ,""AENUMBEROFPARTICIPANTS"", ""AEOTHER"", ""AESERIOUS"")] + treatment <- data[is.na(data$INTERVENTIONOMOPCONCEPTID) | data$INTERVENTIONOMOPCONCEPTID != 19047135,c(""CLINICALTRIALSID"", ""EVENTTERMPTOMOPCONCEPTID"" ,""EVENTTERM"" ,""AENUMBEROFPARTICIPANTS"", ""AEOTHER"", ""AESERIOUS"", ""ARMINTERVENTION"", ""INTERVENTIONOMOPCONCEPTID"")] + colnames(placebo)[colnames(placebo) == ""AENUMBEROFPARTICIPANTS""] <- ""denominatorPlacebo"" + colnames(treatment)[colnames(treatment) == ""AENUMBEROFPARTICIPANTS""] <- ""denominatorTreatment"" + if (type == ""nonserious"") { + colnames(placebo)[colnames(placebo) == ""AEOTHER""] <- ""numeratorPlacebo"" + colnames(treatment)[colnames(treatment) == ""AEOTHER""] <- ""numeratorTreatment"" + placebo$AESERIOUS <- NULL + treatment$AESERIOUS <- NULL + } else { + colnames(placebo)[colnames(placebo) == ""AESERIOUS""] <- ""numeratorPlacebo"" + colnames(treatment)[colnames(treatment) == ""AESERIOUS""] <- ""numeratorTreatment"" + placebo$AEOTHER <- NULL + treatment$AEOTHER <- NULL + } + dataMerged <- merge(treatment, placebo) + dataMerged$numeratorTreatment[is.na(dataMerged$numeratorTreatment)] <- 0 + dataMerged$numeratorPlacebo[is.na(dataMerged$numeratorPlacebo)] <- 0 + + # Detect trials with more than 2 arms and eliminate them: + dataMerged$count <- 1 + counts <- aggregate(count ~ CLINICALTRIALSID + INTERVENTIONOMOPCONCEPTID + EVENTTERMPTOMOPCONCEPTID, dataMerged, sum) + counts <- counts[counts$count > 1, ] + dataMerged <- dataMerged[!(dataMerged$CLINICALTRIALSID %in% unique(counts$CLINICALTRIALSID)), ] + + computeRr <- function(x) { + outcome <- matrix(c(x[""denominatorPlacebo""], + x[""numeratorPlacebo""], + x[""denominatorTreatment""], + x[""numeratorTreatment""]), ncol = 2, byrow = TRUE) + test <- fisher.test(outcome) + result <- c(test$estimate, test$conf.int) + names(result) <- c(""or"", ""lb95ci"",""ub95ci"") + return(result) + } + result <- apply(dataMerged[, c(""denominatorPlacebo"", ""numeratorPlacebo"", ""denominatorTreatment"", ""numeratorTreatment"")], MARGIN = 1, computeRr) + result <- as.data.frame(t(result), row.names = 1:ncol(result)) + result <- cbind(result, dataMerged) + result$logRr <- log(result$or) + result$seLogRr <- (log(result$ub95ci) - log(result$lb95ci))/(2 * qnorm(0.975)) + result <- result[!is.na(result$seLogRr) & !is.infinite(result$seLogRr), ] + return(result) +} + +data <- read.csv(""data.csv"") + +nonSerious <- extractData(data, type = ""nonserious"") +write.csv(nonSerious, ""EstimatesNonSerious.csv"", row.names = FALSE) + +serious <- extractData(data, type = ""serious"") +write.csv(serious, ""EstimatesSerious.csv"", row.names = FALSE) + + +# Prepare exposure-outcome pairs for negative control status evaluation -------------------- + +estimatesNonSerious <- read.csv(""EstimatesNonSerious.csv"") +estimatesSerious <- read.csv(""EstimatesSerious.csv"") +exposureOutcomePairs <- rbind(data.frame(exposureId = estimatesNonSerious$INTERVENTIONOMOPCONCEPTID, + exposureName = estimatesNonSerious$ARMINTERVENTION, + outcomeId = estimatesNonSerious$EVENTTERMPTOMOPCONCEPTID, + outcomeName = estimatesNonSerious$EVENTTERM), + data.frame(exposureId = estimatesSerious$INTERVENTIONOMOPCONCEPTID, + exposureName = estimatesSerious$ARMINTERVENTION, + outcomeId = estimatesSerious$EVENTTERMPTOMOPCONCEPTID, + outcomeName = estimatesSerious$EVENTTERM)) +exposureOutcomePairs <- unique(exposureOutcomePairs) +exposureOutcomePairs <- exposureOutcomePairs[!is.na(exposureOutcomePairs$exposureId) & !is.na(exposureOutcomePairs$outcomeId), ] +exposureOutcomePairs <- exposureOutcomePairs[!grepl(""[,;]"", exposureOutcomePairs$exposureId) & !grepl(""[,;]"", exposureOutcomePairs$outcomeId), ] +exposureOutcomePairs <- exposureOutcomePairs[order(exposureOutcomePairs$exposureId, exposureOutcomePairs$outcomeId), ] +writeLines(paste0(nrow(exposureOutcomePairs), "" unique exposure-outcome pairs in "", length(unique(estimatesSerious$CLINICALTRIALSID)), "" trials"")) +write.csv(exposureOutcomePairs, ""ExposureOutcomePairsForEval.csv"", row.names = FALSE) + +# Load NC status generated elsewhere ------------------------------------- + +library(SqlRender) +library(DatabaseConnector) + +password <- NULL +dbms <- ""sql server"" +user <- NULL +server <- ""RNDUSRDHIT01"" +schema <- 'NCInvestigation.dbo' + +connectionDetails <- createConnectionDetails(dbms = dbms, + user = user, + password = password, + server = server, + schema = schema) + +conn <- connect(connectionDetails) + + +sql <- ""SELECT DISTINCT eo.exposureId, +eo.exposureName, +eo.outcomeId, +eo.outcomeName +INTO #eval_pairs_in_universe +FROM dbo.ExposureOutcomePairsForEval eo +INNER JOIN drug_universe +ON eo.exposureId = drug_universe.ingredient_concept_id +INNER JOIN temp_sena_vocab_map +ON eo.outcomeId = temp_sena_vocab_map.outcomeId +INNER JOIN condition_universe +ON temp_sena_vocab_map.concept_id = condition_universe.condition_concept_id"" + +executeSql(conn, sql) + +sql <- ""SELECT ep.exposureId, +ep.exposureName, +ep.outcomeId, +ep.outcomeName, +COUNT(*) AS concept_count, +MIN(nc_candidate) AS nc_candidate +FROM #eval_pairs_in_universe ep +LEFT JOIN ExposureOutcomePairsWithEvidenceBase eb +ON ep.exposureId = eb.exposureId AND ep.outcomeId = eb.outcomeId +WHERE prediction IS NOT NULL +GROUP BY ep.exposureId, +ep.exposureName, +ep.outcomeId, +ep.outcomeName"" + +d <- querySql(conn, sql) +dbDisconnect(conn) +write.csv(d, ""ExposureOutcomePairsNc.csv"", row.names = FALSE) + + +# Plot distribution for NCs ----------------------------------------------- +library(EmpiricalCalibration) +library(ggplot2) + +ncs <- read.csv(""ExposureOutcomePairsNc.csv"") +colnames(ncs)[colnames(ncs) == ""EXPOSUREID""] <- ""exposureId"" +colnames(ncs)[colnames(ncs) == ""OUTCOMEID""] <- ""outcomeId"" +exposureOutcomePairs <- read.csv(""ExposureOutcomePairsForEval.csv"") +m <- merge(ncs, exposureOutcomePairs) +writeLines(paste0(sum(m$NC_CANDIDATE), "" pairs qualified as negative controls"")) + + +# eo <- querySql(conn, ""SELECT * FROM dbo.ExposureOutcomePairsForEval"") +# colnames(eo)[colnames(eo) == ""EXPOSUREID""] <- ""exposureId"" +# colnames(eo)[colnames(eo) == ""OUTCOMEID""] <- ""outcomeId"" +# m <- merge(eo, exposureOutcomePairs[,c(""exposureId"", ""outcomeId"")]) +# u <- unique(m[,c(""exposureId"", ""outcomeId"")]) +# u <- unique(exposureOutcomePairs[,c(""exposureId"", ""outcomeId"")]) + +estimatesNonSerious <- read.csv(""EstimatesNonSerious.csv"") +ncs <- read.csv(""ExposureOutcomePairsNc.csv"") +ncs$INTERVENTIONOMOPCONCEPTID <- as.integer(as.character(ncs$EXPOSUREID)) +ncs$EVENTTERMPTOMOPCONCEPTID <- as.integer(as.character(ncs$OUTCOMEID)) +ncs$negativeControl <- ncs$NC_CANDIDATE +estimatesNonSerious$INTERVENTIONOMOPCONCEPTID <- as.integer(as.character(estimatesNonSerious$INTERVENTIONOMOPCONCEPTID)) +estimatesNonSerious$EVENTTERMPTOMOPCONCEPTID <- as.integer(as.character(estimatesNonSerious$EVENTTERMPTOMOPCONCEPTID)) +estimatesNonSerious <- estimatesNonSerious[!is.na(estimatesNonSerious$INTERVENTIONOMOPCONCEPTID) & !is.na(estimatesNonSerious$EVENTTERMPTOMOPCONCEPTID), ] +# nrow(unique(estimatesNonSerious[, c(""INTERVENTIONOMOPCONCEPTID"", ""EVENTTERMPTOMOPCONCEPTID"")])) +m <- merge(estimatesNonSerious, ncs[, c(""INTERVENTIONOMOPCONCEPTID"", ""EVENTTERMPTOMOPCONCEPTID"", ""negativeControl"")]) +# nrow(unique(m[, c(""INTERVENTIONOMOPCONCEPTID"", ""EVENTTERMPTOMOPCONCEPTID"")])) +writeLines(paste0(nrow(unique(m[m$negativeControl == 1, c(""INTERVENTIONOMOPCONCEPTID"", ""EVENTTERMPTOMOPCONCEPTID"")])), "" exposure-outcome pairs qualify as negative controls"")) +m <- m[m$negativeControl == 1,] +m$significant <- m$lb95ci > 1 | m$ub95ci < 1 +writeLines(paste0(nrow(m), "" estimates for non serious effects, "", sum(m$significant), "" ("", 100*sum(m$significant)/nrow(m), ""%) are significant"")) + +# plotCalibrationEffect(m$logRr, m$seLogRr) + + +null <- fitMcmcNull(m$logRr, m$seLogRr) +saveRDS(null, ""nonSeriousNcNull.rds"") + +plotCalibrationEffect(m$logRr, m$seLogRr, showCis = TRUE, null = null, xLabel = ""Odds ratio"") +ggsave(""nonSeriousNegativeControlsCali.png"", width = 6, height = 4.5, dpi = 400) + + +estimatesSerious <- read.csv(""EstimatesSerious.csv"") +ncs <- read.csv(""ExposureOutcomePairsNc.csv"") +ncs$INTERVENTIONOMOPCONCEPTID <- as.integer(as.character(ncs$EXPOSUREID)) +ncs$EVENTTERMPTOMOPCONCEPTID <- as.integer(as.character(ncs$OUTCOMEID)) +ncs$negativeControl <- ncs$NC_CANDIDATE +estimatesSerious$INTERVENTIONOMOPCONCEPTID <- as.integer(as.character(estimatesSerious$INTERVENTIONOMOPCONCEPTID)) +estimatesSerious$EVENTTERMPTOMOPCONCEPTID <- as.integer(as.character(estimatesSerious$EVENTTERMPTOMOPCONCEPTID)) +estimatesSerious <- estimatesSerious[!is.na(estimatesSerious$INTERVENTIONOMOPCONCEPTID) & !is.na(estimatesSerious$EVENTTERMPTOMOPCONCEPTID), ] +m <- merge(estimatesSerious, ncs[, c(""INTERVENTIONOMOPCONCEPTID"", ""EVENTTERMPTOMOPCONCEPTID"", ""negativeControl"")]) +m <- m[m$negativeControl == 1,] +m$significant <- m$lb95ci > 1 | m$ub95ci < 1 +writeLines(paste0(nrow(m), "" estimates for serious effects, "", sum(m$significant), "" ("", 100*sum(m$significant)/nrow(m), ""%) are significant"")) + +null <- fitMcmcNull(m$logRr, m$seLogRr) +saveRDS(null, ""seriousNcNull.rds"") + +plotCalibrationEffect(m$logRr, m$seLogRr, showCis = TRUE, null = null, xLabel = ""Odds ratio"") +ggsave(""seriousNegativeControlsCali.png"", width = 6, height = 4.5, dpi = 400) +","R" +"Pharmacogenetics","OHDSI/StudyProtocols","CiCalibration/tests/testthat.R",".R","82","5","library(testthat) +library(CelecoxibVsNsNSAIDs) + +test_check(""CelecoxibVsNsNSAIDs"") +","R" +"Pharmacogenetics","Helix-Research-Lab/PGxPOP","bin/PGxPOP.py",".py","12659","315",""""""" +Greg McInnes and Adam Lavertu +Altman Lab +gmcinnes@stanford.edu, alavertu@stanford.edu +"""""" + +import os +import argparse + +# import multiprocessing as mp +import numpy as np + +from timeit import default_timer as timer +from datetime import timedelta + +import Gene +from DawgToys import * +from GenotypeParser import GenotypeParser +from DiplotypeCaller import * +from ExceptionCaller import ExceptionCaller +from Phenotype import Phenotype +from RareVariantCaller import RareVariantCaller + +''' +Main class for calling PGxPOP +Inputs + - vcf: Path to VCF file + - gene: Gene name to run on. If None, all genes will be run. + - phased: Whether the data is phased + - build: the genome build used (hg19 and grch38 supported) + - output: path to output file + - debug: print lots of debugging info + - batch_mode: a paralleled version that may not work +''' +class PGxPOP(object): + def __init__(self, vcf, gene, phased=False, build='grch38', output=None, + debug=False, batch_mode=False, extra_variants=False): + self.vcf = vcf + self.gene = gene + self.phased = phased + self.build = build + self.debug = debug + self.batch_mode = batch_mode + self.output = output + self.extra_variants = extra_variants + + def run(self): + # Get the genes we want to run on + genes = self.get_genes() + + all_results = [] + # For each gene + for g in genes: + results = self.process_gene(g) + all_results = all_results + results + + # Print results to file + self.print_results(all_results) + + def process_gene(self, g): + if self.debug: + print(""Processing %s"" % g) + # Get the gene object containing all the star allele information + gene = self.get_gene(g) + # Get matrices of genotype calls for each sample in the VCF + gt_matrices = self.get_gt_matrices(gene) + # Call diplotypes from gene matrices + diplotypes, sample_variants, uncallable = self.get_calls(gene, gt_matrices) + # Fetch coding variants outside of star alleles + if self.extra_variants: + rv_caller = RareVariantCaller(vcf=self.vcf, gene=gene, build=self.build, debug=self.debug) + extra_variants = rv_caller.run() + else: + extra_variants = None + # Map diplotypes to phenotypes + phenotypes = self.get_phenotypes(gene, diplotypes, sample_variants, uncallable, extra_variants) + + return phenotypes + + ''' + This function is currently deprecated. It is possible to create an exceptions file that will override the + diplotype calls and look for a single variant to determine phenotype. + ''' + def get_exception_file(self, g): + definition_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), ""../definition/alleles/"") + filename = ""%s_exceptions.json"" % g + if os.path.exists(os.path.join(definition_dir, filename)): + exception_file = os.path.join(definition_dir, filename) + return(exception_file) + else: + return(False) + + ''' + Check if the requested gene is supported. If no gene is provided, return all supported genes. + ''' + def get_genes(self): + genes = ['CFTR', 'CYP2C9', 'CYP2D6', 'CYP4F2', 'IFNL3', 'TPMT', 'VKORC1', + 'CYP2C19', 'CYP3A5', 'DPYD', 'SLCO1B1', 'UGT1A1', 'CYP2B6', 'NUDT15'] + + + if self.gene == 'all': + return genes + + if not self.gene in genes: + print(""Selected gene not available. Please choose from list:"") + print("","".join(genes)) + exit(1) + + return [self.gene] + + ''' + Create a gene object containing star allele variant data + ''' + def get_gene(self, g): + # Get the definition file + gene_definition = get_definition_file(g) + gene = Gene.Gene(gene_definition, build=self.build, debug=self.debug) + return gene + + ''' + Fetch genotype matrices from the VCF for a given gene. + ''' + def get_gt_matrices(self, gene): + if self.debug: + print(""Extracting genotype matrices"") + + extraction_start_time = timer() + gp = GenotypeParser(self.vcf, gene, debug=self.debug) + gt_matrices = gp.haplotype_matrices(batch_mode=self.batch_mode) + extraction_end_time = timer() + + if self.debug: + print(""Genotype extraction finished"") + print(""Execution time: %s"" % timedelta(seconds=extraction_end_time - extraction_start_time)) + + return gt_matrices + + ''' + Determine diplotypes for each sample in the gt_matrices. + ''' + def get_calls(self, gene, gt_matrices): + + g = gene.name + + if self.debug: + print(""Calling diplotypes"") + print(""Checking for exception file"") + gene_exceptions = self.get_exception_file(g) + + if gene_exceptions: + ec = ExceptionCaller(gene_exceptions, gene, is_phased=self.phased) + ec_override = ec.override + if self.debug: + print(""Exception file found"") + else: + ec_override = False + if self.debug: + print(""No exception file found"") + + diplotype_caller_start_time = timer() + + sample_variants = {} + uncallable_alleles = {} + + if ec_override: + if self.debug: + print(""Exception override, calling with ExceptionCaller"") + sample_ids = get_vcf_subject_ids(self.vcf) + sample_calls, sample_variants = ec.call_samples(sample_ids, gt_matrices) + + else: + dipCal = DiplotypeCaller(gene, is_phased=self.phased) + sample_ids = get_vcf_subject_ids(self.vcf) + sample_calls = {} + for gt_mat, phase_matrix, sample_vars, variant_list, uncalled in gt_matrices: + dipCal.variant_list = variant_list + for samp in range(gt_mat[0].shape[1]): + cd_call, uncallable = dipCal.call_diplotype([gt_mat[0][:, samp], gt_mat[1][:, samp]], uncalled[:,samp], phase_matrix[:,samp]) + + #cd_call = self.clean_up_call(cd_call) + + sample_calls[sample_ids[samp]] = cd_call + sample_variants.update(sample_vars) + uncallable_alleles[sample_ids[samp]] = uncallable + + diplotype_caller_end_time = timer() + + if self.debug: + print(""Diplotype calling finished"") + print(""Execution time: %s"" % timedelta(seconds=diplotype_caller_end_time - diplotype_caller_start_time)) + + for k, v in sample_calls.items(): + print(""%s: %s"" % (k, v)) + + return sample_calls, sample_variants, uncallable_alleles + + ''' + Map diplotypes to phenotypes + This function will create the final result dictionary that will be parsed for the output. So extra variables + are passed in that we want to appear in the output. + ''' + def get_phenotypes(self, gene, diplotypes, sample_variants, uncallable, extra_variants=None): + g = gene.name + + # Load phenotype file into object + phenotypes = Phenotype() + + results = [] + + for sample, diplotype in diplotypes.items(): + haps = split_genotype(diplotype) + haplotype_data = {} + for i in range(len(haps)): + h = haps[i] + h_function = phenotypes.get_haplotype_function(g, h) + h_presumptive = phenotypes.get_presumptive_haplotype_function(g, h) + + haplotype_data[""hap_%s"" % i] = h + haplotype_data[""hap_%s_function"" % i] = h_function + haplotype_data[""hap_%s_presumptive"" % i] = h_presumptive + + phenotype = phenotypes.get_diplotype_function(g, haps[0], haps[1]) + presumptive_phenotype = phenotypes.get_diplotype_function(g, haps[0], haps[1], presumptive=True) + activity_score = phenotypes.get_activity_score(g, haps[0], haps[1], presumptive=True) + #if phenotype != presumptive_phenotype: + # print(phenotype, presumptive_phenotype) + # exit() + + results.append({ + ""sample"": sample, + ""gene"": g, + ""diplotype"": diplotype, + ""hap_1"": haplotype_data[""hap_0""], + ""hap_2"": haplotype_data[""hap_1""], + ""hap_1_function"": haplotype_data[""hap_0_function""], + ""hap_2_function"": haplotype_data[""hap_1_function""], + ""hap_1_presumptive_function"": haplotype_data[""hap_0_presumptive""], + ""hap_2_presumptive_function"": haplotype_data[""hap_1_presumptive""], + ""hap_1_variants"": sample_variants[sample][0], + ""hap_2_variants"": sample_variants[sample][1], + ""phenotype"": phenotype, + ""phenotype_presumptive"": presumptive_phenotype, + ""activity_score"": activity_score, + ""uncallable"": "";"".join(x.split(""%"")[0] for x in uncallable[sample]), + ""extra_variants"": None if extra_variants is None else "";"".join( + x.split(""%"")[0] for x in extra_variants[sample]) + }) + + return results + + ''' + Print the results to the specified file + ''' + def print_results(self, results): + f = open(self.output, ""w"") + f.write(""sample_id,gene,diplotype,hap_1,hap_2,hap_1_function,hap_2_function,hap_1_variants,hap_2_variants,"" + ""phenotype,hap_1_presumptive,hap_2_presumptive,phenotype_presumptive,activity_score,uncallable,extra_variants\n"") + for r in results: + if self.debug: + print(""%s,%s,%s,%s,%s,%s,%s,%s,%s,%s"" % (r[""sample""], r[""gene""], r[""diplotype""], r[""hap_1""], r[""hap_2""], + r[""hap_1_function""], r[""hap_2_function""], "";"".join(r[""hap_1_variants""]), + "";"".join(r[""hap_2_variants""]), r[""phenotype""])) + + f.write(f""{r['sample']},{r['gene']},{r['diplotype']},{r['hap_1']},{r['hap_2']},{r['hap_1_function']},"" + f""{r['hap_2_function']},{';'.join(r['hap_1_variants'])},{';'.join(r['hap_2_variants'])},"" + f""{r['phenotype']},{r['hap_1_presumptive_function']},{r['hap_2_presumptive_function']},"" + f""{r['phenotype_presumptive']},{r['activity_score']},{r['uncallable']},{r['extra_variants']}\n"") + + + +"""""" +Parse the command line +"""""" +def parse_command_line(): + welcome_message() + parser = argparse.ArgumentParser( + description = 'CityDawg determines star allele haplotypes for samples in a VCF file and outputs predicted ' + 'pharmacogenetic phenotypes.') + parser.add_argument(""-f"", ""--vcf"", help=""Input VCF"") + parser.add_argument(""-g"", ""--gene"", default='all', help=""Gene to run. Select from list. Run all by default.\n"" + ""CFTR, CYP2C9, CYP2D6, CYP4F2, IFNL3, TPMT, VKORC1, "" + ""CYP2C19, CYP3A5, DPYD, SLCO1B1, UGT1A1, CYP2B6, NUDT15"") + parser.add_argument(""--phased"", action='store_true', default=False, help=""Data is phased. Will try to determine phasing status "" + ""from VCF by default."") + parser.add_argument(""--build"", default='grch38', help=""Select build genome reference. By default PGxPOP assumes "" + ""grch38. Supported: grch38, hg19, hg18, hg17, etc."") + parser.add_argument(""--extra_variants"", action='store_true', default=False, help=""Check for rare variants in coding regions"") + parser.add_argument(""-d"", ""--debug"", action='store_true', default=False, + help=""Output debugging messages. May be very verbose."") + parser.add_argument(""-b"", ""--batch"", action='store_true', default=False, + help=""Fragment into batched sample runs. Suggested for runs with more than 10k samples."") + parser.add_argument(""-o"", ""--output"", default=""pgxpop_results.txt"", help=""Output file"") + options = parser.parse_args() + return options + + +"""""" +Main +"""""" +if __name__ == ""__main__"": + options = parse_command_line() + if options.vcf is None: + print('ERROR: Please specify a vcf path\nFor help run: python PGxPOP.py -h') + exit() + cd = PGxPOP(vcf=options.vcf, gene=options.gene, phased=options.phased, build=options.build, debug=options.debug, + batch_mode=options.batch, output=options.output, extra_variants=options.extra_variants) + + cd.run() + + + + + + +","Python" +"Pharmacogenetics","Helix-Research-Lab/PGxPOP","bin/gt_extractor.py",".py","6445","187",""""""" +Greg McInes +Altman Lab +gmcinnes@stanford.edu +"""""" + + +import sys +import argparse +from DawgToys import fetch_genotypes_2, fetch_genotype_records, get_vcf_subject_ids, parse_vcf_line, split_genotype + +class GTExtractor(object): + def __init__(self, file, chromosome, position, subject=None, carriers_only=False, homs_only=False, debug=False, + list=None): + self.debug = debug + self.file = file + self.chr = chromosome + self.position = position + self.subject = subject + self.carriers_only = carriers_only + self.homs_only = homs_only + self.list = list + + self.run() + + def run(self): + # Get the subjects + subjects = get_vcf_subject_ids(self.file) + + if self.subject is not None: + if not self.subject in subjects: + print(""Subject not found in VCF"") + exit(1) + + if self.list is not None: + # iterate over the list, which should look just like a VCF + with open(self.list) as f: + for line in f: + if line.startswith(""#""): + continue + vcf = parse_vcf_line(line) + chr = vcf.chrom + pos = vcf.pos + ref = vcf.ref + alt = vcf.alt + + # if you want to pull something out of the INFO to include + extras = { + ""AF"": vcf.info['AF'], + #""Gene"": vcf.info['Gene.refGene'], + ""Group"": ""deleterious"", + ""impact"": vcf.info[""impact""], + ""high_impact"": vcf.info[""highimpact""], + ""Gene"": vcf.info[""gene""] + + } + + self.process_variant(chr, pos, subjects, vcf_row=vcf, extras=extras) + else: + self.process_variant(self.chr, self.position, subjects) + + + def process_variant(self, chr, position, subjects, ref=None, alt=None, extras=None, vcf_row=None): + # Extract the variant data + + if vcf_row is not None: + #vcf_row.print_row(minimal=True) + variant = fetch_genotypes_2(self.file, vcf_row) + else: + variant = fetch_genotype_records(self.file, chr, position) + + if variant is None or variant.alt == ""."": + #print(""no variant found"") + return + + + + #variant.print_row(minimal=True) + + if vcf_row is not None: + if variant.ref != vcf_row.ref: + print(""REF DIDN'T MATCH"") + print(vcf_row.ref, variant.ref) + return + if vcf_row.alt not in variant.alts(): + print(""ALTS DIDN'T MATCH"") + print(vcf_row.alt, variant.alts()) + #ariant.print_row() + #exit() + return + + if variant is None: + #print(""Position not found in VCF: %s:%s"" % (chr, position), file=sys.stderr) + return + #exit(1) + + + alt_index = 1 + if vcf_row is not None: + if not variant.ref == vcf_row.ref: + #print(f""Wrong reference! {ref}"", file=sys.stderr) + return + if not vcf_row.alt in variant.alts(): + #print(""Wrong alt!"", file=sys.stderr) + #print(vcf_row.alt, variant.alts()) + return + alts = variant.alts() + #print(alts) + if len(alts) > 1: + for i in range(len(alts)): + if alts[i] == vcf_row.alt: + #print(""Found alt!"") + #print(alts[i], vcf_row.alt) + alt_index = i + 1 + + + #print(alt_index) + + # Get the resultw + + # If a subject is provided, just print that one + if self.subject is not None: + index = subjects.index(self.subject) + print(""%s: %s"" % (self.subject, variant.calls[index])) + return + + # If no subject is given, print all the subjects + for i in range(len(subjects)): + if self.carriers_only is True: + gt = split_genotype(variant.calls[i]) + if not str(alt_index) in gt: + continue + + elif self.homs_only is True: + gt = split_genotype(variant.calls[i]) + if not gt[0] in ['1', '2'] and not gt[1] in ['1', '2']: + continue + #else: + # print(""%s: %s"" % (subjects[i], variant.calls[i])) + + gt = variant.calls[i].split("":"")[0] + ac = sum(int(x) for x in split_genotype(variant.calls[i])) / alt_index + + + if extras: + values = [] + for k in extras.keys(): + values.append(extras[k]) + + print(""%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s"" % (subjects[i], chr, position, vcf_row.ref, vcf_row.alt, gt, ac, ""\t"".join(values))) + else: + print(""%s\t%s\t%s\t%s\t%s"" % (subjects[i], chr, position, gt, ac)) + +"""""" +Parse the command line +"""""" +def parse_command_line(): + parser = argparse.ArgumentParser( + description = 'Extract and print genotypes for subjects at a specific position in a VCF') + parser.add_argument(""-f"", ""--vcf"", help=""Input"") + parser.add_argument(""-c"", ""--chr"", help=""Chromosome"") + parser.add_argument(""-p"", ""--position"", type=int, help=""Position"") + parser.add_argument('-l', ""--list"", help=""List of variants to query"") + parser.add_argument(""-s"", ""--subject"", help=""Subject ID"") + parser.add_argument(""--carriers"", action='store_true', help=""Return only carriers of an alternate allele"") + parser.add_argument(""--homo"", action='store_true', help=""Return only subjects homozygous for the alternate allele"") + parser.add_argument(""-d"", ""--debug"", action='store_true', default=False, + help=""Output debugging messages. May be very verbose."") + options = parser.parse_args() + return options + + +"""""" +Main +"""""" +if __name__ == ""__main__"": + options = parse_command_line() + GTExtractor(file=options.vcf, + chromosome=options.chr, + position=options.position, + subject=options.subject, + carriers_only=options.carriers, + homs_only=options.homo, + debug=options.debug, + list=options.list) + +","Python" +"Pharmacogenetics","Helix-Research-Lab/PGxPOP","bin/Gene.py",".py","2764","95","''' +Greg McInes +Altman Lab +gmcinnes@stanford.edu +''' + +import json +from Variant import Variant +from NamedAllele import NamedAllele +import numpy as np + +''' +Define the Gene object + +This class will be initiated with a Gene definition json and contain functions related to gene specific tasks. +''' +class Gene(object): + def __init__(self, json_file, build='grch38', debug=False): + + # Set global variables + self.data = None + self.build = build + self.debug = debug + + # Load gene information from JSON file + self._load_json(json_file) + + self.name = self.data['gene'] + self.variants = self.get_variants() + self.haplotypes = self.get_haplotypes() + + def _load_json(self, json_file): + with open(json_file) as f: + self.data = json.load(f) + f.close() + + def haplotype_matrix(self): + # contstruct a binary matrix with the alleles along the x axis and haplotypes on the y axis + # 0's indicate a ref allele and 1's an alternate + + all_hap_alleles = [] + star_index = [] + for h in self.haplotypes: + star_index.append(self.haplotypes[h].name) + all_hap_alleles.append(self.haplotypes[h].binary_alleles) + + hap_matrix = np.array(all_hap_alleles) + return(hap_matrix, star_index) + + def get_variants(self): + if self.debug: + print(""Formatting variants"") + if self.build != ""grch38"": + print(""Alternate build detected."") + variants = self.data['variants'] + alleles = self.data['variantAlleles'] + formatted_variants = {} + + index = 0 + for v in variants: + new_variant = Variant(v, alleles=[], index=index, build=self.build, debug=self.debug) + if self.debug: + new_variant.print_variant() + formatted_variants[new_variant.index] = new_variant + index += 1 + + return formatted_variants + + def get_haplotypes(self): + if self.debug: + print(""Formatting haplotypes"") + haplotypes = self.data['namedAlleles'] + stars = {} + + formatted_haplotypes = {} + + index = 0 + for h in haplotypes: + new_haplotype = NamedAllele(h, variants=self.variants, index=index, debug=self.debug) + star = new_haplotype.name + + if star not in stars.keys(): + stars[star] = 0 + else: + substar = f'{star}%{stars[star]}' + stars[star] += 1 + new_haplotype.name = substar + + if self.debug: + new_haplotype.print_haplotype() + formatted_haplotypes[new_haplotype.id] = new_haplotype + index += 1 + + return formatted_haplotypes +","Python" +"Pharmacogenetics","Helix-Research-Lab/PGxPOP","bin/NamedAllele.py",".py","3355","93","''' +Greg McInes +Altman Lab +gmcinnes@stanford.edu +''' + +''' +This object contains the data for star alleles. It contains lists for the alleles found as well as a function +to convert the alleles to a binary representation of their variants. +''' + +class NamedAllele(object): + def __init__(self, data, variants, index=0, debug=False): + + # Set global variables + self.debug = debug + self.name = None + self.id = None + self.function = None + self.alleles = None + self.population_frequency = None + self.index = index + self.variants = variants + self.binary_alleles = None + self.key_list = None + + self._setup(data) + + def _setup(self, data): + self.name = data[""name""] + self.id = data[""id""] + self.alleles = data[""alleles""] + self.populationFrequency = data[""populationFrequency""] + + self._alleles_to_binary() + + def _alleles_to_binary(self): + self.binary_alleles = [] + self.key_list = [] + + # We'll create a binary matrix by iterating over the variants + # Variants with multiple alternates will get multiple columns + for v in range(len(self.variants)): + # Get the variant ref and alts + variant = self.variants[v] + ref = variant.ref + alts = variant.alt + + # If there are multiple alts iterate over them and check if the listed allele matches the alt + for a in alts: + # If it matches the ref, just add a 0 + if self.alleles is None: + # No allele listed + self.binary_alleles.append(0) + elif self.alleles[v] == ref: + # Matches the reference + self.binary_alleles.append(0) + elif self.alleles[v] == a: + # Matches the listed alternate + self.binary_alleles.append(1) + + # If it is an INDEL we have to do this differently + # I am going to set all reference INDELs to ""null"" in the definition files + # That way, if it is an indel and not null, then it must be a 1 + elif variant.type in [""INS"", ""DEL""]: + if not self.alleles[v]: + # it's an indel loci but a null value was listed + self.binary_alleles.append(0) + else: + # Something was there, assuming alt allele + self.binary_alleles.append(1) + + # Null values indicate a ref call + elif not self.alleles[v]: + self.binary_alleles.append(0) + + else: + # No match, just make it a zero + if self.debug: + print(""NO MATCH FOUND!"") + variant.print_variant() + print(variant.alleles) + print(alts) + print(self.alleles[v]) + print(""Current alt: %s"" % a) + self.binary_alleles.append(0) + + # Add a variant key of the alt for every column added + self.key_list.append(""%s_%s"" % (v, a)) + + def print_haplotype(self): + print(""%s %s %s"" % (self.name, self.id, self.function)) +","Python" +"Pharmacogenetics","Helix-Research-Lab/PGxPOP","bin/definition_cleaner.py",".py","12834","393",""""""" +Greg McInes +Altman Lab +gmcinnes@stanford.edu +"""""" + +# This script will make any necessary changes to the allele definition files. + +# Convert all INDELs to null in the reference sequence +# Split apart the TA repeat in UGT1A1 +# Add known synonyms +# Add hg19 position + +''' +***FIXED*** +CYP2D6 almost needs it's own script +Due to the whole gene deletion (*5), every single variant is of type deletion in the file, which doesn't make sense +and breaks things on our end. These need to be changed to the actual type of variant they represent. +*6 has an extra variant in it S486T +*3 extra: N166D +*********** + +***FIXED*** +Additionally, for *4 IUPAC nucleotide representations are used, perhaps overused. For instance an R is used for a +purine. This is not handled at the moment, so I manually changed all them to the nucleotide in the PharmVar definition. +*********** + +***FIXED*** +CYP2B6, I changed the multiallelic sites to be single alts. This isn't a problem in the UKBB, but the other +alts are common enough that this should be fixed. + +g.40991390C>A/T to g.40991390C>T +g.41004406G>A/C/T to g.41004406G>T +g.41010006G>T/A/C to g.41010006G>C +*********** + +Add allele flips for +CYP2C19: rs3758581 +CYP3A5: rs776746 + +# CFTR hg19 synonym - note that this synonym is not in hg38 +# 117199645: 117199644 +''' + +import json +import argparse +from pyliftover import LiftOver +from Gene import Gene +from DawgToys import iupac_nt +import copy +import myvariant + +# todo put this in a file +synonyms = { + ""CYP2C9"": {94949282: [94949281]}, + ""CYP2D6"": {42129084: [42129083], + 42128249: [42128248], + 42128242: [42128241], + 42128218: [42128211], + 42128201: [42128200], + 42128174: [42128173], + 42127963: [42127962], + 42127846: [42127845]} +} + +# CFTR hg19 synonym +# 117199645: 117199644 + +class DefinitionCleaner(object): + def __init__(self, file, debug=False): + self.file = file + self.debug = debug + + # Load the data into a global object + self.data = self.get_data() + self.gene = Gene(self.file, debug=self.debug) + + self.run() + + def run(self): + + # Get ref and alts from MyVariant + #self.update_variants() + + # Add synonynms + self.add_synonyms() + + # Expand out the wobble nucleotides + self.dewobbler() + + # Fix all the INDELs + self.update_indels() + + # Add hg19 position + self.add_alternate_build() + + # Handle special cases + self.special_cases() + + # print the output + print(json.dumps(self.data, indent=2)) + + def special_cases(self): + + # todo + # Expand the INDEL in UGT1A1 into 3 different variants + + # For CYP3A5, *3 needs to have the R and Y changed to G and T + + if self.data[""gene""] == ""CYP2D6"": + self.CYP2D6() + + pass + + def dewobbler(self): + # go through each named allele + new_alleles = [] + + for allele in self.data[""namedAlleles""]: + cyp2d6_exon_9_conv = False + cyp2d6_exon_9_conv_copy = None + if self.data['gene'] == ""CYP2D6"" and allele[""name""] == ""*4"": + cyp2d6_exon_9_conv = True + + branched_alleles = [[]] + #print(allele['name']) + for v in range(len(allele['alleles'])): + + + #print(""Current variant: %s"" % v) + expanded = iupac_nt(allele['alleles'][v]) + + + + #print(""Expanded: %s"" % expanded) + if len(expanded) > 1: + + # create a copy of the original for safe keeping + if cyp2d6_exon_9_conv is True and cyp2d6_exon_9_conv_copy is None: + # check which variant we're at + position = self.data['variants'][v]['position'] + if position == 42126663: + # We're in the conversion. Stop splitting. + #print(""We're in the conversion!"") + cyp2d6_exon_9_conv_copy = copy.deepcopy(branched_alleles) + + if cyp2d6_exon_9_conv_copy is not None: + for i in range(len(branched_alleles)): + branched_alleles[i].append(expanded[0]) + for i in range(len(cyp2d6_exon_9_conv_copy)): + cyp2d6_exon_9_conv_copy[i].append(expanded[1]) + + else: + new_branches = [] + for nt in expanded: + + # create a new copy of all branches and append the new variant + new_branch = copy.deepcopy(branched_alleles) + + #print(""original: %s"" % branched_alleles) + #print(new_branch) + for b in range(len(new_branch)): + new_branch[b].append(nt) + #print(new_branch) + + new_branches = new_branches + new_branch + + branched_alleles = new_branches + + else: + for i in range(len(branched_alleles)): + branched_alleles[i].append(expanded[0]) + + if cyp2d6_exon_9_conv_copy is not None: + for i in range(len(cyp2d6_exon_9_conv_copy)): + cyp2d6_exon_9_conv_copy[i].append(expanded[0]) + + if cyp2d6_exon_9_conv_copy is not None: + branched_alleles = branched_alleles + cyp2d6_exon_9_conv_copy + + # add the new branches to namedAlleles + if len(branched_alleles) > 1: + #print(""Created %s branches"" % len(branched_alleles)) + for i in range(len(branched_alleles)): + new_allele = copy.deepcopy(allele) + new_allele['alleles'] = branched_alleles[i] + new_allele['id'] = new_allele['id'] + '.%s' % i + #print(new_allele) + new_alleles.append(new_allele) + + self.data[""namedAlleles""] = self.data[""namedAlleles""] + new_alleles + #print(self.data[""namedAlleles""]) + + + + + + def CYP2D6(self): + if self.debug: + print(""Fixing CYP2D6"") + + self.variant_splitter('rs72549356') + + # Fix all the types - no longer need to do this after ryan removed *5 + #self.fix_type() + + #exit() + #pass + + def variant_splitter(self, rsid): + # Find the variant in the variants + + index = None + + for i in range(len(self.data['variants'])): + variant = self.data['variants'][i] + if variant['rsid'] == rsid: + index = i + break + + if index is None: + print(""Variant not found in definition: %s"" % rsid) + exit(1) + + # Update the variant definition + variant = self.gene.variants[index] + alts = variant.alt + + if variant.type == ""INS"": + for i in range(len(alts)): + alts[i] = ""ins"" + alts[i] + + new_variants = [] + for alt in variant.alt: + new_variant = copy.deepcopy(self.data['variants'][index]) + + if variant.type == ""INS"": + + new_alt = new_variant['chromosomeHgvsName'].split('ins')[0] + alt + new_variant['chromosomeHgvsName'] = new_alt + + new_variants.append(new_variant) + + del self.data['variants'][index] + + for i in range(len(new_variants)): + + self.data['variants'].insert(index+i, new_variants[i]) + + #print(self.data['variants'][index]) + #print(self.data['variants'][index+1]) + + # fix variantAlleles + #print(self.data['variantAlleles'][index]) + del self.data['variantAlleles'][index] + for i in range(len(alts)): + new_alts = [alts[i], variant.ref] + + self.data['variantAlleles'].insert(index + i, new_alts) + + #print(self.data['variantAlleles'][index]) + #print(self.data['variantAlleles'][index+1]) + + # ok now go through all the named allele definitinos + for i in range(len(self.data['namedAlleles'])): + #print(self.data['namedAlleles'][i]['name']) + if self.data['namedAlleles'][i]['name'] == ""*1"": + # skip *1, just because + self.data['namedAlleles'][i]['alleles'].insert(index, None) + continue + + if self.data['namedAlleles'][i]['alleles'][index] is None: + #just add another one + self.data['namedAlleles'][i]['alleles'].insert(index, None) + + else: + found_alt = self.data['namedAlleles'][i]['alleles'][index] + + del self.data['namedAlleles'][i]['alleles'][index] + for j in range(len(alts)): + if found_alt == alts[j]: + #print('inserting %s' % found_alt) + self.data['namedAlleles'][i]['alleles'].insert(index+j, found_alt) + else: + self.data['namedAlleles'][i]['alleles'].insert(index+j, None) + + #print(self.data['namedAlleles'][i]['alleles'][index]) + #print(self.data['namedAlleles'][i]['alleles'][index+1]) + + #exit() + + #exit() + + + def fix_type(self): + for i in self.gene.variants: + print(self.data[""variants""][i][""type""]) + pass + + + def add_synonyms(self): + current_gene = self.data[""gene""] + if not current_gene in synonyms.keys(): + return + gene_syns = synonyms[current_gene] + for pos in gene_syns.keys(): + for i in self.gene.variants: + if self.gene.variants[i].position == pos: + self.data[""variants""][i][""synonyms""] = gene_syns[pos] + + def update_indels(self): + # Get the indices of all INDELs in the file + for i in self.gene.variants: + if self.gene.variants[i].type in [""INS"", ""DEL""]: + #self.gene.variants[i].print_variant() + # If an INDEL is identified update the index for the reference named allele + j = 0 + for n in self.data[""namedAlleles""]: + if n['name'] in [""*1"", ""Reference""]: + # Set the index of the INDEL to None + self.data[""namedAlleles""][j]['alleles'][i] = None + j += 1 + + def get_data(self): + with open(self.file) as json_file: + data = json.load(json_file) + return data + + def add_alternate_build(self): + # Don't forget to update the synonyms too + for i in self.gene.variants: + # lift the chromosome and position + chr = self.gene.variants[i].chromosome + pos = self.gene.variants[i].position + new_chr, new_pos = self.liftover(chr, pos) + + new_synonyms = [] + if ""synonyms"" in self.data[""variants""][i].keys(): + for s in self.data[""variants""][i][""synonyms""]: + new_chr, s_pos = self.liftover(chr, pos) + new_synonyms.append(s_pos) + + alt_build_info = { + 'build':'hg19', + 'chromosome': new_chr, + 'position': new_pos, + 'synonyms': new_synonyms + } + + self.data[""variants""][i][""hg19""] = alt_build_info + + def liftover(self, chromosome, position, build='hg19'): + + # todo + # Not sure what the failure mode of this tool is. Will probably need to write a try catch eventually + # Changing the chromosome and position messes up the key as well. Could probably fix that. But i don't have + # the ref and alt alleles on hand and I don't want to parse them out of chromosomeHgvsName. + + lo = LiftOver('hg38', build) + lifted = lo.convert_coordinate(chromosome, position) + + new_chromosome = lifted[0][0] + new_position = lifted[0][1] + + if self.debug: + print(""%s %s -> %s %s"" % (chromosome, position, new_chromosome, new_position)) + + return new_chromosome, new_position + + + + +"""""" +Parse the command line +"""""" +def parse_command_line(): + parser = argparse.ArgumentParser( + description = 'This script will make any necessary changes to the allele definition files.') + parser.add_argument(""-f"", ""--file"", help=""Input"") + parser.add_argument(""-d"", ""--debug"", action='store_true', default=False, + help=""Output debugging messages. May be very verbose."") + options = parser.parse_args() + return options + + +"""""" +Main +"""""" +if __name__ == ""__main__"": + options = parse_command_line() + DefinitionCleaner(options.file, options.debug) + +","Python" +"Pharmacogenetics","Helix-Research-Lab/PGxPOP","bin/Variant.py",".py","4433","136","import json +from DawgToys import clean_chr, iupac_nt + +''' +Define the Variant object +''' +class Variant(object): + def __init__(self, data, alleles, index=0, build='grch38', debug=False): + + # Initialize global variables + self.clean_chromosome = None + self.chromosome = None + self.position = None + self.rsid = None + self.chromosomeHgvsName = None + self.geneHgvsName = None + self.proteinNote = None + self.resourceNote = None + self.type = None + self.referenceRepeat = None + self.key = None + self.alleles = alleles + self.ref = None + self.alt = [] + self.flipped = False + self.synonyms = [] + self.index = index + self.build = build.lower() + self.debug = debug + + self._setup(data) + + def _setup(self, data): + + self.chromosome = data['chromosome'] + self.clean_chromosome = clean_chr(self.chromosome) + self.position = data['position'] + self.rsid = data['rsid'] + self.chromosomeHgvsName = data['chromosomeHgvsName'] + self.geneHgvsName = data['geneHgvsName'] + self.proteinNote = data['proteinNote'] + self.resourceNote = data['resourceNote'] + self.type = data['type'] + self.referenceRepeat = data['referenceRepeat'] + self.key = ""%s.%s"" % (self.chromosome, self.chromosomeHgvsName) + self.keys = self.chromosomeHgvsName.split(""; "") + + if ""synonyms"" in data.keys(): + self.synonyms = data[""synonyms""] + + self._parse_alleles() + + if self.build != 'grch38': + if self.debug: + print(""Alternate genome build found. Converting positions."") + if self.build not in ['hg19']: + print(""Build not stored. Coordinate conversion may take a while: %s"" % self.build) + self.liftover() + else: + self.chromosome = data[self.build]['chromosome'] + self.position = data[self.build]['position'] + self.synonyms = data[self.build]['synonyms'] + + if ""ref"" in data[self.build].keys(): + + self.ref = data[self.build]['ref'] + self.alt = data[self.build]['alt'] + self.flipped = True + + def _parse_alleles(self): + if self.type == ""SNP"": + hgvs = self.chromosomeHgvsName.split("";"") + alt_set = set() + for i in hgvs: + i = i.strip() + + fields = i.split('>') + ref = fields[0][-1] + + alt = fields[1].split('/') + + for a in alt: + all_alts = iupac_nt(a) + for new_alt in all_alts: + alt_set.add(new_alt) + + self.alt = list(alt_set) + + if self.ref != ref: + self.ref = ref + + return + + if self.type ==""DEL"": + hgvs = self.chromosomeHgvsName.split("";"") + for i in hgvs: + i = i.strip() + ref = i.split('del')[1] + if self.ref != ref: + self.ref = ref + self.alt.append(""del"" + ref) + return + + if self.type ==""INS"": + hgvs = self.chromosomeHgvsName.split("";"") + for i in hgvs: + i = i.strip() + alts = i.split('/') + for a in alts: + alt = a.split('ins')[1] + self.alt.append(alt) + + self.ref = ""ins"" + return + + print(""Allele parsing of %s not yet supported"" % self.type) + print(self.chromosomeHgvsName) + exit() + + def liftover(self): + + # todo + # Not sure what the failure mode of this tool is. Will probably need to write a try catch eventually + # Changing the chromosome and position messes up the key as well. Could probably fix that. But i don't have + # the ref and alt alleles on hand and I don't want to parse them out of chromosomeHgvsName. + + from pyliftover import LiftOver + lo = LiftOver('hg38', self.build) + lifted = lo.convert_coordinate(self.chromosome, self.position) + + self.chromosome = lifted[0][0] + self.position = lifted[0][1] + + def print_variant(self): + print(""%s %s %s %s %s %s"" % (self.key, self.chromosome, self.position, self.rsid, self.ref, self.alt)) +","Python" +"Pharmacogenetics","Helix-Research-Lab/PGxPOP","bin/GenotypeParser.py",".py","9989","229","''' +Greg McInes +Altman Lab +gmcinnes@stanford.edu +''' + +''' +This script creates matrices of variant calls from a VCF for a gene region. The output is binary matrices where each + column is a variant that is included in the haplotype definition and each row is a sample. Two matrices are output, + one for each strand. +''' + +import numpy as np +from DawgToys import parse_vcf_line, get_vcf_subject_ids, split_genotype, vcf_is_phased, fetch_genotypes, is_gt_phased + +class GenotypeParser(object): + def __init__(self, vcf, gene, debug=False): + # Given a VCF and a Gene definition extract all the necessary genotypes and construct haplotype matrices + self.vcf = vcf + self.vcf_header = get_vcf_subject_ids(vcf) + self.gene = gene + self.phase_matrix = None + self.debug = debug + self.is_phased = False + self.sample_variants = {} + self.called = [] + self.variant_list = [] + + ''' + Find the index of a sample in the VCF + ''' + def get_sample_index(self, sample_id): + sample_index = [x for x, i in enumerate(self.vcf_header) if i == sample_id][0] + return sample_index + + ''' + Create the matrices + ''' + def haplotype_matrices(self, batch_mode=False): + + # Get the subjects from the file that we will be operating on + subjects = get_vcf_subject_ids(self.vcf) + + # Define some defaults to output in the case where no variant is identified + null_row = [] + null_phase_row = [] + for s in subjects: + null_row.append(0) + null_phase_row.append(1) + self.sample_variants[s] = [[], []] + + # Batch mode setup + if batch_mode: + samps_per_batch = int(np.floor(np.sqrt(len(subjects)))) + batches = [subjects[x:x+samps_per_batch] for x in range(0, len(subjects)-samps_per_batch)] + batches.append(subjects[len(subjects)-samps_per_batch:]) + else: + batches = [subjects] + + # Get all the variants that are defined for the gene we are working with + variants = self.gene.variants + + # All alleles identified + # This will be a list of lists. Where the inner lists represent the allele status for every variant in the + # definition table. Column represent subjects. Same order as in the VCF. Each added row should be of the + # same length as the number of samples. + # The left and right lists represent the left and right sides of the genotype + all_alleles = ([], []) + + # Initiate variables to store indices for phasing and no calls + phase_index = [] + no_call_index = [] + + # Batch processing + for batch in batches: + + # Iterate over all variants and process one by one + for v in range(len(variants)): + variant = variants[v] + + if self.debug: + variant.print_variant() + + # Extract the variant with tabix + genotypes = fetch_genotypes(self.vcf, variant) + + # if nothing found, make a row of all zeroes + # also save all the variants that were not callable + if genotypes is None: + if self.debug: + print(""Variant not found"") + # add the same number of null rows as there are genotypes + for i in range(len(variant.alt)): + all_alleles[0].append(null_row) + all_alleles[1].append(null_row) + phase_index.append(null_phase_row) + no_call_index.append(null_phase_row) + new_key = ""%s.g.%s%s>%s"" % (variant.chromosome, variant.position, variant.ref, variant.alt[i]) + self.variant_list.append(new_key) + continue + + # We found something, so add the variant to the called list + self.called.append((variant,v)) + + # Create a dictionary of alts to store genotypes in + alt_alleles = {} + n_alts = 0 + + # Since there can be multiallelic sites, we need to iterate over all possible alternates + # Create matrices for each alt found + for a in variant.alt: + alt_alleles[a] = [[], []] + new_key = ""%s.g.%s%s>%s"" % (variant.chromosome, variant.position, variant.ref, a) + self.variant_list.append(new_key) + n_alts += 1 + + # Dictionary of allele indices in the VCF. This will be the genotype (e.g. 0/1) that we look for + # For example most alternate alleles will get a value of 1 if they are the only alt. + alt_indices = {} + for a in variant.alt: + + # Get the index of the alt in the listed genotypes. + if genotypes.gt_index is not None: + alt_indices[a] = genotypes.gt_index + 1 + + elif a in genotypes.alts(): + index = genotypes.alts().index(a) + alt_indices[a] = index + 1 + + else: + alt_indices[a] = None + + # Loop over every genotype in the row, 1 for each subject + row_phasing_data = [] + row_no_call_data = [] + + for i in range(n_alts): + row_phasing_data.append([]) + row_no_call_data.append([]) + + for i, s in enumerate(batch): + # Get the genotype and split it into an array + gt = split_genotype(genotypes.calls[i]) + + # Update the no-call matrix. + if ""."" in gt: + if self.debug: + print('No call found: %s:%s' % (variant.key, genotypes.calls[i])) + for a in range(n_alts): + row_no_call_data[a].append(1) + else: + for a in range(n_alts): + row_no_call_data[a].append(0) + + # Check the phasing status first. Add a zero if it is phased, one if it's not + if is_gt_phased(genotypes.calls[i]): + for a in range(n_alts): + row_phasing_data[a].append(0) + else: + for a in range(n_alts): + row_phasing_data[a].append(1) + + # For each allele in the genotype (2) figure out if it is a ref call, or if it's an alt, which one. + #for g in range(len(gt)): # for some reason there are 0/0/0 genotypes in the pharmcat test files + for g in range(2): + allele = gt[g] + + if allele == '0': + for a in alt_alleles.keys(): + alt_alleles[a][g].append(0) + else: + # Determine which alterate allele + found = False + for alt in alt_indices: + if str(alt_indices[alt]) == allele: + if self.debug: + print(""Found alt call"") + + alt_alleles[alt][g].append(1) + self.sample_variants[s][g].append(variant.key) + + # Update the other alleles + for other_alt in alt_indices: + if other_alt != alt: + alt_alleles[other_alt][g].append(0) + + found = True + if found is not True: + # if there is only one alternate allele, we can assume it is right because of the extra + # checks when pulling the genotype. Otherwise, we'll need to add more exceptions to catch it. + # This is only true for INDELs. + + # Allele does not exist in definitions. Mark as 0. + for a in alt_alleles.keys(): + alt_alleles[a][g].append(0) + + for i in range(n_alts): + phase_index.append(row_phasing_data[i]) + no_call_index.append(row_no_call_data[i]) + + for a in variant.alt: + + # Check that we ended up with the proper number of alleles in the matrix + if len(alt_alleles[a][0]) != len(batch) or len(alt_alleles[a][1]) != len(batch): + print(""Incorrect number of alleles!"") + print(len(alt_alleles[a][0])) + print(len(alt_alleles[a][1])) + print(""Should be %s"" % len(batch)) + variant.print_variant() + exit() + + if self.debug: + print(""%s calls found in A: %s"" % (a, np.sum(alt_alleles[a][0]))) + print(""%s calls found in B: %s"" % (a, np.sum(alt_alleles[a][1]))) + + all_alleles[0].append(alt_alleles[a][0]) + all_alleles[1].append(alt_alleles[a][1]) + + # Extract the final matrices + left_hap = np.array(all_alleles[0]) + right_hap = np.array(all_alleles[1]) + + # Prepare the phase and no call matrices + phase_matrix = np.array(phase_index) + no_call_matrix = np.array(no_call_index) + + # We yield all these outputs like this to enable parallelization + yield((left_hap, right_hap), phase_matrix, self.sample_variants, self.variant_list, no_call_matrix) +","Python" +"Pharmacogenetics","Helix-Research-Lab/PGxPOP","bin/glib.py",".py","2672","95",""""""" +Greg McInes +Altman Lab +gmcinnes@stanford.edu + +Some custom commands I find useful +"""""" + +# Detect if a file is gzipped before opening +def g_open(file): + if file.endswith('gz'): + import gzip + return gzip.open(file) + return open(file) + +#def g_line(file_object): + + +# Check if a function exists on the os +# Source: https://stackoverflow.com/a/377028/3570907 +def which(program): + import os + def is_exe(fpath): + return os.path.isfile(fpath) and os.access(fpath, os.X_OK) + + fpath, fname = os.path.split(program) + if fpath: + if is_exe(program): + return program + else: + for path in os.environ[""PATH""].split(os.pathsep): + path = path.strip('""') + exe_file = os.path.join(path, program) + if is_exe(exe_file): + return exe_file + + return None + +# Run a system command and return the output from stdout +# Optionally, check if it succeeded (exit code = 0) +def run_system_cmd(command, check_exit=True): + import subprocess + #cmd_list = command.split() + p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr = subprocess.PIPE, shell=True) + out, err = p.communicate() + if check_exit: + exit_code = p.returncode + if exit_code != 0: + print(""Process failed!\nCOMMAND: %s\nEXIT CODE: %s\nSTDERR: %s"" % (command, exit_code, err)) + exit(1) + return out + +def check_file_paths(paths, terminate=True): + import os + import sys + for p in paths: + if not os.path.exists(p): + print(""Invalid file path: %s"" % p)#, file=sys.stderr) # shits broken and i don't know why + #if terminate: + # print(""Exiting"", file=sys.stderr) + # exit(1) + +def timestamp(sep="""", pretty=False): + from datetime import datetime + if pretty: + return datetime.now().strftime(""%Y-%m-%d %H:%M:%S"") + return datetime.now().strftime(sep.join([""%Y"", ""%m"", ""%d"", ""%H"", ""%M""])) + +def glog(message, type, end=False): + import sys + print(""%s %s: %s"" % (timestamp(pretty=True), type, message))#, file=sys.stderr) + if end: + print(""Exiting"")#, file=sys.stderr) + exit() + +def intersection(a, b): + # Return the intersection of both lists + return list(set(a) & set(b)) + +def difference(list_a, list_b): + # Return a list of the elements in a that are not in b + return list(set(list_a) - set(list_b)) + +def mean(numbers): + return float(sum(numbers)) / max(len(numbers), 1) + +def chunks(l, n): + """"""Yield successive n-sized chunks from l."""""" + for i in range(0, len(l), n): + yield l[i:i + n] + +def byte_decoder(a): + #print(a) + return a.decode(""utf-8"") +","Python" +"Pharmacogenetics","Helix-Research-Lab/PGxPOP","bin/calculate_statistics.py",".py","3866","117",""""""" +Greg McInes +Altman Lab +gmcinnes@stanford.edu +"""""" + + +import argparse +import os + +class SumStats(object): + def __init__(self, file, prefix, debug=False): + self.file = file + self.prefix = prefix + self.debug = debug + + self.gene_counts = {} + self.haplotypes = {} + self.diplotypes = {} + self.phenotypes = {} + self.phenotypes_presumptive = {} + + self.run() + + def run(self): + with open(self.file) as f: + for line in f: + fields = line.rstrip().split(',') + if fields[0] == ""sample_id"": + continue + + gene = fields[1] + diplotype_raw = fields[2] + hap_1 = fields[3] + hap_2 = fields[4] + phenotype = fields[9] + phenotype_presumptive = fields[12] + + if ""|"" in diplotype_raw: + diplotype_seperator = ""|"" + else: + diplotype_seperator = ""/"" + + diplotype = diplotype_seperator.join(sorted([hap_1, hap_2])) + + if not gene in self.gene_counts: + self.gene_counts[gene] = 0 + self.haplotypes[gene] = {} + self.diplotypes[gene] = {} + self.phenotypes[gene] = {} + self.phenotypes_presumptive[gene] = {} + + self.gene_counts[gene] += 1 + self.update_dict(self.haplotypes[gene], hap_1) + self.update_dict(self.haplotypes[gene], hap_2) + self.update_dict(self.diplotypes[gene], diplotype) + self.update_dict(self.phenotypes[gene], phenotype) + self.update_dict(self.phenotypes_presumptive[gene], phenotype_presumptive) + + self.print_results() + + def update_dict(self, dict, item): + if not item in dict: + dict[item] = 0 + dict[item] += 1 + + def print_results(self): + hap_file = open(""%s.haplotypes.tsv"" % self.prefix, ""w"") + hap_file.write(""gene\thaplotype\tcount\n"") + for g in self.haplotypes: + for h in self.haplotypes[g]: + hap_file.write(""%s\t%s\t%s\n"" % (g, h, self.haplotypes[g][h])) + hap_file.close() + + dip_file = open(""%s.diplotypes.tsv"" % self.prefix, ""w"") + dip_file.write(""gene\tdiplotype\tcount\n"") + for g in self.haplotypes: + for d in self.diplotypes[g]: + dip_file.write(""%s\t%s\t%s\n"" % (g, d, self.diplotypes[g][d])) + dip_file.close() + + phen_file = open(""%s.phenotypes.tsv"" % self.prefix, ""w"") + phen_file.write(""gene\tphenotype\tcount\n"") + for g in self.phenotypes_presumptive: + for p in self.phenotypes_presumptive[g]: + phen_file.write(""%s\t%s\t%s\n"" % (g, p, self.phenotypes_presumptive[g][p])) + phen_file.close() + + #hap_file = open(""%s.haplotypes.tsv"" % self.prefix, ""w"") + #hap_file.write(""gene\thaplotype\tcount\n"") + #for g in self.haplotypes: + # for h in self.haplotypes[g]: + # hap_file.write(""%s\t%s\t%s\n"" % (g, h, self.haplotypes[g][h])) + #hap_file.close() + +"""""" +Parse the command line +"""""" +def parse_command_line(): + parser = argparse.ArgumentParser( + description = 'Calculate summary statistics from PGxPOP output. Prints to stdout') + parser.add_argument(""-f"", ""--file"", help=""Output from PGxPOP run"") + parser.add_argument(""-p"", ""--prefix"", help=""Output prefix"") + parser.add_argument(""-d"", ""--debug"", action='store_true', default=False, + help=""Output debugging messages. May be very verbose."") + options = parser.parse_args() + return options + + +"""""" +Main +"""""" +if __name__ == ""__main__"": + options = parse_command_line() + SumStats(options.file, options.prefix, options.debug) + +","Python" +"Pharmacogenetics","Helix-Research-Lab/PGxPOP","bin/fix_cyp2d6.py",".py","11389","320",""""""" +Greg McInes +Altman Lab +gmcinnes@stanford.edu +"""""" + +# This script will make any necessary changes to the allele definition files. + +# Convert all INDELs to null in the reference sequence +# Split apart the TA repeat in UGT1A1 +# Add known synonyms +# Add hg19 position + +''' +CYP2D6 almost needs it's own script +Due to the whole gene deletion (*5), every single variant is of type deletion in the file, which doesn't make sense +and breaks things on our end. These need to be changed to the actual type of variant they represent. + +Additionally, for *4 IUPAC nucleotide representations are used, perhaps overused. For instance an R is used for a +purine. This is not handled at the moment, so I manually changed all them to the nucleotide in the PharmVar definition. +''' + +import json +import argparse +from pyliftover import LiftOver +from DawgToys import iupac_nt + + +nonmulti_multis = { + 42130692: ""A"", + 42129819: ""T"", + 42129809: ""C"", + 42127941: ""A"", + 42126663: ""C"", + 42126660: ""C"", + 42126647: ""T"", + 42126636: ""A"", + 42126635: ""G"", + 42126633: ""G"", + 42126627: ""C"", + 42126624: ""T"", + 42126623: ""C"", + 42129075: ""T"", + 42130715: ""T"", + 42129042: ""C"", + 42126611: ""G"" +} + +# 42129071 needs to be split into two. with A and G as alts. +# all the others that need to be split should have a / in the definition + +class CYP2D6Cleaner(object): + def __init__(self, file, debug=False): + self.file = file + self.debug = debug + + # Load the data into a global object + self.data = self.get_data() + + self.run() + + def run(self): + + # change all the types to the actual type instead of ""del"" + self.fix_type() + + # Remove IUPAC codes from definitions (only where unnecessary) + self.remove_iupac() + + # Split all the multiallelic variants apart + split_loci = self.fix_variant_defs() + + # delete *5 + self.remove_s5() + + # now update the allele variant lists with the split loci + self.update_allele_variants(split_loci) + + # print the output + print(json.dumps(self.data, indent=2)) + + def remove_s5(self): + for i in range(len(self.data['namedAlleles'])): + if self.data['namedAlleles'][i][""name""] == ""*5"": + del self.data['namedAlleles'][i] + return + + def update_allele_variants(self, split_loci): + + for i in range(len(self.data['namedAlleles'])): + offset = 0 + copy = self.data['namedAlleles'][i][""alleles""] + # for each loci that was split, split the according loci into two. + # in cases where the allele for that star allele matches one of the split loci + # make sure it ends up in the right index + for s in split_loci.keys(): + # this is the position in the original allele list + #print(self.data['namedAlleles'][i][""alleles""][s]) + #print(split_loci[s]) + + loci_alleles = [] + for l in split_loci[s]: + loci_alleles.append(self.data[""variants""][l][""alt""]) + + current_allele = self.data['namedAlleles'][i][""alleles""][s + offset] + + if current_allele in loci_alleles: + #print(self.data['namedAlleles'][i]['name']) + #print(s) + # make sure it goes in the right place + #print(self.data['namedAlleles'][i][""alleles""][s]) + + #print(split_loci[s]) + #print(loci_alleles) + + # Get index where we need to put the matching allele + index = loci_alleles.index(current_allele) + new = [None] * len(loci_alleles) + new = self.update_variant_list(new, index, [current_allele]) + #print(new) + + #print(copy) + #print(s + offset) + copy = self.update_variant_list(copy, s + offset, new) + #print(copy) + + else: + #print(""no changes"") + # otherwise just fill the new space with Nones + + copy = self.update_variant_list(copy, s + offset, [None] * len(split_loci[s])) + + offset += len(split_loci[s]) - 1 + + #print(len(copy)) + + + + + def fix_type(self): + for i in range(len(self.data['variants'])): + if ""ins"" in self.data[""variants""][i]['chromosomeHgvsName']: + self.data[""variants""][i][""type""] = ""INS"" + elif ""del"" in self.data[""variants""][i]['chromosomeHgvsName']: + self.data[""variants""][i][""type""] = ""DEL"" + elif "">"" in self.data[""variants""][i]['chromosomeHgvsName']: + self.data[""variants""][i][""type""] = ""SNP"" + + def remove_iupac(self): + # will need to first get the index of the variant in the variants + for v in nonmulti_multis.keys(): + index = self.get_variant_index_by_pos(v) + + for i in range(len(self.data['namedAlleles'])): + if self.data['namedAlleles'][i][""alleles""][index] in [""W"", ""S"", ""M"", ""K"", ""R"", ""Y""]: + #print(""fixing %s"" % self.data['namedAlleles'][i][""alleles""][index]) + self.data['namedAlleles'][i][""alleles""][index] = nonmulti_multis[v] + + def fix_variant_defs(self): + # for any snps with multiple alts (either by iupac or by /) split them apart + # also any indels + split_loci = {} + + variants_copy = self.data['variants'].copy() + + for i in range(len(self.data['variants'])): + copy_index = i + len(split_loci) + if ""/"" in self.data[""variants""][i]['chromosomeHgvsName']: + + #print(""-----------------------------------------------------------------------"") + #print(self.data[""variants""][i]) + + # This will not work if there are more than two alts. Thankfully that is very rare. + if self.data[""variants""][i]['type'] == ""SNP"": + head, alt2 = self.data[""variants""][i]['chromosomeHgvsName'].split(""/"") + head2 = head[0:-1] + alt2 + + copy_1 = self.data[""variants""][i].copy() + copy_1['chromosomeHgvsName'] = head + copy_1['alt'] = head[-1] + + copy_2 = self.data[""variants""][i].copy() + + copy_2['chromosomeHgvsName'] = head2 + copy_2['alt'] = head2[-1] + + new = [copy_1, copy_2] + + variants_copy = self.update_variant_list(variants_copy, copy_index, new) + + split_loci[i] = [copy_index, copy_index+1] + + elif self.data[""variants""][i]['type'] == ""INS"": + head, alt2 = self.data[""variants""][i]['chromosomeHgvsName'].split(""/"") + head2 = head.split(""ins"")[0] + alt2 + + copy_1 = self.data[""variants""][i].copy() + copy_1['chromosomeHgvsName'] = head + copy_1['alt'] = 'ins' + head.split(""ins"")[-1] + + copy_2 = self.data[""variants""][i].copy() + copy_2['chromosomeHgvsName'] = head2 + copy_2['alt'] = 'ins' + head2.split(""ins"")[-1] + + new = [copy_1, copy_2] + + variants_copy = self.update_variant_list(variants_copy, copy_index, new) + + split_loci[i] = [copy_index, copy_index + 1] + + # Split IUPAC notation apart + if self.data[""variants""][i]['chromosomeHgvsName'][-1] not in ['A', 'C', 'T', 'G']: + iupac = self.data[""variants""][i]['chromosomeHgvsName'][-1] + alternate_nts = iupac_nt(iupac) + new = [] + original = self.data[""variants""][i]['chromosomeHgvsName'] + split_loci[i] = [] + index = 0 + for alt in alternate_nts: + copy = self.data[""variants""][i].copy() + copy['chromosomeHgvsName'] = original[0:-1] + alt + copy['alt'] = copy['chromosomeHgvsName'][-1] + new.append(copy) + + split_loci[i].append(copy_index + index) + index += 1 + + variants_copy = self.update_variant_list(variants_copy, copy_index, new) + + #print(split_loci) + #print(len(self.data[""variants""])) + #print(len(variants_copy)) + + self.data[""variants""] = variants_copy + return split_loci + + def update_variant_list(self, variants, index, new_variants): + # Remove a variant and replace it with new variants in the same position in the list + del variants[index] + for v in reversed(new_variants): + #print(v) + variants.insert(index, v) + return variants + + def get_variant_index_by_pos(self, pos): + for i in range(len(self.data['variants'])): + if self.data[""variants""][i]['position'] == pos: + return i + return None + + def get_data(self): + with open(self.file) as json_file: + data = json.load(json_file) + return data + + def add_alternate_build(self): + # Don't forget to update the synonyms too + for i in self.gene.variants: + # lift the chromosome and position + chr = self.gene.variants[i].chromosome + pos = self.gene.variants[i].position + new_chr, new_pos = self.liftover(chr, pos) + + new_synonyms = [] + if ""synonyms"" in self.data[""variants""][i].keys(): + for s in self.data[""variants""][i][""synonyms""]: + new_chr, s_pos = self.liftover(chr, pos) + new_synonyms.append(s_pos) + + alt_build_info = { + 'build':'hg19', + 'chromosome': new_chr, + 'position': new_pos, + 'synonyms': new_synonyms + } + + self.data[""variants""][i][""hg19""] = alt_build_info + + def liftover(self, chromosome, position, build='hg19'): + + # todo + # Not sure what the failure mode of this tool is. Will probably need to write a try catch eventually + # Changing the chromosome and position messes up the key as well. Could probably fix that. But i don't have + # the ref and alt alleles on hand and I don't want to parse them out of chromosomeHgvsName. + + lo = LiftOver('hg38', build) + lifted = lo.convert_coordinate(chromosome, position) + + new_chromosome = lifted[0][0] + new_position = lifted[0][1] + + if self.debug: + print(""%s %s -> %s %s"" % (chromosome, position, new_chromosome, new_position)) + + return new_chromosome, new_position + + + + +"""""" +Parse the command line +"""""" +def parse_command_line(): + parser = argparse.ArgumentParser( + description = 'This script will make any necessary changes to the allele definition files.') + parser.add_argument(""-f"", ""--file"", help=""Input"") + parser.add_argument(""-d"", ""--debug"", action='store_true', default=False, + help=""Output debugging messages. May be very verbose."") + options = parser.parse_args() + return options + + +"""""" +Main +"""""" +if __name__ == ""__main__"": + options = parse_command_line() + CYP2D6Cleaner(options.file, options.debug) + +","Python" +"Pharmacogenetics","Helix-Research-Lab/PGxPOP","bin/DiplotypeCaller.py",".py","12788","284",""""""" +DiplotypeCaller.py +Written by Adam Lavertu +05-07-2020 + +DiplotypeCaller takes in a gene object, as created by Gene.py. Then given a matrix of an individual's haplotypes, the caller +identifies haplotypes that match the pgx haplotypes in the gene object, scores those matches, and returns the top scoring match. +"""""" +import re + +import numpy as np +from itertools import combinations,product + +np.seterr(divide='ignore', invalid='ignore') + +class DiplotypeCaller(object): + + # Instantiate DiplotypeCaller object + # Inputs: + # gene - Gene.py object + # is_phased - Boolean indicating whether the genotype data is phased, if false shuffled haplotype scoring is used + # get_partials - Boolean indicating whether partial matches to PGx alleles should be returned + def __init__(self, gene, is_phased=False, get_partials=True): + # Get haplotype matrix and associated star allele names from the gene object + self.hap_matrix, self.stars = gene.haplotype_matrix() + self.gene = gene + + # Store total number of defined positions for each gene haplotype + self.hap_alleles_nums = np.sum(self.hap_matrix, axis =1) + + # Find and store the reference allele + self.ref_allele = self.stars[np.where(self.hap_alleles_nums == 0)[0][0]] + + # Store phased flag + self.is_phased = is_phased + + #Store partials flag + self.get_partial_matches = get_partials + + + # Create dictionary object mapping star alleles to their corresponding haplotype vectors + self.star2dip = dict() + self.variant_list = [var.key for var in gene.variants.values()] + for j,x in enumerate(self.stars): + self.star2dip[x] = self.hap_matrix[j,:] + + # check_for_partial_haps + # Inputs: + # comb - list of haplotype combinations + def check_for_partial_haps(self, comb): + outPartials = [] + # Subtract assigned haplotypes from the sample haplotype, + # find variants that are not part of the haplotype allele definitions + for x in np.where(comb[1] - np.sum([self.star2dip.get(s) for s in comb[0]], axis=0) == 1)[0]: + outPartials.append(self.variant_list[x]) + # Return list of additional PGx variants that are not part of the haplotype + return(outPartials) + + # call_diplotype + # Inputs: + # diplotype - list of two vectors, each representing one haplotype of the sample + # uncalled - list of uncalled positions to exclude from analysis + # phase_vector (optional) - vector indicating phased status of each position (1 = phased, 0 = unphased) + # Outputs: + # string of diplotype calls for the given sample, list of uncallable alleles + def call_diplotype(self, diplotype, uncalled, phase_vector = None): + # If data is phased, simply pass through the given diplotype + if self.is_phased: + possib_diplotypes = [diplotype] + # If data is unphased, get list of all possible combinations of the observed variants + else: + possib_diplotypes = self.get_possible_diplotypes(*diplotype, phase_vector) + + # Score all possible diplotypes + dips, dip_scores = self.score_diplotypes(possib_diplotypes) + + # Create list of uncallable star alleles, alleles where at least one relevant position is unobserved + uncallable = [self.stars[x] for x in np.where(np.sum(np.multiply(self.hap_matrix, uncalled.transpose()), axis=1) > 0)[0]] + uncallable = list(set(uncallable)) + + # Find top scoring diplotype + top_dip_score = np.max(dip_scores) + + out_dips = set() + # Find all top scoring diplotypes and format the corresponding string output + for combs in [dips[x] for x in np.where(dip_scores == top_dip_score)[0]]: + # If the star alleles on a single strand have overlapping variants, adjust the output strings + strand1 = ""or"".join(self.process_for_overlaps(combs[0])) + strand2 = ""or"".join(self.process_for_overlaps(combs[1])) + + # If data is phased, output with pipe + if self.is_phased: + star_dip = ""|"".join([strand1,strand2]) + else: + # If data is not phased, sort strings and output with forward slash + try: + star_dip = ""/"".join(sorted([strand1,strand2], key=lambda a: float(a[1:]))) + except: + star_dip = ""/"".join(sorted([strand1,strand2])) + out_dips.add(star_dip) + + return(["";"".join(out_dips), uncallable]) + + # score_diplotypes + # For each possible diplotypes in the nested list of hap_sets, score the star alleles and return + # Inputs: + # hap_sets - nested list of diplotypes, with one pair of haplotypes per nested list + # Outputs: + # list of diplotypes and their associated scores + def score_diplotypes(self, hap_sets): + dips = [] + dip_scores = [] + for haps in hap_sets: + hap1_results = self.get_max_star_alleles(haps[0]) + hap2_results = self.get_max_star_alleles(haps[1]) + tot_dip_score = hap1_results[0] + hap2_results[0] + dip_scores.append(tot_dip_score) + dips.append([hap1_results[1:], hap2_results[1:]]) + return([dips, dip_scores]) + + # get_possible_diplotypes + # Input: + # haplo1 - vector representation of one haplotype + # haplo2 - vector representation of the other haplotype + # phase_vector - vector representation of phased state, only unphased positions will be included in novel + # haplotype combinations + # Output: + # hap_sets - list of possible haplotype combinations given phasing status + def get_possible_diplotypes(self, haplo1, haplo2, phase_vector=None): + # If data is_phased, find positions that are not phased and available for rearrangement + if self.is_phased: + temp_hap1 = np.multiply(haplo1,phase_vector) + temp_hap2 = np.multiply(haplo2,phase_vector) + alt_sites = np.where(temp_hap1 != temp_hap2)[0] + else: + alt_sites = np.where(haplo1 != haplo2)[0] + hap_sets = [] + + # For each alternate allele site create new haplotypes by shuffling the haplotypes at that site + if len(alt_sites) > 1: + combos = [] + for i in range((len(alt_sites)**2)//2): + b = bin(i)[2:].zfill(len(alt_sites)) + combos.append(np.array([int(x) for x in list(b)])) + for c in combos: + hap1 = np.zeros(haplo1.shape) + hap2 = np.zeros(haplo1.shape) + alt_sites_new = set([alt_sites[x] for x in np.where(c == 1)[0]]) + for x in alt_sites: + if x in alt_sites_new: + hap1[x] = 1 + else: + hap2[x] = 1 + hap_sets.append([hap1, hap2]) + else: + hap_sets.append([haplo1, haplo2]) + return(hap_sets) + + # get_max_star_alleles + # Input: + # hap - a single haplotype vector + # Output: + # top_score - highest score achieved by one or more pgx haplotypes (total number of matching positions) + # alleles - list of alleles that achieve that top score + # hap - input haplotype for downstream functions + def get_max_star_alleles(self,hap): + # Calculate the number of hits per haplotype + hap_hit_nums = np.sum(np.multiply(self.hap_matrix,hap), axis=1) + + # Calculate the proportion of alleles matched per haplotype + hap_prop = (hap_hit_nums/self.hap_alleles_nums) + + # If no haplotype matches 100%, return reference + if np.nanmax(hap_prop) != 1.0: + top_score = 0.0 + alleles = [self.ref_allele] + + else: + + top_score = 1.0 + + # Find all alleles with a 100% match + matching_alleles = np.argwhere(hap_prop == 1.0)[:,0] + alleles = {self.stars[x] for x in np.argwhere(hap_prop == 1.0)[:,0]} + + # Check for overlapping haplotypes, i.e. those with positions that sum to more than 1 + pot_dips = self.hap_matrix[matching_alleles,:] + pot_sum = np.sum(pot_dips, axis=0) + toRemove = set() + if np.nanmax(pot_sum) > 1: + + # Find which positions have overlapping alleles + cols_oi = np.argwhere(pot_sum > 1) + + for pos in cols_oi: + # Get haplotypes corresponding to the overlapping alleles + overlap_coords = np.squeeze(np.asarray(np.argwhere(self.hap_matrix[:,pos] == 1)[:,0])) + + # Find the position with the maximum matching and remove the rest + overlap_scores = sorted([(self.hap_alleles_nums[x],self.stars[x]) for x in overlap_coords if self.stars[x] in alleles], reverse=True) + + # Make sure we're not removing duplicate star alleles + for x in overlap_scores[1:]: + # Check that the allele is not the same as the lead allele and is not tied + # for overlap score with the lead allele + if x[1] != overlap_scores[0][1] and x[0] != overlap_scores[0][0]: + toRemove.add(x[1]) + + # Filter alleles for the overlaps then return the remaining matching alleles + alleles = list(alleles.difference(toRemove)) + if ""*1"" in alleles and len(alleles) > 1: + _ = alleles.remove(""*1"") + + return([top_score, alleles, hap]) + + # process_for_overlaps + # Input: + # hap_result - a single haplotype vector + # Output: + # outSet - set of haplotypes that overlap within the selected haplotypes + def process_for_overlaps(self, hap_result): + # Create matrix of the identified haplotypes + hit_gen_mat = np.matrix([self.star2dip.get(x) for x in hap_result[0]]) + + # Find positions not overlapping with the identified haplotypes + overlap = np.where(np.squeeze(np.array(np.any(np.dot(hit_gen_mat, hit_gen_mat.transpose()) > 1, axis=1))))[0] + + # Find locations where there's an alternate allele and it's already covered by the identified haplotypes + non_overlap = np.where(np.squeeze(np.array(np.all(np.dot(hit_gen_mat, hit_gen_mat.transpose()) <= 1, axis=1))))[0] + add_haps = [hap_result[0][j] for j in non_overlap] + + outSet = set() + partial_vars_hap = [] + # Find overlapping haplotypes and format for output + if len(overlap) > 0: + for sep_allele in overlap: + subset = [hap_result[0][sep_allele]] + add_haps + if self.get_partial_matches: + partial_vars_hap = self.check_for_partial_haps([subset,hap_result[1]]) + subset = [a.split(f""%"")[0] for a in subset] + subset = list(set(subset)) + x = ""+"".join(sorted(subset, key=lambda a: a[1:]) + partial_vars_hap) + outSet.add(x) + else: + if self.get_partial_matches: + partial_vars_hap = self.check_for_partial_haps([add_haps,hap_result[1]]) + subset = [a.split(f""%"")[0] for a in add_haps] + subset = list(set(subset)) + x = ""+"".join(sorted(subset, key=lambda a: a[1:]) + partial_vars_hap) + outSet.add(x) + return(outSet) + + # Test function + def test_gene(self, gene): + haps, stars = gene.haplotype_matrix() + indices = [x for x in range(len(stars))] + true_dips = [] + true_haps = [] + for hap1, hap2 in combinations(indices, 2): + if self.is_phased: + true_dips.append(""|"".join([stars[hap1], stars[hap2]])) + else: + true_dips.append(""/"".join([stars[hap1], stars[hap2]])) + true_haps.append([haps[hap1], haps[hap2]]) +# len(fake_dips) + + pred_dips = [] + for hap_set in true_haps: + pred_dips.append(self.call_diplotype(hap_set)) + + misses = [] + for x in range(len(pred_dips)): + if self.is_phased and true_dips[x] != pred_dips[x]: + misses.append([true_dips[x], pred_dips[x]]) + else: + t = set(re.split(r""[/\|]+"", true_dips[x])) + p = set(re.split(r""[/\|]+"", pred_dips[x])) + if len(p.difference(t)) > 0: + misses.append([true_dips[x], pred_dips[x]]) + + return({""error rate"":len(misses)/len(true_dips), ""misses"":misses, ""true_dips"":true_dips, ""pred_dips"":pred_dips}) + + +","Python" +"Pharmacogenetics","Helix-Research-Lab/PGxPOP","bin/test.py",".py","5435","187",""""""" +Greg McInes +Altman Lab +gmcinnes@stanford.edu +"""""" + + +import argparse +import os + +from CityDawg import CityDawg +from DiplotypeCaller import DiplotypeCaller +from DawgToys import * +from Gene import Gene + +class DawgTest(object): + def __init__(self, file, debug=False): + self.file = file + self.debug = debug + + self.run() + + def run(self): + + # Two parts here + # 1. Check test files defined by PharmCAT + # This will test the VCF loader and caller + # 2. Test all possible combinations of named alleles + # This will check for any systematic bias when calling haplotypes from phased and unphased data. + + + self.pharmcat_tests() + + self.combo_tests() + + + def combo_tests(self): + print(""Running haplotype combination tests"") + + genes = ['CFTR', 'CYP2C9', 'CYP2D6', 'CYP4F2', 'IFNL3', 'TPMT', 'VKORC1', + 'CYP2C19', 'CYP3A5', 'DPYD', 'SLCO1B1', 'UGT1A1'] + + for g in genes: + # Create the gene object + gene_definition = get_definition_file(g) + gene = Gene(gene_definition, debug=self.debug) + for phased in [False, True]: + dc = DiplotypeCaller(gene, is_phased=phased) + combo_gene_results = dc.test_gene(gene) + print(""%s error rate (phased = %s): %s"" % (g, phased, combo_gene_results['error rate'])) + #print(combo_gene_results.keys()) + + + + + + def pharmcat_tests(self, gene='all'): + print(""Executing PharmCAT tests"") + tests = self.get_tests() + + failed = [] + missed_alleles = {} + for t in tests: + if t['skip'] == '1': + continue + result, missed = self.run_pharmcat_test(t) + + if result is not None: + t['result'] = result + failed.append(t) + + if t['gene'] not in missed_alleles.keys(): + missed_alleles[t['gene']] = {} + for h in missed: + if h not in missed_alleles[t['gene']].keys(): + missed_alleles[t['gene']][h] = 0 + missed_alleles[t['gene']][h] += 1 + + print(""--------------------------------------------------------------------"") + print(""%s failed tests"" % len(failed)) + for f in failed: + print(""%s %s %s"" % (f['gene'], f['file'], f['result'])) + + print(missed_alleles) + + + def run_pharmcat_test(self, test): + #if self.debug: + print(""--------------------------------------------------------------------"") + print(""Gene: %s, File: %s"" % (test['gene'], test['file'])) + + test_file = self.test_path(test['gene'], test['file']) + + + if test['phased'] == '1': + phased = True + else: + phased = False + + failure = None + missed = [] + + try: + cd = CityDawg(vcf=test_file, gene=test['gene'], phased=phased, debug=self.debug) + result = cd.process_gene(test['gene'])[0] + except: + failure = ""parse error"" + print(""TEST FAILED"") + print(""Parse error"") + return failure, missed + + + test_haps = [test['hap1'], test['hap2']] + result_haps = [result['hap_1'], result['hap_2']] + + test_haps.sort() + result_haps.sort() + + if test_haps == result_haps: + print(""Test passed"") + + else: + print(""TEST FAILED"") + print(""Expected: %s"" % "","".join(test_haps)) + #print(""Found: %s"" % "","".join(result_haps)) + print(""Found: %s"" % result['diplotype']) + failure = ""Match error"" + + missed = [] + for h in test_haps: + if h not in result_haps: + missed.append(h) + + return failure, missed + + + def test_path(self, gene, file): + test_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), ""../test/%s/"" % gene) + test_file = os.path.join(test_dir, file) + return test_file + + def get_tests(self): + tests = [] + with open(self.get_pharmcat_test_file()) as f: + for line in f: + if line.startswith(""gene""): + continue + fields = line.rstrip().split("","") + new_row = { + 'gene':fields[0], + 'file': fields[1], + 'hap1': fields[2], + 'hap2': fields[3], + 'phased': fields[4], + 'skip': fields[5] + } + tests.append(new_row) + return tests + + def get_pharmcat_test_file(self): + definition_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), ""../test/"") + filename = ""pharmcat_test_cases.csv"" + definition_file = os.path.join(definition_dir, filename) + return definition_file + + +"""""" +Parse the command line +"""""" +def parse_command_line(): + parser = argparse.ArgumentParser( + description = 'This is a script I wrote') + parser.add_argument(""-f"", ""--file"", help=""Input"") + parser.add_argument(""-d"", ""--debug"", action='store_true', default=False, + help=""Output debugging messages. May be very verbose."") + options = parser.parse_args() + return options + + +"""""" +Main +"""""" +if __name__ == ""__main__"": + options = parse_command_line() + DawgTest(options.file, options.debug) + +","Python" +"Pharmacogenetics","Helix-Research-Lab/PGxPOP","bin/ExceptionCaller.py",".py","2669","65","# I DON'T THINK WE NEED THIS ANYMORE, AND IT CAN BE REMOVED ENTIRELY + +import numpy as np +import json + +class ExceptionCaller(object): + def __init__(self, gene_exception_file, gene, is_phased = False): + self.data = json.load(open(gene_exception_file)) + self.is_phased = is_phased + self.override = self.data['overide_all'] + self.affected_diplotypes = self.data['affected_diplotypes'] + self.build_exception_rules(gene) + + def build_exception_rules(self, gene): + hapCond_to_index_mapping = {} + for haplotype in self.data['rules']: + if 'rsids' in self.data['rules'][haplotype]: + for rsid in self.data['rules'][haplotype]['rsids']: + hapCond_to_index_mapping[rsid] = None + for ind, var in gene.variants.items(): + if var.rsid in hapCond_to_index_mapping: + hapCond_to_index_mapping[var.rsid] = ind + + self.hap_defs = {} + for hap, rules in self.data['rules'].items(): + temp = {} + for v in rules.values(): + for var, info in v.items(): + temp[hapCond_to_index_mapping[var]] = int(info) + self.hap_defs[hap] = temp + + + def call_samples(self, sample_order, gt_matrices): + sample_dips = {} + sample_variants = {} + for gt_mat, phase_matrix, sample_vars, variant_list, uncalled in gt_matrices: + sample_variants.update(sample_vars) + for hap, crits in self.hap_defs.items(): + for crit, val in crits.items(): + + for samp in np.where(gt_mat[0][crit] == val)[0]: + sid = sample_order[samp] + if sid not in sample_dips: + sample_dips[sid] = [hap, None] + else: + sample_dips[sid][0] = hap + + for samp in np.where(gt_mat[1][crit] == val)[0]: + sid = sample_order[samp] + if sid not in sample_dips: + sample_dips[sid] = [None, hap] + else: + sample_dips[sid][1] = hap + + + out_calls = dict() + if self.is_phased: + for sample in sample_dips: + out_calls[sample] = ""|"".join(sample_dips[sample]) + else: + for sample in sample_dips: + out_calls[sample] = ""/"".join(sorted(sample_dips[sample])) + + return([out_calls, sample_variants]) +","Python" +"Pharmacogenetics","Helix-Research-Lab/PGxPOP","bin/synonym_checker.py",".py","3400","100",""""""" +Greg McInes +Altman Lab +gmcinnes@stanford.edu +"""""" + +# Check all definitions RSIDs against a VCF file for any positions where +# the RSID is the same but the position is different + +import argparse +import sys +import os + +from Gene import Gene +from DawgToys import parse_vcf_line + +class SynonymChecker(object): + def __init__(self, file, build='grch38', debug=False): + self.file = file + self.build = build + self.debug = debug + + self.run() + + def run(self): + + # Get all the positions associated with star allele definitions + definition_rsids = self.get_rsids() + + # Iterate over the VCF and check whether there are any rsids where the position is different in the + # VCF than it is in the definition + with open(self.file) as f: + for line in f: + if line.startswith(""#""): + continue + vcf_line = parse_vcf_line(line) + if vcf_line.id in definition_rsids.keys(): + print(""rsid found: %s"" % vcf_line.id) + variant = definition_rsids[vcf_line.id] + if str(variant[""position""]) != str(vcf_line.pos): + print(""Position mismatch!"") + vcf_line.print_row() + print(definition_rsids[vcf_line.id]) + # Also check for allele flips + if variant[""ref""] != vcf_line.ref: + print(""Ref mismatch!"") + vcf_line.print_row() + print(definition_rsids[vcf_line.id]) + + + def get_rsids(self): + variants = {} + + genes = ['CFTR', 'CYP2C9', 'CYP4F2', 'IFNL3', 'TPMT', 'VKORC1', 'NUDT15', + 'CYP2C19', 'CYP3A5', 'DPYD', 'SLCO1B1', 'UGT1A1', 'CYP2D6', 'CYP2B6', ] + + for g in genes: + gene_definition = self.get_definition_file(g) + gene = Gene(gene_definition, build=self.build, debug=self.debug) + + for v in gene.variants: + if gene.variants[v].rsid != None: + variants[gene.variants[v].rsid] = { + ""position"": gene.variants[v].position, + ""ref"": gene.variants[v].ref, + ""alt"": gene.variants[v].alt + } + + return variants + + + def get_definition_file(self, g): + definition_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), ""../definition/alleles/"") + filename = ""%s_translation.json"" % g + definition_file = os.path.join(definition_dir, filename) + return definition_file + +"""""" +Parse the command line +"""""" +def parse_command_line(): + parser = argparse.ArgumentParser( + description = 'Check all definitions RSIDs against a VCF file for any positions ' + 'where the RSID is the same but the position is different') + parser.add_argument(""-f"", ""--file"", help=""Input"") + parser.add_argument(""-b"", ""--build"", default=""grch38"", help=""Alternate genome build"") + parser.add_argument(""-d"", ""--debug"", action='store_true', default=False, + help=""Output debugging messages. May be very verbose."") + options = parser.parse_args() + return options + + +"""""" +Main +"""""" +if __name__ == ""__main__"": + options = parse_command_line() + SynonymChecker(options.file, options.build, options.debug) + +","Python" +"Pharmacogenetics","Helix-Research-Lab/PGxPOP","bin/gseq.py",".py","20684","721",""""""" +Greg McInes +Altman Lab +gmcinnes@stanford.edu + +A set of commands to work with sequencing data +"""""" + +from __future__ import division +from glib import * +import sys + +# Calculate GC content for specified genomic window +def window_gc_content(fasta_file, chr, start, end): + sequence = fasta_extract(fasta_file, chr, start, end) + gc = gc_content(sequence) + return gc + +# Calculate the GC content of a sequence of DNA +def gc_content(sequence): + # Make the entire sequence uppercase + sequence = sequence.upper() + # Get the necessary counts + seq_length = len(sequence) + if seq_length == 0: + return 0 + g_count = sequence.count(""G"") + c_count = sequence.count(""C"") + + # Calculate gc content. Sum of G's and C's divided by sequence length + gc_content = (g_count + c_count) / seq_length + return gc_content + +# Extract sequence from a fasta file using samtools +def fasta_extract(fasta_file, chr, start, end): + # Check if samtools is available + if not which('samtools'): + print(""Samtools not found on path. Please install to continue."") + exit(1) + # Format the region + + #region = ""%s:%s-%s"" % (clean_chr(chr), start, end) + region = ""%s:%s-%s"" % (chr, start, end) + #print(region) + #print(fasta_file) + # Format and execute the command + command = 'samtools faidx %s %s' % (fasta_file, region) + output = run_system_cmd(command) + # Format the response + # The returned sequence will have a header line (>chr:start-end) followed by newline separated sequence + seq_list = output.split(b""\n"") + seq = '' + for s in seq_list[1:]: + seq += s.decode(""utf-8"") + return seq + + +# Check whether a chromosome is greater than or less than another chromosome +def chr_greater_than_chr(chr1, chr2): + + chr1 = str(chr1) + chr2 = str(chr2) + + chr1 = strip_chr(chr1) + chr2 = strip_chr(chr2) + + # Check whether they're the same + if chr1 == chr2: + return False + + # Check the non numeric chromosomes. I know there are more but I'm not accounting for those + if chr1.lower() == 'x': + if chr2.lower() == 'y' or chr2.lower() == 'm': + return False + return True + + if chr1.lower() == 'y': + if chr2.lower() == 'x': + return True + + if chr2.lower() == 'm': + return False + + if chr2.lower() in ['x', 'y', 'm']: + return False + + try: + chr1 = int(chr1) + chr2 = int(chr2) + + return chr1 > chr2 + + except Exception as e: + print(e) + exit() + +def get_vcf_subject_ids(vcf): + ids = [] + with g_open(vcf) as f: + for line in f: + try: + line = byte_decoder(line) + except: + line = line + if line.startswith(""#CHROM""): + fields = line.rstrip().split() + ids = fields[9:] + break + return ids + +#todo get subjects and make a dictionary +def parse_vcf_line(line): + CHROM = 0 + POS = 1 + ID = 2 + REF = 3 + ALT = 4 + QUAL = 5 + FILTER = 6 + INFO = 7 + FORMAT = 8 + calls = 9 + if isinstance(line, list) is True: + fields = line + else: + fields = line.rstrip().split() + + class VCFfields(object): + def __init__(self): + self.chrom = None + self.pos = None + self.id = None + self.ref = None + self.alt = None + self.qual = None + self.filter = None + self.info = {} + self.format = None + self.calls = [] + + def print_row(self, chr=True): + info_print_format = self.format_info() + calls_print_format = ""\t"".join(self.calls) + if chr: + # If I want to make sure the output has chr on the chromosome, do this. Kind of messy but works. + chrom = ""chr%s"" % strip_chr(self.chrom) + else: + chrom = self.chrom + print(""%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s"" % (chrom, self.pos, self.id, self.ref, self.alt, + self.qual, self.filter, info_print_format, self.format, + calls_print_format)) + def intake_info(self, info): + fields = info.split(';') + for f in fields: + try: + key, value = f.split(""="") + self.info[key] = value + except: + pass + + def format_info(self): + output = [] + if len(self.info) == 0: + return ""."" + for key, value in self.info.items(): + output.append(""%s=%s"" % (key, value)) + + + return "";"".join(output) + + def add_info(self, key, value): + self.info[key] = value + + def add_allele(self, new): + if new == self.alt: + return + self.alt += "",%s"" % new + + def make_multiallelic(self, new_vcf): + self.add_allele(new_vcf.alt) + # add the info + for i in new_vcf.info: + self.add_info(i, new_vcf.info[i]) + # update the genotypes + for i in range(len(new_vcf.calls)): + if ""/"" in new_vcf.calls[i]: + alleles = new_vcf.calls[i].split(""/"") + elif ""|"" in new_vcf.calls[i]: + alleles = new_vcf.calls[i].split(""|"") + else: + print(""Unrecognized delimiter!"") + print(new_vcf.calls[i]) + exit() + + alt_found = False + + n_alts = str(len(self.alts())) + #rint(n_alts) + + if alleles[0] == '1': + #alleles[0] = str(len(alleles)) + alleles[0] = n_alts + alt_found = True + if alleles[1] == '1': + #alleles[1] = str(len(alleles)) + alleles[1] = n_alts + alt_found = True + if alt_found: + self.calls[i] = ""/"".join(alleles) + + + + + def alts(self): + return self.alt.split("","") + + def is_multiallelic(self): + if len(self.alts()) == 1: + return False + return True + + def max_insertion(self): + max_insert = 1 + for a in self.alts(): + #if len(a) - len(self.ref) > max_insert: + if len(a) > max_insert: + max_insert = len(a) #- len(self.ref) + return max_insert + + def max_insertion2(self): + max_insert = 0 + for a in self.alts(): + print(a, file=sys.stderr) + print(len(a) - len(self.ref), file=sys.stderr) + if len(a) - len(self.ref) > max_insert: + max_insert = len(a) - len(self.ref) + return max_insert + + + row = VCFfields() + row.chrom = fields[CHROM] + row.pos = int(fields[POS]) + row.id = fields[ID] + row.ref = fields[REF] + row.alt = fields[ALT] + row.qual = fields[QUAL] + row.filter = fields[FILTER] + row.intake_info(fields[INFO]) + if len(fields) > 8: + row.format = fields[FORMAT] + row.calls = fields[calls:] + return row + + +# +def bed_extract(bed_file): + class BedFields(object): + def __init__(self): + self.entries = { + ""chrom"":[], + ""start"":[], + ""end"":[] + } + self.count = 0 + def add_entry(self, chrom, start, end): + self.entries[""chrom""].append(chrom) + self.entries[""start""].append(int(start)) + self.entries[""end""].append(int(end)) + self.count += 1 + def retrieve_entry(self, index): + # todo, check for valid index + return self.entries['chrom'][index], self.entries['start'][index], self.entries['end'][index] + bed_result = BedFields() + with open(bed_file) as f: + for line in f: + if line.startswith('#'): + continue + fields = line.rstrip().split() + bed_result.add_entry(chrom=fields[0], start=fields[1], end=fields[2]) + return bed_result + + def check_range(self, bed, vcf): + if chr_greater_than_chr(bed[0], vcf[0]): + return False + if bed[1] > vcf[1]: + return False + return True + + + + + + + + + +def strip_chr(chrom): + if isinstance(chrom, int): + return chrom + if chrom.startswith('chr'): + return chrom.replace(""chr"", """") + return chrom + +# Write functions to check if an allele is a pyrimadine or purine +def is_purine(allele): + purines = ['A', 'G'] + if allele in purines: + return True + return False + +def is_pyrimadine(allele): + pyrimadine = ['C', 'T'] + if allele in pyrimadine: + return True + return False + +# Write functions to check if a variant is a transition or transversion +def is_transition(allele_1, allele_2): + if (is_purine(allele_1) and is_purine(allele_2)) or (is_pyrimadine(allele_1) and is_pyrimadine(allele_2)): + return True + return False + +def is_transversion(allele_1, allele_2): + if (is_purine(allele_1) and is_pyrimadine(allele_2)) or (is_pyrimadine(allele_1) and is_purine(allele_2)): + return True + return False + +# Check if a variant is an indel +def is_indel(ref, alt): + if len(ref) != 1 or len(alt) != 1: + return True + return False + +def indel_size(ref, alt): + return abs(len(ref) - len(alt)) + +def is_frameshift(ref, alt): + if indel_size(ref, alt) % 3 == 0: + return False + return True + + +def high_at(fasta_file, chr, start, end): + gc = window_gc_content(fasta_file, chr, start, end) + if gc < 0.25: + return True + return False + +def high_gc(fasta_file, chr, start, end): + gc = window_gc_content(fasta_file, chr, start, end) + if gc > 0.75: + return True + return False + +# Allele frequency calculations +def is_commom(af): + if af >= 0.01: + return True + return False + +def is_rare(af, include_very_rare=True): + if af == ""."": + return True + af = float(af) + # Cutoff for rare from GoT2D paper + # https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5034897/ + if include_very_rare and af < 0.005: + return True + if af >= 0.00001 and af < 0.005: + return True + return False + +def is_very_rare(af): + if af == ""."": + return True + if af < 0.00001: + return True + return False + +# Conservation +def is_conserved(phylop_score): + # Super simple threshold here. Could definitely do better if I did some reading + if phylop_score > 0.5: + return True + return False + +def is_dann_pathogenic(dann): + # Super rough eyeballed cutoff based on this + # http://www.enlis.com/blog/2015/03/17/the-best-variant-prediction-method-that-no-one-is-using/ + try: + if float(dann) > 0.9688: + return True + else: + return False + except: + return False + +def is_fathmm_pathogenic(fathmm): + # Super rough eyeballed cutoff based on this + # http://www.enlis.com/blog/2015/03/17/the-best-variant-prediction-method-that-no-one-is-using/ + #if fathmm > 0.8: + # return True + #return False + if fathmm > 0.8: + return True + return False + +def is_cadd_pathogenic(cadd): + # http://cadd.gs.washington.edu/info + # recommended cutoff + if cadd > 19.19: + return True + return False + +def is_gerp_pathogenic(gerp): + # cutoff from here + # https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4460046/ + if gerp >= 2: + return True + return False + +def vcf_info_to_dict(info): + dict = {} + info_fields = info.split(';') + for f in info_fields: + field = f.split(""="") + if len(field) == 1: + continue + dict[field[0]] = field[1] + return dict + +# Functional annotations +def is_exonic(vcf_info): + if ""Func.refGene"" in vcf_info: + function = vcf_info[""Func.refGene""] + if function == 'exonic': + return True + return False + +def is_intronic(func): + if func == 'intronic': + return True + return False + +def is_utr(func): + if func in ['UTR5', 'UTR3']: + return True + return False + +def is_intergenic(func): + if func == 'intergenic': + return True + return False + +def is_neighboring(func): + if func in ['upstream', 'downstream']: + return True + return False + +def is_splicing(func): + if func == 'splicing': + return True + return False + +def is_ncrna(func): + if func in ['ncRNA_exonic', 'ncRNA_intronic']: + return True + return False + +def is_lof(func): + if func in ['frameshift_insertion', 'frameshift_deletion', 'stopgain', 'stoploss']: + return True + return False + +def is_deleterious(dann, func): + #print(dann, func) + if is_dann_pathogenic(dann): + return True + if is_lof(func): + return True + return False + +def is_deleterious_2(vcf_info, ref, alt): + # Check Loftee + loftee = is_loftee_lof(vcf_info) + if loftee is True: + return True + if loftee is False: + return False + # If loftee returns None that means there was no prediction for this variant + + if is_exonic(vcf_info): + # Check whether it's a frameshift indel. Loftee should be checking these already. This is here just in case. + if is_frameshift(ref, alt): + return True + + # For SNPs, do majority vote of LRT, MutationAssessor, Provean, VEST, and CADD + if pgx_coding_deleterious(vcf_info): + return True + + # If it's non-coding, do majority vote of cadd, dann, and fathmm + else: + if pgx_noncoding_deleterious(vcf_info): + return True + + return False + + + +def pgx_coding_deleterious(vcf_info): + lrt = is_lrt_deleterious(vcf_info) + ma = is_mutation_assessor_deleterious(vcf_info) + cadd = is_cadd_deleterious(vcf_info) + provean = is_provean_deleterious(vcf_info) + vest = is_vest_deleterious(vcf_info) + votes = sum([lrt, ma, cadd, provean, vest]) + if votes >= 3: + + + return True + return False + +def pgx_noncoding_deleterious(vcf_info): + dann = is_dann_deleterious(vcf_info, noncoding=True) + fathmm = is_fathmm_deleterious(vcf_info, noncoding=True) + cadd = is_cadd_deleterious(vcf_info, noncoding=True) + + votes = sum([dann, fathmm, cadd]) + if votes >= 2: + return True + return False + + +def is_lrt_deleterious(vcf_info): + if ""LRT_score"" in vcf_info: + LRT_score = vcf_info[""LRT_score""] + if LRT_score == ""."": + return False + if float(LRT_score) < 0.0025: + return True + return False + +def is_mutation_assessor_deleterious(vcf_info): + if ""MutationAssessor_score"" in vcf_info: + MutationAssessor_score = vcf_info[""MutationAssessor_score""] + if MutationAssessor_score == ""."": + return False + if float(MutationAssessor_score) > 2.0566: + return True + return False + +def is_provean_deleterious(vcf_info): + if ""PROVEAN_score"" in vcf_info: + PROVEAN_score = vcf_info[""PROVEAN_score""] + if PROVEAN_score == ""."": + return False + if float(PROVEAN_score) < -3.286: + return True + return False + +def is_vest_deleterious(vcf_info): + if ""VEST3_score"" in vcf_info: + VEST3_score = vcf_info[""VEST3_score""] + if VEST3_score == ""."": + return False + if float(VEST3_score) > 0.4523: + return True + return False + +def is_cadd_deleterious(vcf_info, noncoding=False): + cutoff = 19.19 + if noncoding: + cutoff = 15 + + if ""CADD_Phred"" in vcf_info: + CADD_Phred = vcf_info[""CADD_Phred""] + if CADD_Phred == ""."": + return False + if float(CADD_Phred) > cutoff: + return True + return False + +def is_dann_deleterious(vcf_info, noncoding=False): + cutoff = 0.9688 + if noncoding: + cutoff = 0.9 + + if ""dann"" in vcf_info: + dann = vcf_info[""dann""] + if dann == ""."": + return False + if float(dann) > cutoff: + return True + return False + +def is_fathmm_deleterious(vcf_info, noncoding=False): + + if noncoding: + cutoff = 0.9 + if ""FATHMM_noncoding"" in vcf_info: + CADD_Phred = vcf_info[""FATHMM_noncoding""] + if CADD_Phred == ""."": + return False + if float(CADD_Phred) > cutoff: + return True + + else: + cutoff = 0.3982 + if ""FATHMM_coding"" in vcf_info: + CADD_Phred = vcf_info[""FATHMM_coding""] + if CADD_Phred == ""."": + return False + if float(CADD_Phred) > cutoff: + return True + + + return False + +def is_loftee_lof(vcf_info): + # Get the VEP part + vep_string = 'Allele|Consequence|IMPACT|SYMBOL|Gene|Feature_type|Feature|BIOTYPE|EXON|INTRON|HGVSc|HGVSp|cDNA_position|CDS_position|Protein_position|Amino_acids|Codons|Existing_variation|DISTANCE|STRAND|FLAGS|SYMBOL_SOURCE|HGNC_ID|REFSEQ_MATCH|SOURCE|GIVEN_REF|USED_REF|BAM_EDIT|MOTIF_NAME|MOTIF_POS|HIGH_INF_POS|MOTIF_SCORE_CHANGE|LoF|LoF_filter|LoF_flags|LoF_info' + vep_fields = vep_string.split('|') + + if ""CSQ"" in vcf_info: + vep_annotations = [dict(zip(vep_fields, x.split('|'))) for x in vcf_info['CSQ'].split(',')][0] + #print(vep_annotations) + if vep_annotations['LoF'] == ""HC"": + return True + if vep_annotations['LoF'] == ""LC"": + return False + + return None + +def amino_acid_change(vcf_info): + # Get the VEP part + vep_string = 'Allele|Consequence|IMPACT|SYMBOL|Gene|Feature_type|Feature|BIOTYPE|EXON|INTRON|HGVSc|HGVSp|cDNA_position|CDS_position|Protein_position|Amino_acids|Codons|Existing_variation|DISTANCE|STRAND|FLAGS|SYMBOL_SOURCE|HGNC_ID|REFSEQ_MATCH|SOURCE|GIVEN_REF|USED_REF|BAM_EDIT|MOTIF_NAME|MOTIF_POS|HIGH_INF_POS|MOTIF_SCORE_CHANGE|LoF|LoF_filter|LoF_flags|LoF_info' + vep_fields = vep_string.split('|') + + if ""CSQ"" in vcf_info: + vep_annotations = [dict(zip(vep_fields, x.split('|'))) for x in vcf_info['CSQ'].split(',')][0] + #print(vep_annotations) + + protein_pos = vep_annotations['Protein_position'] + amino_acid = vep_annotations['Amino_acids'] + + if ""/"" in amino_acid: + aminos = amino_acid.split(""/"") + change = ""%s%s%s"" % (aminos[0], protein_pos, aminos[1]) + return change + + if len(amino_acid) == 1: + change = ""%s%s%s"" % (amino_acid, protein_pos, amino_acid) + return change + + return ""NA"" + +def is_methylation_site(vcf_info): + # Check wgEncodeHaibMethyl450Gm12878SitesRep1 & wgEncodeHaibMethylRrbsGm12878HaibSitesRep1 + # If either are true return True + if ""wgEncodeHaibMethyl450Gm12878SitesRep1"" in vcf_info: + wgEncodeHaibMethyl450Gm12878SitesRep1 = vcf_info[""wgEncodeHaibMethyl450Gm12878SitesRep1""] + if wgEncodeHaibMethyl450Gm12878SitesRep1 != ""."": + return True + if ""wgEncodeHaibMethylRrbsGm12878HaibSitesRep1"" in vcf_info: + wgEncodeHaibMethylRrbsGm12878HaibSitesRep1 = vcf_info[""wgEncodeHaibMethylRrbsGm12878HaibSitesRep1""] + if wgEncodeHaibMethylRrbsGm12878HaibSitesRep1 != ""."": + return True + return False + +def is_tf_binding_site(vcf_info): + # Check wgEncodeRegTfbsClusteredV3 & tfbsConsSites + if ""tfbsConsSites"" in vcf_info: + tfbsConsSites = vcf_info[""tfbsConsSites""] + if tfbsConsSites != ""."": + return True + if ""wgEncodeRegTfbsClusteredV3"" in vcf_info: + wgEncodeRegTfbsClusteredV3 = vcf_info[""wgEncodeRegTfbsClusteredV3""] + if wgEncodeRegTfbsClusteredV3 != ""."": + return True + return False + +def is_eQTL(vcf_info): + # Check CYP2D6_eQTLs + if ""eQTL"" in vcf_info: + eQTL = vcf_info[""eQTL""] + if eQTL != ""."": + return True + return False + + +def is_dnase_hypersensitivity_site(vcf_info): + # Check wgEncodeAwgDnaseMasterSites + if ""wgEncodeAwgDnaseMasterSites"" in vcf_info: + wgEncodeAwgDnaseMasterSites = vcf_info[""wgEncodeAwgDnaseMasterSites""] + if wgEncodeAwgDnaseMasterSites != ""."": + return True + return False + + +def clean_chr(chr): + if not chr: + return chr + if chr.startswith('chr'): + return chr[3:] + return chr + +def is_deletion(ref, alt): + if len(alt) < len(ref): + return True + return False + +def split_genotype(gt): + if ""/"" in gt: + alleles = gt.split(""/"") + return alleles + elif ""|"" in gt: + alleles = gt.split(""|"") + return alleles + print(""Unrecognized delimiter! %s"" % gt) + return gt +","Python" +"Pharmacogenetics","Helix-Research-Lab/PGxPOP","bin/DawgToys.py",".py","20896","694","import numpy as np +import tabix +import os +import sys + +"""""" +Get sites that are included in more than one haplotype definition + +Inputs: + haplotye_matrix: numpy matrix, containing one haplotype per row +Returns: + competitive_haplotypes: Dictionary of each star allele and the haplotypes that it shares variants with +"""""" +def get_competitive_haplotype_indices(haplotype_matrix): + dual_sites = np.where(np.sum(haplotype_matrix, axis=0) > 1)[0] + competitive_haplotypes = dict() + for x in haplotype_matrix[:,dual_sites].T: + comps = set(np.where(x == 1)[0]) + for y in comps: + if y not in competitive_haplotypes: + competitive_haplotypes[y] = set() + competitive_haplotypes[y].update(comps.difference({y})) + return(competitive_haplotypes) + + +"""""" +Normalize chromosome names. Sometimes chromosomes are listed as just numbers, other times they start with 'chr'. +This function strips the 'chr' and returns just the chromosome number, if applicable. + +Inputs: + chr: variable containing chromosome id +Returns: + chr with 'chr' stripped from beginning. + +"""""" +def clean_chr(chr): + if isinstance(chr, int): + return chr + if chr.startswith('chr'): + return chr.replace(""chr"", """") + return chr + +''' +This function parses a line from a VCF into an object with some useful functions. + +Inputs: + line: A string directly from a VCF representing an entire row of call data. +Returns: + VCFfields object +''' +def parse_vcf_line(line): + CHROM = 0 + POS = 1 + ID = 2 + REF = 3 + ALT = 4 + QUAL = 5 + FILTER = 6 + INFO = 7 + FORMAT = 8 + calls = 9 + + if isinstance(line, list) is True: + fields = line + else: + fields = line.rstrip().split() + + class VCFfields(object): + def __init__(self): + self.chrom = None + self.pos = None + self.id = None + self.ref = None + self.alt = None + self.qual = None + self.filter = None + self.info = {} + self.format = None + self.calls = [] + self.gt_index = None + + def print_row(self, chr=True, minimal=False): + info_print_format = self.format_info() + calls_print_format = ""\t"".join(self.calls) + if chr: + # If I want to make sure the output has chr on the chromosome, do this. Kind of messy but works. + chrom = ""chr%s"" % clean_chr(self.chrom) + else: + chrom = self.chrom + if minimal is True: + print(""%s\t%s\t%s\t%s\t%s"" % (chrom, self.pos, self.id, self.ref, self.alt)) + else: + print(""%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s"" % (chrom, self.pos, self.id, self.ref, self.alt, + self.qual, self.filter, info_print_format, + self.format, calls_print_format)) + + def intake_info(self, info): + fields = info.split(';') + for f in fields: + try: + key, value = f.split(""="") + self.info[key] = value + except: + pass + + def format_info(self): + output = [] + if len(self.info) == 0: + return ""."" + for key, value in self.info.items(): + output.append(""%s=%s"" % (key, value)) + + + return "";"".join(output) + + def add_info(self, key, value): + self.info[key] = value + + def add_allele(self, new): + if new == self.alt: + return + self.alt += "",%s"" % new + + def make_multiallelic(self, new_vcf): + self.add_allele(new_vcf.alt) + # add the info + for i in new_vcf.info: + self.add_info(i, new_vcf.info[i]) + # update the genotypes + for i in range(len(new_vcf.calls)): + if ""/"" in new_vcf.calls[i]: + alleles = new_vcf.calls[i].split(""/"") + elif ""|"" in new_vcf.calls[i]: + alleles = new_vcf.calls[i].split(""|"") + else: + print(""Unrecognized delimiter!"") + print(new_vcf.calls[i]) + exit() + + alt_found = False + + n_alts = str(len(self.alts())) + + if alleles[0] == '1': + alleles[0] = n_alts + alt_found = True + if alleles[1] == '1': + alleles[1] = n_alts + alt_found = True + if alt_found: + self.calls[i] = ""/"".join(alleles) + + def alts(self): + return self.alt.split("","") + + def is_multiallelic(self): + if len(self.alts()) == 1: + return False + return True + + def max_insertion(self): + max_insert = 1 + for a in self.alts(): + if len(a) > max_insert: + max_insert = len(a) + return max_insert + + def is_indel(self): + if len(self.ref) > 1 or len(self.alt) > 1: + return True + return False + + row = VCFfields() + row.chrom = fields[CHROM] + row.pos = int(fields[POS]) + row.id = fields[ID] + row.ref = fields[REF] + row.alt = fields[ALT] + row.qual = fields[QUAL] + row.filter = fields[FILTER] + row.intake_info(fields[INFO]) + if len(fields) > 8: + row.format = fields[FORMAT] + row.calls = fields[calls:] + return row + +''' +Read a VCF and return the subject IDs +''' +def get_vcf_subject_ids(vcf): + ids = [] + with smart_open(vcf) as f: + for line in f: + try: + line = byte_decoder(line) + except: + line = line + if line.startswith(""#CHROM""): + fields = line.rstrip().split() + ids = fields[9:] + break + return ids + + +''' +Detect if a file is gzipped before opening. If it is open with gzip, otherwise open normally. +''' +def smart_open(file): + if file.endswith('gz'): + import gzip + return gzip.open(file) + return open(file) + +''' +Decode byte data into utf-8 +''' +def byte_decoder(a): + return a.decode(""utf-8"") + + +''' +Split a genotype string into an array +''' +def split_genotype(gt): + gt = gt.split("":"")[0] + if ""/"" in gt: + alleles = gt.split(""/"") + return alleles + elif ""|"" in gt: + alleles = gt.split(""|"") + return alleles + print(""Unrecognized delimiter! %s"" % gt, file=sys.stderr) + gt = [None, None] + return gt + +''' +Check if a file is phased +''' +def vcf_is_phased(vcf): + with smart_open(vcf) as f: + for line in f: + try: + line = byte_decoder(line) + except: + line = line + if line.startswith(""#""): + continue + vcfline = parse_vcf_line(line) + + complete = False + index = 0 + while not complete: + gt = vcfline.calls[0].split(':')[index] + if ""|"" in gt: + f.close() + return True + elif ""/"" in gt: + f.close() + return False + elif index > len(vcfline.calls): + complete = True + else: + index += 1 + + # If we went through all the genotypes and haven't figure it out, there is something wrong. + print(""Phasing status could not be determined. VCF may be corrupted."") + exit(1) + +''' +Check if a single genotype call is phased. e.g. 0/1 vs 0|1. +''' +def is_gt_phased(gt): + if ""/"" in gt: + return False + if ""|"" in gt: + return True + # otherwise I don't know, so we'll say false + return False + +''' +Determine if a VCF encodes chromosome names with ""chr"" preceding the chromosome number. +''' +def chr_string(vcf): + with smart_open(vcf) as f: + for line in f: + try: + line = byte_decoder(line) + except: + line = line + if line.startswith(""#""): + continue + if line.startswith(""chr""): + f.close() + return True + else: + f.close() + return False + +''' +Query a VCF using tabix to extract the row for a particular variant. +Performs lots of QC checks to make sure that the retrieved variant is the same as the one requested. +''' +def fetch_genotypes(vcf, variant, synonym=None): + tb = tabix.open(vcf) + + # Check whether the chromosomes start with 'chr' or not + chr_represenation = chr_string(vcf) + if chr_represenation: + chr = variant.chromosome + else: + chr = variant.clean_chromosome + + # synonym is just an alternate position that the variant may be at. This is common for INDELs. + if synonym is not None: + position = synonym + + else: + position = variant.position + + records = tb.query(""%s"" % chr, position-1, position+1) + + n_records = 0 + for r in records: + n_records += 1 + + if n_records > 1: + strict = True + else: + strict = False + + records = tb.query(""%s"" % chr, position - 1, position + 1) + + for r in records: + + # Check that we fetched the right thing + valid = True + + # gt_index will store the index of the matched alternate allele + gt_index = None + + # Check if the chromosome is the same + if r[0] != chr: + valid = False + + if variant.rsid != r[2] and strict is True: + continue + + # Check if the position is the same + if str(r[1]) != str(position): + valid = False + + # Check if the reference variant is the same + if r[3] != variant.ref: + valid = False + + # Check whether the specified alternate allele is in the alts list + any_alt = False + + found_alts = r[4].split("","") + + for alt in found_alts: + if alt in variant.alt: + gt_index = found_alts.index(alt) + any_alt = True + + if r[3] == variant.ref: + valid = True + + if valid is False: + # Check if it's an INDEL + for a in variant.alt: + # Check the case where the alt is a deletion + if a.startswith(""del""): + # Check if any alt listed satisfies the deletion + satisfied, index = del_checker(a, r) + if satisfied is True: + valid = True + gt_index = index + + # Check the case where it is an insertion + elif len(a) > 1: + satisfied, index = ins_checker(a, r) + if satisfied is True: + valid = True + gt_index = index + + # I know this is duplicatd but it works. The last one wasn't catching cases where a single nucleotide was + # added + if variant.type == ""INS"": + for a in variant.alt: + satisfied, index = ins_checker(a, r) + if satisfied is True: + valid = True + gt_index = index + + + if variant.rsid == r[2]: + # if the IDs match then nothing else matters + # This will especially catch INDELs with different conventions for ref and alt representation + valid = True + + if valid is True: + data = parse_vcf_line(r) + # If there is only one alternate allele in the definition, set the index + if len(variant.alt) == 1: + data.gt_index = gt_index + return data + + # Recursively try any synonyms - not actually recursive + if synonym is not None: + for pos in variant.synonyms: + syn_result = fetch_genotypes(vcf, variant, pos) + if syn_result is not None: + return syn_result + + + return None + +''' +Check that an insertion identified in a file is the same as one specified in the definition file. +''' +def ins_checker(original, query): + # I'm not sure this will work for all insertion representations + # Basically what I'm doing is adding the added nucleotides from the definition to the ref allele and checking + # If that matches the listed alternate. + # I'm sure there will be exceptions to take care of at some point. + index = 0 + for alt in query[4].split("",""): + if alt == query[3] + original: + return True, index + index += 1 + return False, None + +''' +Check that an deletion identified in a file is the same as one specified in the definition file. +''' +def del_checker(original, query): + # This checks the difference between the ref and the alt and checks if that matches the deletion stated in the + # definition file. + deleted_nts = original.strip(""del"") + ref = query[3] + index = 0 + for alt in query[4].split("",""): + if alt in ref: + diff_nts = ref.replace(alt, '', 1) + if diff_nts == deleted_nts: + return True, index + index += 1 + + return False, None + +# Deprecated function used for something else. Will delete. +def fetch_genotype_records(vcf, chromosome, position, ref=None, alt=None): + tb = tabix.open(vcf) + records = tb.query(""%s"" % chromosome, position - 1, position + 1) + for r in records: + # todo add some additional checks here + # Otherwise check if there is an rsid, if there is check that it matches the variant file + # If not just check the position and the alternate alleles + # If it is an indel, try to match but it might not + if r[1] == str(position): + data = parse_vcf_line(r) + # position didn't match + return data + return None + +# Deprecated function used for something else. Will delete. +def fetch_genotypes_2(vcf, variant, synonym=None): + tb = tabix.open(vcf) + + # Check whether the chromosomes start with 'chr' or not + chr_represenation = chr_string(vcf) + if chr_represenation: + chr = variant.chrom + else: + chr = variant.clean_chromosome + + # synonym is just an alternate position that the variant may be at. This is common for INDELs. + if synonym is not None: + position = synonym + + else: + position = variant.pos + + records = tb.query(""%s"" % chr, position-1, position+1) + + n_records = 0 + for r in records: + n_records += 1 + + if n_records > 1: + strict = True + else: + strict = False + + records = tb.query(""%s"" % chr, position - 1, position + 1) + + for r in records: + #print(""Record!"") + # todo add some additional checks here + # Otherwise check if there is an rsid, if there is check that it matches the variant file + # If not just check the position and the alternate alleles + # If it is an indel, try to match but it might not + + # Check that we fetched the right thing + valid = True + + # gt_index will store the index of the matched alternate allele + gt_index = None + + if r[0] != chr: + #print(""Chromosome didn't match"") + valid = False + + if variant.id != r[2] and strict is True: + continue + + if str(r[1]) != str(position): + valid = False + continue + #if variant.rsid != r[2] and strict is True: + # continue + + if r[3] != variant.ref: + #print(""Ref didnt' match"") + continue + #valid = False + #if variant.rsid != r[2] and strict is True: + # continue + + #if variant.position == 42130655: + # print(""*15!!!!"") + + any_alt = False + #print(r[4]) + + found_alts = r[4].split("","") + + for alt in found_alts: + if alt in variant.alts(): + #gt_index = variant.alt.index(alt) + gt_index = found_alts.index(alt) + #print(""GT index: %s "" % gt_index) + #print(""Found alt %s in %s"" % (alt, variant.alts())) + any_alt = True + + if r[3] == variant.ref: + valid = True + + + + + if any_alt is False: + #print(""Alt didn't match"") + #print(found_alts) + valid = False + continue + + + + #if valid is False: + # # Check if it's an INDEL + # # todo put this in it's own function + # for a in variant.alt: + # # Check the case where the alt is a deletion + # if a.startswith(""del""): + # # Check if any alt listed satisfies the deletion + # satisfied, index = del_checker(a, r) + # if satisfied is True: + # valid = True + # gt_index = index +# + # # Check the case where it is an insertion + # elif len(a) > 1: + # satisfied, index = ins_checker(a, r) + # if satisfied is True: + # valid = True + # gt_index = index +# + # # I know this is duplicatd but it works. The last one wasn't catching cases where a single nucleotide was + # # added + # if variant.is_indel: + # for a in variant.alt: + # satisfied, index = ins_checker(a, r) + # if satisfied is True: + # valid = True + # gt_index = index +# + + # todo add other exceptions where necessary + + if variant.id != ""."" and variant.id == r[2]: + + # if the IDs match then nothing else matters + # This will especially catch INDELs with different conventions for ref and alt representation + #if valid == False: + valid = True + + if valid is True: + #print(""found"") + data = parse_vcf_line(r) + # If there is only one alternate allele in the definition, set the index + if len(variant.alt) == 1: + data.gt_index = gt_index + return data + + # Recursively try any synonyms - not actually recursive + if synonym is not None: + for pos in variant.synonyms: + syn_result = fetch_genotypes(vcf, variant, pos) + if syn_result is not None: + return syn_result + + return None + +''' +Sometimes multiple nucleotides ban be found at a position and have the same function. In this case +rather than representing them as multiple letters they can be collapsed into a single letter. For example +R is used to represent any purine, so the site could be an A or a G. This function will map a nucleotide to +it's IUPAC definition and return a list of nucleotides it could be. +''' + +def iupac_nt(nt): + nts = { + ""A"": [""A""], + ""C"": [""C""], + ""T"": [""T""], + ""G"": [""G""], + ""W"": [""A"", ""T""], + ""S"": [""C"", ""G""], + ""M"": [""A"", ""C""], + ""K"": [""G"", ""T""], + ""R"": [""A"", ""G""], + ""Y"": [""C"", ""T""], + ""B"": [""C"", ""G"", ""T""], + ""D"": [""A"", ""G"", ""T""], + ""H"": [""A"", ""C"", ""T""], + ""V"": [""A"", ""C"", ""G""], + ""N"": [""A"", ""C"", ""G"", ""T""], + ""Z"": [] + } + + if nt in nts.keys(): + return nts[nt] + + return [nt] + +''' +Fetch the allele definition file for a particular gene +''' +def get_definition_file(g): + definition_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), ""../definition/alleles/"") + filename = ""%s_translation.json"" % g + definition_file = os.path.join(definition_dir, filename) + return definition_file + +''' +Split a genotype from a VCF into a list +''' +def gt_splitter(gt): + gt = gt.split(':')[0] + if ""/"" in gt: + alleles = gt.split(""/"") + elif ""|"" in gt: + alleles = gt.split(""|"") + else: + alleles = None + return alleles + + +'''' +Print a nice welcome message. Hello! +''' +def welcome_message(): + message = ''' + + ________________________________________ + | ___ ___ ___ ___ ___ | + | | _ \/ __|_ _| _ \/\ \| _ \ | + | | _/ (_ \ \ / _/ \ | _/ | + | |_| \___/_\_\_| \__\/|_| | + | | + | v1.0 | + | Written by | + | Adam Lavertu and Greg McInnes | + | with help from PharmGKB. | + |________________________________________| + +Copyright (C) 2020 Stanford University. +Distributed under the Mozilla Public License 2.0 open source license. + ''' + + print(message, file=sys.stderr) +","Python" +"Pharmacogenetics","Helix-Research-Lab/PGxPOP","bin/Phenotype.py",".py","5750","182",""""""" +Greg McInes +Altman Lab +gmcinnes@stanford.edu +"""""" + +import json +import os +import sys + +''' +Define the Phenotype object + +This class will perform all functions related to retrieving phenotypes for gene diplotypes +''' +class Phenotype(object): + def __init__(self, json_file=None, debug=False): + + # Set global variables + self.data = None + self.debug = debug + + self._load_json(json_file) + + def _load_json(self, json_file): + if json_file is None: + json_file = self.default_json_file() + with open(json_file) as f: + self.data = json.load(f) + f.close() + + def default_json_file(self): + definition_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), ""../definition/"") + filename = ""gene.phenotypes.json"" + phenotype_file = os.path.join(definition_dir, filename) + return phenotype_file + + def get_gene(self, gene_name): + for g in self.data: + if g[""gene""] == gene_name: + return g + return None + + def get_haplotype_function(self, gene_name, hap): + # Determine the function of a single haplotype + gene = self.get_gene(gene_name) + if gene is None: + return ""Not available"" + if hap in gene[""haplotypes""].keys(): + return gene[""haplotypes""][hap] + return ""Not available"" + + def get_presumptive_haplotype_function(self, gene_name, hap): + + # Determine the function of a combination of haplotypes (+ calls) + gene = self.get_gene(gene_name) + if gene is None: + return None + + split_haps = hap.split(""+"") + + if len(split_haps) == 1: + return self.get_haplotype_function(gene_name, hap) + + if gene_name == ""CFTR"": + return self.CFTR_presumptive(split_haps) + + minimum_function = ""Not available"" + + min_functions = [""No Function"", ""Loss of function""] + if gene_name in [""UGT1A1"", ""SLCO1B1""]: + min_functions.append(""Decreased Function"") + + for h in split_haps: + f = self.get_haplotype_function(gene_name, h) + + if f in min_functions: + minimum_function = f + + return minimum_function + + def CFTR_presumptive(self, split_haps): + any_responsive = True + + for h in split_haps: + f = self.get_haplotype_function(""CFTR"", h) + if f == ""ivacaftor responsive"": + any_responsive = False + + if any_responsive is True: + return ""ivacaftor responsive"" + else: + return ""Not available"" + + def function_rank(self): + functions = { + ""No function"": 0, + ""Loss of function"": 0, + ""Decreased function"": 1, + ""Probable Decreased Function"": 2, + ""Possible Decreased function"": 2, + ""Normal function"": 3, + ""Increased function"": 4 + + } + + return functions + + def get_diplotype_function(self, gene_name, hap1, hap2, presumptive=False): + + # Haplotypes with equal scores will now be output as H1A;H1B, so we'll split those + # and check the function of each separately. If they have the same function, we + # can assign the function. If it is different, then we will report ""Conflicting"" + + + # Determine the function of two haplotypes for a given gene + hap1_function = self.haplotype_checker(gene_name, hap1, presumptive) + hap2_function = self.haplotype_checker(gene_name, hap2, presumptive) + + + if hap1_function is None or hap2_function is None: + return None + + if hap1_function == ""Not available"" or hap2_function == ""Not available"": + return ""Not available"" + + + if hap1_function == ""Conflicting"" or hap2_function == ""Conflicting"": + return ""Conflicting"" + + hap_functions = sorted([hap1_function, hap2_function]) + + # Next we need to iterate over the list of diplotypes and do a list comparison + gene = self.get_gene(gene_name) + for d in gene['diplotypes']: + if sorted(d['diplotype']) == hap_functions: + return d['phenotype'] + print('Unable to determine function of %s and %s for %s' % (hap1, hap2, gene_name), file=sys.stderr) + return ""Not available"" + + def haplotype_checker(self, gene_name, hap, presumptive=False): + found_functions = set() + for h in hap.split("";""): + if presumptive is True: + found_functions.add(self.get_presumptive_haplotype_function(gene_name, h)) + else: + found_functions.add(self.get_haplotype_function(gene_name, h)) + if len(found_functions) > 1: + return ""Conflicting"" + return list(found_functions)[0] + + def get_activity_score(self, gene_name, hap1, hap2, presumptive=False): + + hap1_as = self.get_hap_activity_score(gene_name, hap1, presumptive) + hap2_as = self.get_hap_activity_score(gene_name, hap2, presumptive) + + if None in [hap1_as, hap2_as]: + return None + + return hap1_as + hap2_as + + def get_hap_activity_score(self, gene_name, hap, presumptive=False): + gene = self.get_gene(gene_name) + + if gene is None: + return None + + if ""haplotype_as"" not in list(gene.keys()): + return None + + if not presumptive: + if hap in list(gene['haplotype_as'].keys()): + return gene['haplotype_as'][hap] + else: + return None + + else: + if hap in list(gene['haplotype_as'].keys()): + return gene['haplotype_as'][hap] + if self.get_presumptive_haplotype_function(gene_name, hap) == ""No Function"": + return 0 +","Python" +"Pharmacogenetics","Helix-Research-Lab/PGxPOP","bin/RareVariantCaller.py",".py","6065","209",""""""" +Greg McInes +Altman Lab +gmcinnes@stanford.edu +"""""" + +from DawgToys import parse_vcf_line, get_vcf_subject_ids, get_definition_file, gt_splitter +from Gene import Gene +import argparse +import sys +import os +import tabix + +class RareVariantCaller(object): + def __init__(self, vcf, gene, build='grch38', debug=False): + self.vcf = vcf + self.gene = gene + self.build = build + self.debug = debug + + def run(self): + if self.debug: + print(""Extracting rare variants in %s"" % self.gene.name) + + # Get the bed regions for the gene + regions = self.coding_regions() + + if regions is None: + return None + + # Get the variants from the definition file for this gene + rare_variants = self.get_rare_variants(regions[self.gene.name]) + + return rare_variants + + def get_rare_variants(self, regions): + + # Create dictionary to store results + sample_variants = {} + subjects = get_vcf_subject_ids(self.vcf) + for s in subjects: + sample_variants[s] = [] + + known_vars = self.known_variants() + + # For each region, extract all the variants + for r in regions: + variants, keys = self.get_region_variants(r, exclude=known_vars) + + for i in range(len(variants)): + vcf_row = parse_vcf_line(variants[i]) + for j in range(len(subjects)): + s = subjects[j] + gt = vcf_row.calls[j].split(':')[0] + + # If the genotype contains any alternate allele, store it + # For best performance SNPs should be split across multiple rows in the VCF + # Otherwise it won't be possible to decipher multiallelic sites + if '1' in gt or '2' in gt or '3' in gt: + + sample_variants[s].append(keys[i]) + + return sample_variants + + def known_variants(self): + variants = [] + + for v in self.gene.variants: + chrom = self.gene.variants[v].chromosome + pos = self.gene.variants[v].position + ref = self.gene.variants[v].ref + + for a in self.gene.variants[v].alt: + key = ""%s_%s_%s_%s"" % (chrom, pos, ref, a) + variants.append(key) + + return variants + + def coding_regions(self): + + regions = {} + + wd = os.path.dirname(os.path.realpath(__file__)) + + if self.build == ""grch38"": + bed = os.path.join(wd, ""../definition/exome_target_regions.bed"") + elif self.build == 'hg19': + bed = os.path.join(wd, ""../definition/exome_target_regions.hg19.bed"") + else: + print(""Build %s not supported for rare variant discovery."") + return None + + with open(bed) as f: + for line in f: + fields = line.rstrip().split() + chrom = fields[0] + start = int(fields[1]) + end = int(fields[2]) + gene = fields[3] + + if not gene in regions: + regions[gene] = [] + + r = {""chr"": chrom, + ""start"": start, + ""end"": end, + ""gene"": gene} + + regions[gene].append(r) + + return regions + + def get_region_variants(self, region, exclude=None): + + variant_records = [] + keys = [] + + chrom = region[""chr""] + start = region[""start""] + end = region[""end""] + + tb = tabix.open(self.vcf) + + records = tb.query(""%s"" % chrom, start, end) + + n_records = 0 + for r in records: + n_records += 1 + + c = r[0] + p = r[1] + ref = r[3] + alt = r[4] + + if alt != ""."": + + if exclude is not None: + alts = alt.split("","") + for a in alts: + main_key = ""%s_%s_%s_%s"" % (c, p, ref, a) + + # SNP + if len(ref) == len(a): + + key = ""%s_%s_%s_%s"" % (c, p, ref, a) + if key not in exclude: + variant_records.append(r) + keys.append(main_key) + + # Deletion + elif len(ref) > len(a): + + deletion = ref[len(a):] + + + key = ""%s_%s_%s_del%s"" % (c, p, deletion, deletion) + + if key not in exclude: + variant_records.append(r) + keys.append(main_key) + + + + # Insertion + elif len(ref) < len(a): + insertion = a[len(ref):] + key = ""%s_%s_ins_%s"" % (c, p, insertion) + + if key not in exclude: + variant_records.append(r) + keys.append(main_key) + + else: + alts = alt.split("","") + for a in alts: + main_key = ""%s_%s_%s_%s"" % (c, p, ref, a) + variant_records.append(r) + keys.append(main_key) + + + + return variant_records, keys + +"""""" +Parse the command line +"""""" +def parse_command_line(): + parser = argparse.ArgumentParser( + description = 'This is a script I wrote') + parser.add_argument(""-f"", ""--file"", help=""Input"") + parser.add_argument(""-g"", ""--gene"", help=""Input"") + + parser.add_argument(""-d"", ""--debug"", action='store_true', default=False, + help=""Output debugging messages. May be very verbose."") + options = parser.parse_args() + return options + + +"""""" +Main +"""""" +if __name__ == ""__main__"": + options = parse_command_line() + gene = Gene(get_definition_file(options.gene)) + caller = RareVariantCaller(vcf=options.file, gene=gene, debug=options.debug) + variants = caller.run() + print(variants) + +","Python" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/PlatinumMain.java",".java","4597","105","package com.hartwig.platinum; + +import static java.lang.String.format; + +import java.util.concurrent.Callable; + +import com.google.cloud.storage.StorageOptions; +import com.hartwig.platinum.config.PlatinumConfiguration; +import com.hartwig.platinum.config.Validation; +import com.hartwig.platinum.config.version.PipelineVersion; +import com.hartwig.platinum.config.version.VersionCompatibility; +import com.hartwig.platinum.kubernetes.ContainerProvider; +import com.hartwig.platinum.kubernetes.JobSubmitter; +import com.hartwig.platinum.kubernetes.KubernetesClientProxy; +import com.hartwig.platinum.kubernetes.KubernetesEngine; +import com.hartwig.platinum.kubernetes.ProcessRunner; +import com.hartwig.platinum.pdl.PDLConversion; +import com.hartwig.platinum.scheduling.JobScheduler; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.fabric8.kubernetes.client.DefaultKubernetesClient; +import picocli.CommandLine; +import picocli.CommandLine.Option; + +public class PlatinumMain implements Callable { + private static final Logger LOGGER = LoggerFactory.getLogger(PlatinumMain.class); + private static final String MIN_PV5_VERSION = ""5.33.8""; + private static final String MAX_PV5_VERSION = VersionCompatibility.UNLIMITED; + + @Option(names = { ""-n"" }, + required = true, + description = ""The name of the run, used in output bucket and cluster naming"") + private String runName; + + @Option(names = { ""-i"" }, + required = true, + description = ""JSON or YAML file that contains arguments to be passed to the pipeline jobs and a list of samples"") + private String inputJson; + + @Option(names = { ""-p"" }, + description = ""The GCP Project ID (not name!) where we'll run the pipelines."") + private String project; + + @Option(names = { ""-r"" }, + description = ""The GCP Region where we'll run the pipelines."") + private String region; + + @Override + public Integer call() { + try { + PlatinumConfiguration configuration = addRegionAndProject(PlatinumConfiguration.from(inputJson)); + Validation.apply(runName, configuration); + + new VersionCompatibility(MIN_PV5_VERSION, MAX_PV5_VERSION, new PipelineVersion()).check(configuration.image()); + + String clusterName = configuration.cluster().orElse(runName); + KubernetesClientProxy kubernetesClientProxy = + new KubernetesClientProxy(clusterName, configuration.gcp(), new DefaultKubernetesClient()); + JobSubmitter jobSubmitter = new JobSubmitter(kubernetesClientProxy, configuration.retryFailed()); + JobScheduler jobScheduler = JobScheduler.fromConfiguration(configuration, jobSubmitter, kubernetesClientProxy); + + new Platinum(runName, + inputJson, + StorageOptions.newBuilder().setProjectId(configuration.gcp().projectOrThrow()).build().getService(), + new KubernetesEngine(ContainerProvider.get(), new ProcessRunner(), configuration, jobScheduler, kubernetesClientProxy), + configuration, + PDLConversion.create(configuration)).run(); + return 0; + } catch (Exception e) { + LOGGER.error(""Unexpected exception"", e); + return 1; + } + } + + public PlatinumConfiguration addRegionAndProject(PlatinumConfiguration configuration) { + configuration = addRegion(configuration); + configuration = addProject(configuration); + return configuration; + } + + private PlatinumConfiguration addRegion(final PlatinumConfiguration configuration) { + if (configuration.gcp().region().isPresent() && region != null) { + throw new IllegalArgumentException(""Region cannot be specified in both JSON input and CLI. Choose one or the other""); + } else if (region != null) { + return configuration.withGcp(configuration.gcp().withRegion(region)); + } + return configuration; + } + + private PlatinumConfiguration addProject(final PlatinumConfiguration configuration) { + if (configuration.gcp().project().isPresent() && project != null) { + throw new IllegalArgumentException(""Project cannot be specified in both JSON input and CLI. Choose one or the other""); + } else if (project != null) { + return configuration.withGcp(configuration.gcp().withProject(project)); + } + return configuration; + } + + public static void main(String[] args) { + System.exit(new CommandLine(new PlatinumMain()).execute(args)); + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/Platinum.java",".java","2359","56","package com.hartwig.platinum; + +import static com.hartwig.platinum.Console.bold; + +import java.util.List; +import java.util.function.Supplier; + +import com.google.cloud.storage.Storage; +import com.hartwig.pdl.PipelineInput; +import com.hartwig.platinum.config.PlatinumConfiguration; +import com.hartwig.platinum.config.version.PipelineVersion; +import com.hartwig.platinum.config.version.VersionCompatibility; +import com.hartwig.platinum.kubernetes.KubernetesEngine; +import com.hartwig.platinum.pdl.PDLConversion; +import com.hartwig.platinum.storage.OutputBucket; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class Platinum { + + private static final Logger LOGGER = LoggerFactory.getLogger(Platinum.class); + private final String runName; + private final String input; + private final Storage storage; + private final KubernetesEngine kubernetesEngine; + private final PlatinumConfiguration configuration; + private final PDLConversion pdlConversion; + + public Platinum(final String runName, final String input, final Storage storage, final KubernetesEngine clusterProvider, + final PlatinumConfiguration configuration, final PDLConversion pdlConversion) { + this.runName = runName; + this.input = input; + this.storage = storage; + this.kubernetesEngine = clusterProvider; + this.configuration = configuration; + this.pdlConversion = pdlConversion; + } + + public void run() { + LOGGER.info(""Starting Platinum run with name {} and input {}"", bold(runName), bold(input)); + String clusterName = configuration.cluster().orElse(runName); + + List> pipelineInputs = pdlConversion.apply(configuration); + PlatinumResult result = kubernetesEngine.findOrCreate(clusterName, + runName, + pipelineInputs, + OutputBucket.from(storage).findOrCreate(runName, configuration.gcp().regionOrThrow(), configuration)).submit(); + LOGGER.info(""Platinum started {} pipelines on GCP"", bold(String.valueOf(result.numSuccess()))); + if (result.numFailure() > 0) { + LOGGER.info(""{} pipelines failed on submission, see previous messages"", bold(String.valueOf(result.numFailure()))); + } + LOGGER.info(""You can monitor their progress with: {}"", bold(""./platinum status"")); + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/ApiRerun.java",".java","2729","71","package com.hartwig.platinum; + +import static java.lang.String.format; + +import com.hartwig.ApiException; +import com.hartwig.api.RunApi; +import com.hartwig.api.SetApi; +import com.hartwig.api.helpers.OnlyOne; +import com.hartwig.api.model.CreateRun; +import com.hartwig.api.model.Ini; +import com.hartwig.api.model.Run; +import com.hartwig.api.model.SampleSet; +import com.hartwig.api.model.SampleType; +import com.hartwig.api.model.Status; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ApiRerun { + + private static final Logger LOGGER = LoggerFactory.getLogger(ApiRerun.class); + + private final RunApi runApi; + private final SetApi setApi; + private final String bucket; + private final String version; + + public ApiRerun(final RunApi runApi, final SetApi setApi, final String bucket, final String version) { + this.runApi = runApi; + this.setApi = setApi; + this.bucket = bucket; + this.version = version; + } + + public long create(final String tumorSampleName) { + try { + SampleSet set = setApi.canonical(tumorSampleName, SampleType.TUMOR); + return getOrCreateRun(tumorSampleName, set); + } catch (ApiException e) { + throw new IllegalArgumentException(format(""No sets with consent for the database could be found for [%s]"", tumorSampleName)); + } catch (IllegalStateException e) { + LOGGER.error(""Failed to get or create run for [{}]"", tumorSampleName); + throw e; + } + } + + /** + * @return Run ID, never null but the openAPI generated classes are limited. + */ + private Long getOrCreateRun(final String tumorSampleName, final SampleSet sampleSet) { + return OnlyOne.ofNullable(runApi.callList(null, Ini.RERUN_INI, sampleSet.getId(), version, version, null, null, null, null), Run.class) + .filter(r -> !r.getStatus().equals(Status.INVALIDATED)) + .map(r -> { + LOGGER.info(""Using existing run for sample [{}] id [{}]"", tumorSampleName, r.getId()); + return r.getId(); + }) + .orElseGet(() -> { + final Long id = runApi.create(new CreateRun().bucket(bucket) + .cluster(""gcp"") + .context(""RESEARCH"") + .ini(Ini.RERUN_INI) + .version(version) + .status(Status.PENDING) + .isHidden(true) + .setId(sampleSet.getId())).getId(); + LOGGER.info(""Created API run for sample [{}] id [{}]"", tumorSampleName, id); + return id; + }); + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/Console.java",".java","266","11","package com.hartwig.platinum; + +public class Console { + private static final String RESET = ""\033[0m""; + private static final String BLACK_BOLD = ""\033[1;30m""; + + public static String bold(final String text) { + return BLACK_BOLD + text + RESET; + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/PlatinumResult.java",".java","346","16","package com.hartwig.platinum; + +import org.immutables.value.Value; + +@Value.Immutable +public interface PlatinumResult { + + int numSuccess(); + + int numFailure(); + + static PlatinumResult of(final int successes, final int failures) { + return ImmutablePlatinumResult.builder().numSuccess(successes).numFailure(failures).build(); + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/iam/ServiceAccountName.java",".java","163","9","package com.hartwig.platinum.iam; + +public class ServiceAccountName { + + static String from(final String runName) { + return ""platinum-"" + runName; + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/iam/ServiceAccountId.java",".java","223","9","package com.hartwig.platinum.iam; + +public class ServiceAccountId { + + static String from(final String project, final String email) { + return String.format(""projects/%s/serviceAccounts/%s"", project, email); + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/iam/ResourceManagerProvider.java",".java","1166","28","package com.hartwig.platinum.iam; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.Collections; + +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; +import com.google.api.client.json.jackson2.JacksonFactory; +import com.google.api.services.cloudresourcemanager.CloudResourceManager; +import com.google.api.services.cloudresourcemanager.CloudResourceManagerScopes; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; + +public class ResourceManagerProvider { + + public static CloudResourceManager get() { + try { + return new CloudResourceManager.Builder(GoogleNetHttpTransport.newTrustedTransport(), + JacksonFactory.getDefaultInstance(), + new HttpCredentialsAdapter(GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(CloudResourceManagerScopes.CLOUD_PLATFORM)))).setApplicationName(""platinum"") + .build(); + } catch (IOException | GeneralSecurityException e) { + throw new RuntimeException(e); + } + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/iam/PipelineIamPolicy.java",".java","2009","45","package com.hartwig.platinum.iam; + +import java.io.IOException; +import java.util.List; + +import com.google.api.services.cloudresourcemanager.CloudResourceManager; +import com.google.api.services.cloudresourcemanager.model.Binding; +import com.google.api.services.cloudresourcemanager.model.GetIamPolicyRequest; +import com.google.api.services.cloudresourcemanager.model.Policy; +import com.google.api.services.cloudresourcemanager.model.SetIamPolicyRequest; +import com.google.api.services.iam.v1.model.ServiceAccount; +import com.google.cloud.Identity; + +public class PipelineIamPolicy { + + static final String COMPUTE_ADMIN = ""roles/compute.admin""; + static final String STORAGE_ADMIN = ""roles/storage.admin""; + static final String SERVICE_ACCOUNT_USER = ""roles/iam.serviceAccountUser""; + private final CloudResourceManager cloudResourceManager; + + public PipelineIamPolicy(final CloudResourceManager cloudResourceManager) { + this.cloudResourceManager = cloudResourceManager; + } + + void apply(final ServiceAccount serviceAccount) { + try { + Policy existingPolicy = + cloudResourceManager.projects().getIamPolicy(serviceAccount.getProjectId(), new GetIamPolicyRequest()).execute(); + existingPolicy.getBindings() + .addAll(List.of(binding(serviceAccount, COMPUTE_ADMIN), + binding(serviceAccount, STORAGE_ADMIN), + binding(serviceAccount, SERVICE_ACCOUNT_USER))); + cloudResourceManager.projects() + .setIamPolicy(serviceAccount.getProjectId(), new SetIamPolicyRequest().setPolicy(existingPolicy)) + .execute(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private static Binding binding(final ServiceAccount serviceAccount, final String role) { + return new Binding().setRole(role).setMembers(List.of(Identity.serviceAccount(serviceAccount.getEmail()).strValue())); + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/iam/IamProvider.java",".java","1020","27","package com.hartwig.platinum.iam; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.Collections; + +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; +import com.google.api.client.json.jackson2.JacksonFactory; +import com.google.api.services.iam.v1.Iam; +import com.google.api.services.iam.v1.IamScopes; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; + +public class IamProvider { + + public static Iam get() { + try { + return new Iam.Builder(GoogleNetHttpTransport.newTrustedTransport(), + JacksonFactory.getDefaultInstance(), + new HttpCredentialsAdapter(GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM)))).setApplicationName(""platinum"").build(); + } catch (IOException | GeneralSecurityException e) { + throw new RuntimeException(e); + } + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/pdl/PDLConversion.java",".java","1592","38","package com.hartwig.platinum.pdl; + +import java.util.List; +import java.util.function.Supplier; + +import com.hartwig.api.HmfApi; +import com.hartwig.pdl.PipelineInput; +import com.hartwig.pdl.generator.PdlGenerator; +import com.hartwig.platinum.ApiRerun; +import com.hartwig.platinum.config.PlatinumConfiguration; + +public interface PDLConversion { + + List> apply(final PlatinumConfiguration configuration); + + static PDLConversion create(final PlatinumConfiguration configuration) { + return configuration.hmfConfiguration().map(hmfConfiguration -> { + HmfApi api = HmfApi.create(hmfConfiguration.apiUrl()); + PdlGenerator pdlGenerator = PdlGenerator.forResearch(api); + if (hmfConfiguration.isRerun()) { + return new ConvertForRerun(pdlGenerator, + new ApiRerun(api.runs(), + api.sets(), + configuration.outputBucket() + .orElseThrow(() -> new IllegalArgumentException( + ""Cannot execute a rerun without a configured outputBucket in the platinum configuration"")), + extractVersion(configuration.image()))); + } else { + return new ConvertForBiopsies(api.runs(), api.samples(), api.sets(), pdlGenerator); + } + }).orElse(new ConvertFromGCSPaths()); + } + + private static String extractVersion(final String imageName) { + return imageName.split("":"")[1].split(""-"")[0]; + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/pdl/ConvertFromGCSPaths.java",".java","5035","114","package com.hartwig.platinum.pdl; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import com.hartwig.pdl.LaneInput; +import com.hartwig.pdl.PipelineInput; +import com.hartwig.pdl.SampleInput; +import com.hartwig.platinum.config.FastqConfiguration; +import com.hartwig.platinum.config.PlatinumConfiguration; +import com.hartwig.platinum.config.RawDataConfiguration; +import com.hartwig.platinum.config.SampleConfiguration; + +public class ConvertFromGCSPaths implements PDLConversion { + + public static final int GCP_VM_LIMIT = 55; + + public List> apply(final PlatinumConfiguration configuration) { + List> pairs = new ArrayList<>(); + for (SampleConfiguration sample : configuration.samples()) { + if (sample.name().length() >= GCP_VM_LIMIT) { + throw new IllegalArgumentException( + ""Platinum can only support sample names up to "" + GCP_VM_LIMIT + "" characters. Please shorten the sample "" + + ""name (this name will not be used for file naming or in any headers)""); + } + boolean indexTumors = sample.tumors().size() > 1; + int tumorIndex = 1; + if (!sample.tumors().isEmpty()) { + for (RawDataConfiguration tumor : sample.tumors()) { + final int tumorIndexReadOnly = tumorIndex; + if (tumor.bam().isPresent()) { + pairs.add(() -> PipelineInput.builder() + .reference(sample.normal().map(ConvertFromGCSPaths::createReferenceInput)) + .tumor(SampleInput.builder() + .name(tumor.name()) + .turquoiseSubject(tumor.name()) + .bam(tumor.bam()) + .primaryTumorDoids(sample.primaryTumorDoids()) + .build()) + .setName(indexTumors ? sample.name() + ""-t"" + tumorIndexReadOnly : sample.name()) + .build()); + } else { + + pairs.add(() -> PipelineInput.builder() + .reference(sample.normal().map(ConvertFromGCSPaths::createReferenceInput)) + .tumor(SampleInput.builder() + .name(tumor.name()) + .turquoiseSubject(tumor.name()) + .lanes(toLanes(tumor.fastq())) + .primaryTumorDoids(sample.primaryTumorDoids()) + .build()) + .setName(indexTumors ? sample.name() + ""-t"" + tumorIndexReadOnly : sample.name()) + .build()); + } + tumorIndex++; + } + } else if (sample.normal().isPresent()) { + pairs.add(() -> PipelineInput.builder() + .reference(sample.normal().map(ConvertFromGCSPaths::createReferenceInput)) + .setName(sample.name()) + .build()); + } + } + return pairs; + } + + private static SampleInput createReferenceInput(final RawDataConfiguration normal) + { + if (normal.bam().isPresent()) { + return createReferenceBamInput(normal); + } else { + return createReferenceFastqInput(normal); + } + } + + private static SampleInput createReferenceBamInput(final RawDataConfiguration normal) + { + return SampleInput.builder() + .name(normal.name()) + .turquoiseSubject(normal.name()) + .bam(normal.bam()) + .build(); + } + + private static SampleInput createReferenceFastqInput(final RawDataConfiguration normal) + { + return SampleInput.builder() + .name(normal.name()) + .turquoiseSubject(normal.name()) + .lanes(toLanes(normal.fastq())) + .build(); + } + + private static List toLanes(final List referenceFastq) { + return IntStream.rangeClosed(1, referenceFastq.size()) + .boxed() + .map(i -> Map.entry(String.valueOf(i), referenceFastq.get(i - 1))) + .map(e -> LaneInput.builder() + .laneNumber(e.getKey()) + .firstOfPairPath(stripGs(e.getValue().read1())) + .secondOfPairPath(stripGs(e.getValue().read2())) + .build()) + .collect(Collectors.toList()); + } + + private static String stripGs(final String maybeWithGs) { + return maybeWithGs.replace(""gs://"", """"); + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/pdl/ConvertForBiopsies.java",".java","2116","50","package com.hartwig.platinum.pdl; + +import java.util.Comparator; +import java.util.List; +import java.util.Optional; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +import com.hartwig.api.RunApi; +import com.hartwig.api.SampleApi; +import com.hartwig.api.SetApi; +import com.hartwig.api.model.Ini; +import com.hartwig.api.model.Run; +import com.hartwig.api.model.SampleType; +import com.hartwig.api.model.Status; +import com.hartwig.pdl.ImmutablePipelineInput; +import com.hartwig.pdl.PipelineInput; +import com.hartwig.pdl.generator.PdlGenerator; +import com.hartwig.platinum.config.PlatinumConfiguration; + +public class ConvertForBiopsies implements PDLConversion { + + private final RunApi runApi; + private final SampleApi sampleApi; + private final SetApi setApi; + private final PdlGenerator pdlGenerator; + + public ConvertForBiopsies(final RunApi runApi, final SampleApi sampleApi, final SetApi setApi, final PdlGenerator pdlGenerator) { + this.runApi = runApi; + this.sampleApi = sampleApi; + this.setApi = setApi; + this.pdlGenerator = pdlGenerator; + } + + @Override + public List> apply(final PlatinumConfiguration configuration) { + return configuration.sampleIds() + .stream() + .flatMap(biopsy -> sampleApi.callList(null, null, null, null, SampleType.TUMOR, biopsy, null).stream()) + .flatMap(sample -> setApi.callList(null, null, sample.getId(), null, null, true).stream()) + .flatMap(set -> runApi.callList(Status.VALIDATED, Ini.SOMATIC_INI, set.getId(), null, null, null, null, ""RESEARCH"", null) + .stream() + .filter(run -> run.getEndTime() != null) + .max(Comparator.comparing(Run::getEndTime)) + .map(run -> (Supplier) () -> ImmutablePipelineInput.copyOf(pdlGenerator.generate(run.getId())) + .withOperationalReferences(Optional.empty())) + .stream()) + .collect(Collectors.toList()); + } +}","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/pdl/ConvertForRerun.java",".java","950","29","package com.hartwig.platinum.pdl; + +import java.util.List; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +import com.hartwig.pdl.PipelineInput; +import com.hartwig.pdl.generator.PdlGenerator; +import com.hartwig.platinum.ApiRerun; +import com.hartwig.platinum.config.PlatinumConfiguration; + +public class ConvertForRerun implements PDLConversion { + + private final PdlGenerator generator; + private final ApiRerun apiRerun; + + public ConvertForRerun(final PdlGenerator generator, final ApiRerun apiRerun) { + this.generator = generator; + this.apiRerun = apiRerun; + } + + @Override + public List> apply(final PlatinumConfiguration configuration) { + return configuration.sampleIds() + .stream() + .map(sampleId -> (Supplier) () -> generator.generate(apiRerun.create(sampleId))) + .collect(Collectors.toList()); + } +}","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/kubernetes/KubernetesEngine.java",".java","8990","169","package com.hartwig.platinum.kubernetes; + +import static java.time.Duration.ofMinutes; +import static java.time.Duration.ofSeconds; + +import java.io.IOException; +import java.util.List; +import java.util.Optional; +import java.util.function.Supplier; + +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.services.container.Container; +import com.google.api.services.container.Container.Projects.Locations.Clusters.Create; +import com.google.api.services.container.Container.Projects.Locations.Clusters.Get; +import com.google.api.services.container.model.Cluster; +import com.google.api.services.container.model.CreateClusterRequest; +import com.google.api.services.container.model.IPAllocationPolicy; +import com.google.api.services.container.model.NodeConfig; +import com.google.api.services.container.model.NodePool; +import com.google.api.services.container.model.Operation; +import com.google.api.services.container.model.PrivateClusterConfig; +import com.hartwig.pdl.PipelineInput; +import com.hartwig.platinum.Console; +import com.hartwig.platinum.config.BatchConfiguration; +import com.hartwig.platinum.config.GcpConfiguration; +import com.hartwig.platinum.config.PlatinumConfiguration; +import com.hartwig.platinum.kubernetes.pipeline.PipelineConfigMapBuilder; +import com.hartwig.platinum.kubernetes.pipeline.PipelineConfigMapVolume.PipelineConfigMapVolumeBuilder; +import com.hartwig.platinum.scheduling.JobScheduler; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.jodah.failsafe.Failsafe; +import net.jodah.failsafe.RetryPolicy; + +public class KubernetesEngine { + private static final Logger LOGGER = LoggerFactory.getLogger(KubernetesEngine.class); + private final Container containerApi; + private final ProcessRunner processRunner; + private final PlatinumConfiguration configuration; + private final JobScheduler jobScheduler; + private final KubernetesClientProxy kubernetesClientProxy; + + public KubernetesEngine(final Container containerApi, final ProcessRunner processRunner, final PlatinumConfiguration configuration, + final JobScheduler jobScheduler, final KubernetesClientProxy kubernetesClientProxy) { + this.containerApi = containerApi; + this.processRunner = processRunner; + this.configuration = configuration; + this.jobScheduler = jobScheduler; + this.kubernetesClientProxy = kubernetesClientProxy; + } + + private static String fullPath(final String project, final String region, final String cluster) { + return String.format(""projects/%s/locations/%s/clusters/%s"", project, region, cluster); + } + + private static void create(final Container containerApi, final String parent, final String cluster, + final GcpConfiguration gcpConfiguration) { + try { + Cluster newCluster = new Cluster(); + newCluster.setName(cluster); + newCluster.setNetwork(gcpConfiguration.networkUrl()); + newCluster.setSubnetwork(gcpConfiguration.subnetUrl()); + newCluster.setLocations(gcpConfiguration.zones()); + NodePool defaultNodePool = new NodePool().setName(""default"").setInitialNodeCount(2); + final NodeConfig nodeConfig = new NodeConfig().setPreemptible(gcpConfiguration.preemptibleCluster()) + .setOauthScopes(List.of(""https://www.googleapis.com/auth/cloud-platform"")) + .setDiskSizeGb(500); + if (!gcpConfiguration.networkTags().isEmpty()) { + nodeConfig.setTags(gcpConfiguration.networkTags()); + } + defaultNodePool.setConfig(nodeConfig); + newCluster.setNodePools(List.of(defaultNodePool)); + + IPAllocationPolicy ipAllocationPolicy = new IPAllocationPolicy(); + if (gcpConfiguration.privateCluster()) { + PrivateClusterConfig privateClusterConfig = new PrivateClusterConfig(); + privateClusterConfig.setEnablePrivateEndpoint(true); + privateClusterConfig.setEnablePrivateNodes(true); + privateClusterConfig.setMasterIpv4CidrBlock(gcpConfiguration.masterIpv4CidrBlock()); + newCluster.setPrivateClusterConfig(privateClusterConfig); + ipAllocationPolicy.setUseIpAliases(true); + } + if (gcpConfiguration.secondaryRangeNamePods().isPresent() && gcpConfiguration.secondaryRangeNameServices().isPresent()) { + ipAllocationPolicy.setClusterSecondaryRangeName(gcpConfiguration.secondaryRangeNamePods().get()); + ipAllocationPolicy.setServicesSecondaryRangeName(gcpConfiguration.secondaryRangeNameServices().get()); + } + newCluster.setIpAllocationPolicy(ipAllocationPolicy); + + CreateClusterRequest createRequest = new CreateClusterRequest(); + createRequest.setCluster(newCluster); + Create created = containerApi.projects().locations().clusters().create(parent, createRequest); + Operation execute = created.execute(); + LOGGER.info(""Creating new kubernetes cluster {} in project {} and region {}, this can take upwards of 5 minutes..."", + Console.bold(newCluster.getName()), + Console.bold(gcpConfiguration.projectOrThrow()), + Console.bold(gcpConfiguration.regionOrThrow())); + Failsafe.with(new RetryPolicy<>().withMaxDuration(ofMinutes(15)) + .withDelay(ofSeconds(15)) + .withMaxAttempts(-1) + .handleResult(null) + .handleResult(""RUNNING"")) + .onFailure(objectExecutionCompletedEvent -> LOGGER.info(""Waiting on operation, status is [{}]"", + objectExecutionCompletedEvent.getResult())) + .get(() -> containerApi.projects() + .locations() + .operations() + .get(String.format(""projects/%s/locations/%s/operations/%s"", + gcpConfiguration.projectOrThrow(), + gcpConfiguration.regionOrThrow(), + execute.getName())) + .execute() + .getStatus()); + } catch (Exception e) { + throw new RuntimeException(""Failed to create cluster"", e); + } + } + + private Optional find(final String path) throws IOException { + try { + Get found = containerApi.projects().locations().clusters().get(path); + return Optional.of(found.execute()); + } catch (GoogleJsonResponseException e) { + return Optional.empty(); + } + } + + public KubernetesCluster findOrCreate(final String clusterName, final String runName, + final List> pipelineInputs, final String outputBucketName) { + try { + GcpConfiguration gcpConfiguration = configuration.gcp(); + String parent = String.format(""projects/%s/locations/%s"", gcpConfiguration.projectOrThrow(), gcpConfiguration.regionOrThrow()); + if (find(fullPath(gcpConfiguration.projectOrThrow(), gcpConfiguration.regionOrThrow(), clusterName)).isEmpty()) { + create(containerApi, parent, clusterName, gcpConfiguration); + } + if (!configuration.inCluster()) { + kubernetesClientProxy.authorise(); + LOGGER.info(""Connection to cluster {} configured via gcloud and kubectl"", Console.bold(clusterName)); + } + + TargetNodePool targetNodePool = configuration.gcp() + .nodePoolConfiguration() + .map(c -> TargetNodePool.fromConfig(c, + configuration.batch() + .map(BatchConfiguration::size) + .orElse(configuration.samples().isEmpty() + ? configuration.sampleIds().size() + : configuration.samples().size()))) + .orElse(TargetNodePool.defaultPool()); + if (!targetNodePool.isDefault()) { + new GcloudNodePool(processRunner).create(targetNodePool, + configuration.serviceAccount().gcpEmailAddress(), + clusterName, + gcpConfiguration.projectOrThrow()); + } + return new KubernetesCluster(runName, + jobScheduler, + pipelineInputs, + new PipelineConfigMapBuilder(new PipelineConfigMapVolumeBuilder(kubernetesClientProxy), runName), + outputBucketName, + configuration, + targetNodePool); + } catch (Exception e) { + throw new RuntimeException(""Failed to create cluster"", e); + } + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/kubernetes/KubernetesCluster.java",".java","4308","89","package com.hartwig.platinum.kubernetes; + +import static java.util.stream.Collectors.toList; +import static java.util.stream.Stream.concat; +import static java.util.stream.Stream.of; + +import java.time.Duration; +import java.util.List; +import java.util.function.Supplier; + +import com.hartwig.pdl.PipelineInput; +import com.hartwig.pdl.SampleInput; +import com.hartwig.platinum.PlatinumResult; +import com.hartwig.platinum.config.PlatinumConfiguration; +import com.hartwig.platinum.kubernetes.pipeline.PipelineArguments; +import com.hartwig.platinum.kubernetes.pipeline.PipelineConfigMapBuilder; +import com.hartwig.platinum.kubernetes.pipeline.PipelineContainer; +import com.hartwig.platinum.kubernetes.pipeline.PipelineJob; +import com.hartwig.platinum.kubernetes.pipeline.SampleArgument; +import com.hartwig.platinum.scheduling.JobScheduler; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.fabric8.kubernetes.api.model.Volume; + +public class KubernetesCluster { + public final static String NAMESPACE = ""default""; + private final static Logger LOGGER = LoggerFactory.getLogger(KubernetesCluster.class); + private final String runName; + private final JobScheduler scheduler; + private final List> pipelineInputs; + private final PipelineConfigMapBuilder configMaps; + private final String outputBucketName; + private final PlatinumConfiguration configuration; + private final TargetNodePool targetNodePool; + + KubernetesCluster(final String runName, final JobScheduler scheduler, final List> pipelineInputs, + final PipelineConfigMapBuilder configMaps, final String outputBucketName, final PlatinumConfiguration configuration, + final TargetNodePool targetNodePool) { + this.runName = runName.toLowerCase(); + this.scheduler = scheduler; + this.pipelineInputs = pipelineInputs; + this.configMaps = configMaps; + this.outputBucketName = outputBucketName; + this.configuration = configuration; + this.targetNodePool = targetNodePool; + } + + public PlatinumResult submit() { + Volume maybeJksVolume = new JksSecret().asKubernetes(); + int numSubmitted = 0; + int failures = 0; + for (Supplier inputSupplier : pipelineInputs) { + try { + PipelineInput pipelineInput = inputSupplier.get(); + String sampleName = pipelineInput.tumor() + .or(pipelineInput::reference) + .map(SampleInput::name) + .orElseThrow(() -> new IllegalArgumentException(""At least one tumor or reference sample must be provided"")); + SampleArgument sample = SampleArgument.sampleJson(sampleName, runName); + Volume configMapVolume = configMaps.forSample(sampleName, pipelineInput); + PipelineContainer pipelineContainer = new PipelineContainer(sample, + new PipelineArguments(configuration.argumentOverrides(), + outputBucketName, + configuration.serviceAccount().gcpEmailAddress(), + configuration), + configMapVolume.getName(), + configuration.image(), + configuration); + + scheduler.submit(new PipelineJob(sampleName + ""-"" + runName, + configuration.keystorePassword() + .map(p -> new JksEnabledContainer(pipelineContainer.asKubernetes(), maybeJksVolume, p).asKubernetes()) + .orElse(pipelineContainer.asKubernetes()), + concat(of(configMapVolume), configuration.keystorePassword().map(p -> maybeJksVolume).stream()).collect(toList()), + configuration.serviceAccount().kubernetesServiceAccount(), + targetNodePool, + configuration.gcp().jobTtl().orElse(Duration.ZERO))); + numSubmitted++; + } catch (Exception e) { + LOGGER.warn(""Unexpected failure, skipping further processing of sample"", e); + failures++; + } + } + return PlatinumResult.of(numSubmitted, failures); + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/kubernetes/TargetNodePool.java",".java","1455","63","package com.hartwig.platinum.kubernetes; + +import com.hartwig.platinum.config.NodePoolConfiguration; + +public interface TargetNodePool { + + boolean isDefault(); + + String name(); + + String machineType(); + + int numNodes(); + + static TargetNodePool fromConfig(final NodePoolConfiguration configuration, final int samples) { + return new TargetNodePool() { + @Override + public boolean isDefault() { + return false; + } + + @Override + public String name() { + return configuration.name(); + } + + @Override + public String machineType() { + return ""e2-medium""; + } + + @Override + public int numNodes() { + return Math.max(1, samples / 10); + } + }; + } + + static TargetNodePool defaultPool() { + return new TargetNodePool() { + @Override + public boolean isDefault() { + return true; + } + + @Override + public String name() { + throw new UnsupportedOperationException(); + } + + @Override + public String machineType() { + throw new UnsupportedOperationException(); + } + + @Override + public int numNodes() { + throw new UnsupportedOperationException(); + } + }; + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/kubernetes/KubernetesClientProxy.java",".java","4520","116","package com.hartwig.platinum.kubernetes; + +import static java.util.List.of; + +import java.util.Map; + +import javax.inject.Provider; + +import com.hartwig.platinum.config.GcpConfiguration; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.fabric8.kubernetes.api.model.ConfigMapBuilder; +import io.fabric8.kubernetes.api.model.ConfigMapList; +import io.fabric8.kubernetes.api.model.ServiceAccount; +import io.fabric8.kubernetes.api.model.ServiceAccountList; +import io.fabric8.kubernetes.api.model.Volume; +import io.fabric8.kubernetes.api.model.VolumeBuilder; +import io.fabric8.kubernetes.api.model.batch.v1.Job; +import io.fabric8.kubernetes.api.model.batch.v1.JobList; +import io.fabric8.kubernetes.client.DefaultKubernetesClient; +import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.KubernetesClientException; +import io.fabric8.kubernetes.client.dsl.MixedOperation; +import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; +import io.fabric8.kubernetes.client.dsl.Resource; +import io.fabric8.kubernetes.client.dsl.ScalableResource; +import io.fabric8.kubernetes.client.dsl.ServiceAccountResource; + +public class KubernetesClientProxy { + private static final Logger LOGGER = LoggerFactory.getLogger(KubernetesClientProxy.class); + private final String clusterName; + private final String region; + private final String project; + private KubernetesClient kubernetesClient; + + public KubernetesClientProxy(String clusterName, GcpConfiguration gcpConfiguration, KubernetesClient kubernetesClient) { + this.clusterName = clusterName; + this.region = gcpConfiguration.regionOrThrow(); + this.project = gcpConfiguration.projectOrThrow(); + this.kubernetesClient = kubernetesClient; + authorise(); + } + + public MixedOperation> configMaps() { + return executeWithRetries(() -> kubernetesClient.configMaps()); + } + + public Volume ensureConfigMapVolumeExists(String volumeName, Map configMapContents) { + try { + configMaps().inNamespace(KubernetesCluster.NAMESPACE) + .withName(volumeName) + .createOrReplace(new ConfigMapBuilder() + .addToData(configMapContents) + .withNewMetadata() + .withName(volumeName) + .withNamespace(KubernetesCluster.NAMESPACE) + .endMetadata() + .build()); + return new VolumeBuilder() + .withName(volumeName) + .editOrNewConfigMap() + .withName(volumeName) + .endConfigMap() + .build(); + } catch (KubernetesClientException e) { + authorise(); + return ensureConfigMapVolumeExists(volumeName, configMapContents); + } + } + + public NonNamespaceOperation> jobs() { + try { + return kubernetesClient.batch().jobs().inNamespace(KubernetesCluster.NAMESPACE); + } catch (KubernetesClientException e) { + authorise(); + return jobs(); + } + } + + private MixedOperation executeWithRetries(Provider> operationProvider) { + try { + return operationProvider.get(); + } catch (KubernetesClientException e) { + authorise(); + return executeWithRetries(operationProvider); + } + } + + public MixedOperation serviceAccounts() { + return kubernetesClient.serviceAccounts(); + } + + public void authorise() { + LOGGER.info(""Authorising with cluster""); + ProcessRunner processRunner = new ProcessRunner(); + if (!processRunner.execute(of(""gcloud"", + ""container"", + ""clusters"", + ""get-credentials"", + clusterName, + ""--region"", + region, + ""--project"", + project))) { + throw new RuntimeException(""Failed to get credentials for cluster""); + } + if (!processRunner.execute(of(""kubectl"", ""get"", ""nodes""))) { + throw new RuntimeException(""Failed to run kubectl command against cluster""); + } + kubernetesClient = new DefaultKubernetesClient(); + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/kubernetes/KubernetesComponent.java",".java","109","7","package com.hartwig.platinum.kubernetes; + +public interface KubernetesComponent { + + T asKubernetes(); +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/kubernetes/JksSecret.java",".java","377","12","package com.hartwig.platinum.kubernetes; + +import io.fabric8.kubernetes.api.model.Volume; +import io.fabric8.kubernetes.api.model.VolumeBuilder; + +public class JksSecret implements KubernetesComponent { + @Override + public Volume asKubernetes() { + return new VolumeBuilder().withName(""jks"").editOrNewSecret().withSecretName(""jks"").endSecret().build(); + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/kubernetes/JobSubmitter.java",".java","2693","71","package com.hartwig.platinum.kubernetes; + +import static com.hartwig.platinum.kubernetes.KubernetesCluster.NAMESPACE; + +import com.hartwig.platinum.kubernetes.pipeline.PipelineJob; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.fabric8.kubernetes.api.model.batch.v1.Job; +import io.fabric8.kubernetes.api.model.batch.v1.JobBuilder; +import io.fabric8.kubernetes.api.model.batch.v1.JobSpec; + +public class JobSubmitter { + + private static final Logger LOGGER = LoggerFactory.getLogger(JobSubmitter.class); + private static final String JOB_COMPLETE_STATUS = ""Complete""; + private static final String JOB_FAILED_STATUS = ""Failed""; + + private final KubernetesClientProxy kubernetesClientProxy; + private final boolean retryFailed; + + public JobSubmitter(final KubernetesClientProxy kubernetesClientProxy, boolean retryFailed) { + this.kubernetesClientProxy = kubernetesClientProxy; + this.retryFailed = retryFailed; + } + + public boolean submit(final PipelineJob job) { + JobSpec spec = job.asKubernetes(); + Job existing = kubernetesClientProxy.jobs().withName(job.getName()).get(); + if (existing == null) { + submit(job, spec); + return true; + } else if (jobIs(existing, JOB_COMPLETE_STATUS)) { + LOGGER.info(""Job [{}] existed and completed successfully, skipping"", job.getName()); + return false; + } else if (jobIs(existing, JOB_FAILED_STATUS)) { + if (retryFailed) { + LOGGER.info(""Job [{}] existed but failed, restarting"", job.getName()); + kubernetesClientProxy.jobs().delete(existing); + submit(job, spec); + return true; + } else { + LOGGER.info(""Job [{}] existed but failed, skipping"", job.getName()); + return false; + } + } else { + LOGGER.info(""Job [{}] is already running"", job.getName()); + return true; + } + } + + private void submit(final PipelineJob job, final JobSpec spec) { + kubernetesClientProxy.jobs() + .create(new JobBuilder().withNewMetadata() + .withName(job.getName()) + .withNamespace(NAMESPACE) + .endMetadata() + .withSpec(spec) + .build()); + LOGGER.info(""Submitted [{}]"", job.getName()); + } + + public static boolean jobIs(Job job, String stateName) { + return job.getStatus() + .getConditions() + .stream() + .anyMatch(c -> stateName.equalsIgnoreCase(c.getType()) && ""True"".equals(c.getStatus())); + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/kubernetes/GcloudNodePool.java",".java","1601","43","package com.hartwig.platinum.kubernetes; + +import static java.lang.String.format; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class GcloudNodePool { + + private static final Logger LOGGER = LoggerFactory.getLogger(GcloudNodePool.class); + + private final ProcessRunner processRunner; + + public GcloudNodePool(final ProcessRunner processRunner) { + this.processRunner = processRunner; + } + + void create(final TargetNodePool targetNodePool, final String serviceAccount, final String clusterName, final String project) { + LOGGER.info(""Creating new node pool with name [{}] machine type [{}] and [{}] nodes"", + targetNodePool.name(), + targetNodePool.machineType(), + targetNodePool.numNodes()); + List arguments = List.of(""gcloud"", + ""container"", + ""node-pools"", + ""create"", + targetNodePool.name(), + ""--cluster="" + clusterName, + ""--machine-type="" + targetNodePool.machineType(), + ""--node-labels=pool="" + targetNodePool.name(), + ""--node-taints=reserved-pool=true:NoSchedule"", + ""--num-nodes="" + targetNodePool.numNodes(), + ""--region=europe-west4"", + ""--project="" + project, + ""--service-account="" + serviceAccount); + if (!processRunner.execute(arguments)) { + throw new RuntimeException(format(""Failed to create node pool via command: [%s]"", String.join("" "", arguments))); + } + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/kubernetes/ProcessRunner.java",".java","693","24","package com.hartwig.platinum.kubernetes; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ProcessRunner { + private static final Logger LOGGER = LoggerFactory.getLogger(ProcessRunner.class); + + boolean execute(List arguments) { + ProcessBuilder processBuilder = new ProcessBuilder(arguments); + try { + LOGGER.debug(""Starting [{}]"", arguments); + Process process = processBuilder.start(); + process.waitFor(); + return process.exitValue() == 0; + } catch (Exception e) { + LOGGER.warn(""Unable to run [{}]"", arguments, e); + return false; + } + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/kubernetes/ContainerProvider.java",".java","1046","27","package com.hartwig.platinum.kubernetes; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.Set; + +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; +import com.google.api.client.json.jackson2.JacksonFactory; +import com.google.api.services.container.Container; +import com.google.api.services.container.ContainerScopes; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; + +public class ContainerProvider { + + public static Container get() { + try { + return new Container.Builder(GoogleNetHttpTransport.newTrustedTransport(), + JacksonFactory.getDefaultInstance(), + new HttpCredentialsAdapter(GoogleCredentials.getApplicationDefault() + .createScoped(Set.of(ContainerScopes.CLOUD_PLATFORM)))).setApplicationName(""platinum"").build(); + } catch (GeneralSecurityException | IOException e) { + throw new RuntimeException(e); + } + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/kubernetes/KubernetesUtil.java",".java","637","19","package com.hartwig.platinum.kubernetes; + +public final class KubernetesUtil { + public static String toValidRFC1123Label(String... input) { + String label = String.join(""-"", input).replaceAll(""[_\\s]+"", ""-"").toLowerCase(); + + if (label.length() > 63) { + throw new IllegalArgumentException(""Label is too long: "" + label); + } + + String labelRegex = ""[a-z0-9]([-a-z0-9]*[a-z0-9])?""; + if (!label.matches(labelRegex)) { + throw new IllegalArgumentException(String.format(""Invalid label: \""%s\"", should follow regex: \""%s\"""", label, labelRegex)); + } + + return label; + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/kubernetes/JksEnabledContainer.java",".java","1168","30","package com.hartwig.platinum.kubernetes; + +import java.util.List; + +import io.fabric8.kubernetes.api.model.Container; +import io.fabric8.kubernetes.api.model.ContainerBuilder; +import io.fabric8.kubernetes.api.model.EnvVar; +import io.fabric8.kubernetes.api.model.Volume; +import io.fabric8.kubernetes.api.model.VolumeMountBuilder; + +public class JksEnabledContainer implements KubernetesComponent { + + private final Container wrapped; + private final Volume jksVolume; + private final String keystorePassword; + + public JksEnabledContainer(final Container wrapped, final Volume jksVolume, final String keystorePassword) { + this.wrapped = wrapped; + this.jksVolume = jksVolume; + this.keystorePassword = keystorePassword; + } + + @Override + public Container asKubernetes() { + return new ContainerBuilder(wrapped).withEnv(List.of(new EnvVar(""JAVA_OPTS"", + String.format(""-Djavax.net.ssl.keyStore=/jks/api.jks -Djavax.net.ssl.keyStorePassword=%s"", keystorePassword), + null))).addToVolumeMounts(new VolumeMountBuilder().withMountPath(""/jks"").withName(jksVolume.getName()).build()).build(); + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/kubernetes/pipeline/PipelineArguments.java",".java","3398","77","package com.hartwig.platinum.kubernetes.pipeline; + +import static java.lang.String.format; + +import static com.hartwig.platinum.config.OverrideableArguments.of; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import com.google.common.collect.ImmutableMap; +import com.hartwig.platinum.config.GcpConfiguration; +import com.hartwig.platinum.config.PlatinumConfiguration; + +public class PipelineArguments { + + private final Map overrides; + private final String outputBucket; + private final String serviceAccountEmail; + private final PlatinumConfiguration platinumConfiguration; + + public PipelineArguments(final Map overrides, final String outputBucket, final String serviceAccountEmail, + final PlatinumConfiguration platinumConfiguration) { + this.overrides = addDashesIfNeeded(overrides); + checkForForbiddenOverrides(this.overrides); + this.outputBucket = outputBucket; + this.serviceAccountEmail = serviceAccountEmail; + this.platinumConfiguration = platinumConfiguration; + } + + public List asCommand(final SampleArgument sampleArgument) { + return of(Map.of(""-profile"", ""public"", ""-output_cram"", ""false"")).override(of(overrides)) + .override(of(sampleArgument.arguments())) + .override(of(fixed())) + .asCommand(""/pipeline5.sh""); + } + + private void checkForForbiddenOverrides(Map proposedOverrides) { + List.of(""-hmf_api_url"").forEach(forbidden -> { + if (proposedOverrides.containsKey(forbidden)) { + throw new IllegalArgumentException(format(""Override of pipeline5 argument [%s] is not allowed from Platinum"", forbidden)); + } + }); + } + + private Map addDashesIfNeeded(Map overrides) { + return overrides.entrySet() + .stream() + .collect(Collectors.toMap(e -> e.getKey().startsWith(""-"") ? e.getKey() : ""-"" + e.getKey(), Map.Entry::getValue)); + } + + private Map fixed() { + GcpConfiguration gcpConfiguration = platinumConfiguration.gcp(); + ImmutableMap.Builder builder = ImmutableMap.builder() + .put(""-output_bucket"", outputBucket) + .put(""-project"", gcpConfiguration.projectOrThrow()) + .put(""-region"", gcpConfiguration.regionOrThrow()) + .put(""-network"", gcpConfiguration.networkUrl()) + .put(""-subnet"", gcpConfiguration.subnetUrl()) + .put(""-service_account_email"", serviceAccountEmail); + if (!gcpConfiguration.networkTags().isEmpty()) { + builder.put(""-network_tags"", String.join("","", gcpConfiguration.networkTags())); + } + if (platinumConfiguration.hmfConfiguration().isPresent() && platinumConfiguration.hmfConfiguration().get().isRerun()) { + builder.put(""-profile"", ""production""); + builder.put(""-context"", ""RESEARCH""); + builder.put(""-hmf_api_url"", platinumConfiguration.hmfConfiguration().get().apiUrl()); + } else { + builder.put(""-context"", ""PLATINUM""); + } + if (platinumConfiguration.cmek().isPresent()) { + builder.put(""-cmek"", platinumConfiguration.cmek().get()); + } + return builder.build(); + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/kubernetes/pipeline/PipelineContainer.java",".java","2335","54","package com.hartwig.platinum.kubernetes.pipeline; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.hartwig.platinum.config.PlatinumConfiguration; +import com.hartwig.platinum.kubernetes.KubernetesComponent; +import com.hartwig.platinum.kubernetes.KubernetesUtil; + +import io.fabric8.kubernetes.api.model.Container; +import io.fabric8.kubernetes.api.model.Quantity; +import io.fabric8.kubernetes.api.model.ResourceRequirements; +import io.fabric8.kubernetes.api.model.VolumeMountBuilder; + +public class PipelineContainer implements KubernetesComponent { + private final static String SAMPLES_PATH = ""/samples""; + private final SampleArgument sample; + private final PipelineArguments arguments; + private final String configMapName; + private final String imageName; + private final PlatinumConfiguration configuration; + + public PipelineContainer(final SampleArgument sample, final PipelineArguments arguments, final String configMapName, + final String imageName, final PlatinumConfiguration configuration) { + this.sample = sample; + this.arguments = arguments; + this.configMapName = configMapName; + this.imageName = imageName; + this.configuration = configuration; + } + + @Override + public Container asKubernetes() { + Container container = new Container(); + container.setImage(imageName); + container.setName(KubernetesUtil.toValidRFC1123Label(sample.id())); + List command = arguments.asCommand(sample); + container.setCommand(command); + container.setVolumeMounts(List.of(new VolumeMountBuilder().withMountPath(SAMPLES_PATH).withName(configMapName).build())); + final ResourceRequirements resourceRequirements = new ResourceRequirements(); + final Map resources = new HashMap<>(); + if (configuration.samples().isEmpty() && configuration.sampleBucket().isEmpty()) { + resources.putAll(Map.of(""cpu"", new Quantity(""100m""), ""memory"", new Quantity(""512Mi""))); + } else { + resources.put(""memory"", new Quantity(""1024Mi"")); + } + resourceRequirements.setLimits(resources); + resourceRequirements.setRequests(resources); + container.setResources(resourceRequirements); + return container; + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/kubernetes/pipeline/PipelineConfigMapBuilder.java",".java","909","23","package com.hartwig.platinum.kubernetes.pipeline; + +import com.hartwig.pdl.PdlJsonConversion; +import com.hartwig.pdl.PipelineInput; +import com.hartwig.platinum.kubernetes.pipeline.PipelineConfigMapVolume.PipelineConfigMapVolumeBuilder; + +import io.fabric8.kubernetes.api.model.Volume; + +public class PipelineConfigMapBuilder { + + private final PipelineConfigMapVolumeBuilder pipelineConfigMapVolumeBuilder; + private final String runName; + + public PipelineConfigMapBuilder(final PipelineConfigMapVolumeBuilder pipelineConfigMapVolumeBuilder, final String runName) { + this.pipelineConfigMapVolumeBuilder = pipelineConfigMapVolumeBuilder; + this.runName = runName; + } + + public Volume forSample(String sample, PipelineInput pipelineInput) { + return pipelineConfigMapVolumeBuilder.of(runName, sample, PdlJsonConversion.getInstance().serialize(pipelineInput)).asKubernetes(); + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/kubernetes/pipeline/SampleArgument.java",".java","540","21","package com.hartwig.platinum.kubernetes.pipeline; + +import java.util.Map; + +import org.immutables.value.Value; + +@Value.Immutable +public interface SampleArgument { + + String id(); + + Map arguments(); + + static SampleArgument sampleJson(final String sampleName, final String runName) { + return ImmutableSampleArgument.builder() + .id(sampleName) + .putArguments(""-sample_json"", ""samples/"" + sampleName) + .putArguments(""-run_tag"", runName) + .build(); + } +}","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/kubernetes/pipeline/PipelineConfigMapVolume.java",".java","1629","45","package com.hartwig.platinum.kubernetes.pipeline; + +import static java.lang.String.format; + +import static com.hartwig.platinum.kubernetes.KubernetesUtil.toValidRFC1123Label; + +import java.util.Map; + +import com.hartwig.platinum.kubernetes.KubernetesClientProxy; +import com.hartwig.platinum.kubernetes.KubernetesComponent; + +import io.fabric8.kubernetes.api.model.Volume; + +public class PipelineConfigMapVolume implements KubernetesComponent { + private final KubernetesClientProxy kubernetesClientProxy; + private final String volumeName; + private final String sample; + private final String content; + + private PipelineConfigMapVolume(final KubernetesClientProxy kubernetesClientProxy, final String runName, final String sample, + final String content) { + this.kubernetesClientProxy = kubernetesClientProxy; + this.volumeName = toValidRFC1123Label(format(""%s-%s"", runName, sample)); + this.sample = sample; + this.content = content; + } + + @Override + public Volume asKubernetes() { + return kubernetesClientProxy.ensureConfigMapVolumeExists(volumeName, Map.of(sample, content)); + } + + public static class PipelineConfigMapVolumeBuilder { + private final KubernetesClientProxy kubernetesClient; + + public PipelineConfigMapVolumeBuilder(final KubernetesClientProxy kubernetesClient) { + this.kubernetesClient = kubernetesClient; + } + + public PipelineConfigMapVolume of(String runName, String sample, String content) { + return new PipelineConfigMapVolume(kubernetesClient, runName, sample, content); + } + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/kubernetes/pipeline/PipelineJob.java",".java","2762","72","package com.hartwig.platinum.kubernetes.pipeline; + +import java.time.Duration; +import java.util.List; +import java.util.Map; + +import com.hartwig.platinum.kubernetes.KubernetesComponent; +import com.hartwig.platinum.kubernetes.KubernetesUtil; +import com.hartwig.platinum.kubernetes.TargetNodePool; + +import io.fabric8.kubernetes.api.model.Container; +import io.fabric8.kubernetes.api.model.PodTemplateSpecFluent; +import io.fabric8.kubernetes.api.model.Toleration; +import io.fabric8.kubernetes.api.model.Volume; +import io.fabric8.kubernetes.api.model.batch.v1.JobSpec; +import io.fabric8.kubernetes.api.model.batch.v1.JobSpecBuilder; +import io.fabric8.kubernetes.api.model.batch.v1.JobSpecFluent; + +public class PipelineJob implements KubernetesComponent { + + private final Container container; + private final List volumes; + private final String name; + private final String serviceAccountName; + private final TargetNodePool nodePool; + private final Duration ttl; + + public PipelineJob(final String name, final Container container, final List volumes, final String serviceAccountName, + final TargetNodePool nodePool, final Duration ttl) { + this.container = container; + this.volumes = volumes; + this.serviceAccountName = serviceAccountName; + this.nodePool = nodePool; + this.ttl = ttl; + this.name = KubernetesUtil.toValidRFC1123Label(name); + } + + public Container getContainer() { + return container; + } + + public String getName() { + return name; + } + + public List getVolumes() { + return volumes; + } + + @Override + public JobSpec asKubernetes() { + JobSpecBuilder jobSpecBuilder = new JobSpecBuilder(); + final PodTemplateSpecFluent.TemplateNested>.SpecNested.TemplateNested> + dsl = jobSpecBuilder.withNewTemplate() + .withNewSpec() + .withContainers(container) + .withRestartPolicy(""Never"") + .withVolumes(volumes) + .withServiceAccountName(serviceAccountName) + .withNodeSelector(Map.of(""iam.gke.io/gke-metadata-server-enabled"", ""true"")); + if (!nodePool.isDefault()) { + dsl.withNodeSelector(Map.of(""pool"", nodePool.name())) + .withTolerations(List.of(new Toleration(""NoSchedule"", ""reserved-pool"", ""Equal"", null, ""true""))); + } + JobSpec spec = dsl.endSpec().endTemplate().build(); + spec.setBackoffLimit(1); + if (!ttl.equals(Duration.ZERO)) { + spec.setTtlSecondsAfterFinished(Math.toIntExact(ttl.getSeconds())); + } + return spec; + } +}","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/scheduling/ConstantJobCountScheduler.java",".java","4280","101","package com.hartwig.platinum.scheduling; + +import java.util.ArrayList; +import java.util.List; + +import com.hartwig.platinum.kubernetes.JobSubmitter; +import com.hartwig.platinum.kubernetes.KubernetesClientProxy; +import com.hartwig.platinum.kubernetes.pipeline.PipelineJob; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.fabric8.kubernetes.api.model.batch.v1.Job; +import io.fabric8.kubernetes.client.KubernetesClientException; +import net.jodah.failsafe.Failsafe; +import net.jodah.failsafe.RetryPolicy; + +public class ConstantJobCountScheduler implements JobScheduler { + private static final Logger LOGGER = LoggerFactory.getLogger(ConstantJobCountScheduler.class); + private static final int INITIAL_LOGGING_INTERVAL_MILLISECONDS = 60 * 1000; + private final JobSubmitter jobSubmitter; + private final int jobCount; + private final List activeJobs; + private final KubernetesClientProxy kubernetesClientProxy; + private final Delay delayBetweenSubmissions; + private final Delay pollingInterval; + + private enum JobState { + COMPLETE, + FAILED + } + + public ConstantJobCountScheduler(final JobSubmitter jobSubmitter, final KubernetesClientProxy kubernetesClientProxy, final int jobCount, + final Delay delayBetweenSubmissions, final Delay pollingInterval) { + this.jobSubmitter = jobSubmitter; + this.kubernetesClientProxy = kubernetesClientProxy; + this.jobCount = jobCount; + this.delayBetweenSubmissions = delayBetweenSubmissions; + this.pollingInterval = pollingInterval; + + activeJobs = new ArrayList<>(); + } + + @Override + public void submit(final PipelineJob job) { + while (activeJobs.size() >= jobCount) { + List removedJobs = waitForCapacity(); + if (!removedJobs.isEmpty()) { + activeJobs.removeAll(removedJobs); + } + } + if (jobSubmitter.submit(job)) { + activeJobs.add(job); + delayBetweenSubmissions.threadSleep(); + } + } + + private boolean jobIs(Job job, JobState state) { + return JobSubmitter.jobIs(job, state.name()); + } + + private List waitForCapacity() { + List removedJobs = new ArrayList<>(); + if (activeJobs.size() >= jobCount) { + int millisecondsWaitedSoFar = 0; + while (activeJobs.size() - removedJobs.size() >= jobCount) { + for (PipelineJob activeJob : activeJobs) { + Failsafe.with(new RetryPolicy<>().handle(KubernetesClientException.class) + .withMaxRetries(2) + .onRetry(e -> kubernetesClientProxy.authorise())).run(() -> { + Job job = kubernetesClientProxy.jobs().withName(activeJob.getName()).get(); + if (job == null) { + LOGGER.warn(""Previously-created k8 job [{}] not found, will not schedule another in its place!"", + activeJob.getName()); + removedJobs.add(activeJob); + } else { + if (jobIs(job, JobState.FAILED)) { + kubernetesClientProxy.jobs().delete(job); + if (jobSubmitter.submit(activeJob)) { + LOGGER.info(""Resubmitted failed job [{}]"", activeJob.getName()); + } else { + removedJobs.add(activeJob); + } + } else if (jobIs(job, JobState.COMPLETE)) { + removedJobs.add(activeJob); + } + } + }); + } + pollingInterval.threadSleep(); + millisecondsWaitedSoFar += pollingInterval.toMillis(); + if (millisecondsWaitedSoFar >= INITIAL_LOGGING_INTERVAL_MILLISECONDS) { + LOGGER.info(""Maximum number of pipelines [{}] already running, waiting to submit more"", jobCount); + millisecondsWaitedSoFar = 0; + } + } + } + return removedJobs; + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/scheduling/Delay.java",".java","1392","59","package com.hartwig.platinum.scheduling; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class Delay { + + private static final Logger LOGGER = LoggerFactory.getLogger(Delay.class); + private final long delay; + private final Unit unit; + + public enum Unit { + MINUTES(1000 * 60), + SECONDS(1000), + MILLISECONDS(1); + + final long millisecondsPer; + + Unit(long millisecondsPer) { + this.millisecondsPer = millisecondsPer; + } + } + + private Delay(long delay, Unit unit) { + this.delay = delay; + this.unit = unit; + } + + static Delay forMinutes(final int minutes) { + return new Delay(minutes, Unit.MINUTES); + } + + static Delay forSeconds(final int seconds) { + return new Delay(seconds, Unit.SECONDS); + } + + static Delay forMilliseconds(final int milliseconds) { + return new Delay(milliseconds, Unit.MILLISECONDS); + } + + public void threadSleep() { + try { + Thread.sleep(toMillis()); + } catch (InterruptedException e) { + LOGGER.error(""Thread interupted"", e); + Thread.currentThread().interrupt(); + } + } + + public long toMillis() { + return delay * unit.millisecondsPer; + } + + @Override + public String toString() { + return String.format(""%d %s"", delay, unit.name().toLowerCase()); + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/scheduling/JobScheduler.java",".java","1410","31","package com.hartwig.platinum.scheduling; + +import com.hartwig.platinum.config.PlatinumConfiguration; +import com.hartwig.platinum.kubernetes.JobSubmitter; +import com.hartwig.platinum.kubernetes.KubernetesClientProxy; +import com.hartwig.platinum.kubernetes.pipeline.PipelineJob; + +public interface JobScheduler { + Delay DELAY_BETWEEN_SUBMISSIONS = Delay.forSeconds(1); + Delay POLLING_INTERVAL = Delay.forSeconds(10); + + static JobScheduler fromConfiguration(PlatinumConfiguration configuration, JobSubmitter jobSubmitter, + KubernetesClientProxy kubernetesClientProxy) { + return configuration.batch() + .map(c -> c.delay().isPresent() + ? new TimedBatchScheduler(jobSubmitter, Delay.forMinutes(c.delay().get()), c.size()) + : new ConstantJobCountScheduler(jobSubmitter, + kubernetesClientProxy, + c.size(), + JobScheduler.DELAY_BETWEEN_SUBMISSIONS, + JobScheduler.POLLING_INTERVAL)) + .orElse(new ConstantJobCountScheduler(jobSubmitter, + kubernetesClientProxy, + Integer.MAX_VALUE, + JobScheduler.DELAY_BETWEEN_SUBMISSIONS, + JobScheduler.POLLING_INTERVAL)); + } + + void submit(final PipelineJob job); +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/scheduling/TimedBatchScheduler.java",".java","1099","34","package com.hartwig.platinum.scheduling; + +import com.hartwig.platinum.kubernetes.JobSubmitter; +import com.hartwig.platinum.kubernetes.pipeline.PipelineJob; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Deprecated +public class TimedBatchScheduler implements JobScheduler { + private static final Logger LOGGER = LoggerFactory.getLogger(TimedBatchScheduler.class); + private final JobSubmitter jobSubmitter; + private final Delay delay; + private final int batchSize; + private int numSubmitted; + + public TimedBatchScheduler(final JobSubmitter jobSubmitter, final Delay delay, final int batchSize) { + this.jobSubmitter = jobSubmitter; + this.delay = delay; + this.batchSize = batchSize; + } + + @Override + public void submit(final PipelineJob job) { + if (jobSubmitter.submit(job)) { + numSubmitted++; + if (numSubmitted % batchSize == 0) { + LOGGER.info(""Batch [{}] scheduled, waiting [{}]"", (numSubmitted / batchSize), delay.toString()); + delay.threadSleep(); + } + } + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/storage/OutputBucket.java",".java","2168","51","package com.hartwig.platinum.storage; + +import com.google.cloud.Identity; +import com.google.cloud.Policy; +import com.google.cloud.storage.Bucket; +import com.google.cloud.storage.BucketInfo; +import com.google.cloud.storage.Storage; +import com.google.cloud.storage.StorageRoles; +import com.hartwig.platinum.Console; +import com.hartwig.platinum.config.PlatinumConfiguration; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class OutputBucket { + + private static final Logger LOGGER = LoggerFactory.getLogger(OutputBucket.class); + + private final Storage storage; + + private OutputBucket(final Storage storage) { + this.storage = storage; + } + + public static OutputBucket from(final Storage storage) { + return new OutputBucket(storage); + } + + public String findOrCreate(final String runName, final String region, final PlatinumConfiguration configuration) { + String bucketName = configuration.outputBucket().orElse(BucketName.from(runName)); + Bucket outputBucket = storage.get(bucketName); + if (outputBucket != null) { + LOGGER.info(""Bucket {} already existed, re-using it, if this is not a re-run of an existing experiment platinum will not have "" + + ""permission to write"", Console.bold(outputBucket.getName())); + } else { + outputBucket = storage.create(BucketInfo.newBuilder(bucketName) + .setIamConfiguration(BucketInfo.IamConfiguration.newBuilder().setIsUniformBucketLevelAccessEnabled(true).build()) + .setLocation(region) + .setDefaultKmsKeyName(configuration.cmek().orElse(null)) + .setAutoclass(BucketInfo.Autoclass.newBuilder().setEnabled(true).build()) + .build()); + Policy bucketPolicy = storage.getIamPolicy(bucketName); + storage.setIamPolicy(bucketName, + bucketPolicy.toBuilder() + .addIdentity(StorageRoles.admin(), Identity.serviceAccount(configuration.serviceAccount().gcpEmailAddress())) + .build()); + } + return outputBucket.getName(); + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/storage/BucketName.java",".java","166","9","package com.hartwig.platinum.storage; + +public class BucketName { + + static String from(final String runName) { + return ""platinum-output-"" + runName; + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/jobs/PipelineResult.java",".java","68","5","package com.hartwig.platinum.jobs; + +public class PipelineResult { +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/jobs/Pipeline.java",".java","66","5","package com.hartwig.platinum.jobs; + +public interface Pipeline { +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/jobs/Run.java",".java","62","6","package com.hartwig.platinum.jobs; + +public interface Run { + +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/config/BatchConfiguration.java",".java","336","17","package com.hartwig.platinum.config; + +import java.util.Optional; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; + +import org.immutables.value.Value; + +@Value.Immutable +@JsonDeserialize(as = ImmutableBatchConfiguration.class) +public interface BatchConfiguration { + + Integer size(); + + Optional delay(); +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/config/NodePoolConfiguration.java",".java","309","13","package com.hartwig.platinum.config; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; + +import org.immutables.value.Value; + +@Value.Immutable +@JsonDeserialize(as = ImmutableNodePoolConfiguration.class) +@Value.Style(jdkOnly = true) +public interface NodePoolConfiguration { + + String name(); +}","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/config/HmfConfiguration.java",".java","326","16","package com.hartwig.platinum.config; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; + +import org.immutables.value.Value; + +@Value.Immutable +@Value.Style(jdkOnly = true) +@JsonDeserialize(as = ImmutableHmfConfiguration.class) +public interface HmfConfiguration { + + boolean isRerun(); + + String apiUrl(); +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/config/SampleBucket.java",".java","2949","64","package com.hartwig.platinum.config; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; + +import com.google.cloud.storage.Blob; +import com.google.cloud.storage.BlobInfo; +import com.google.cloud.storage.Bucket; +import com.google.cloud.storage.Storage; + +public class SampleBucket { + + private static final String TUMOR_PATH = ""TUMOR""; + private static final String NORMAL_PATH = ""NORMAL""; + public static final String R1 = ""_R1""; + public static final String R2 = ""_R2""; + private final Bucket bucket; + + public SampleBucket(final Bucket bucket) { + this.bucket = bucket; + } + + public List apply() { + return StreamSupport.stream(bucket.list(Storage.BlobListOption.currentDirectory()).iterateAll().spliterator(), false) + .map(blob -> ImmutableSampleConfiguration.builder() + .addAllTumors(extractFastq(blob, TUMOR_PATH).stream().collect(Collectors.toList())) + .normal(extractFastq(blob, NORMAL_PATH)) + .name(blob.getName().replace(""/"", """")) + .build()) + .collect(Collectors.toList()); + } + + private Optional extractFastq(final Blob blob, final String typePrefix) { + final Optional maybeSampleName = + StreamSupport.stream(bucket.list(Storage.BlobListOption.prefix(blob.getName() + typePrefix)).iterateAll().spliterator(), + false).findFirst().map(BlobInfo::getName).map(s -> s.split(""/"")).map(s -> s[2]); + ImmutableRawDataConfiguration.Builder rawDataConfigurationBuilder = ImmutableRawDataConfiguration.builder(); + if (maybeSampleName.isPresent()) { + String sampleName = maybeSampleName.get(); + final Iterable fastqs = bucket.list(Storage.BlobListOption.prefix(blob.getName() + typePrefix)).iterateAll(); + for (Blob fastq : fastqs) { + if (fastq.getName().contains(R1)) { + for (Blob pairCandidate : fastqs) { + if (isMatchingR2(fastq, pairCandidate)) { + rawDataConfigurationBuilder.addFastq(ImmutableFastqConfiguration.builder() + .read1(bucket.getName() + ""/"" + fastq.getName()) + .read2(bucket.getName() + ""/"" + pairCandidate.getName()) + .build()); + } + } + } + } + return Optional.of(rawDataConfigurationBuilder.name(sampleName).build()); + } + return Optional.empty(); + } + + private boolean isMatchingR2(final Blob fastq, final Blob pairCandidate) { + return pairCandidate.getName().contains(R2) && pairCandidate.getName().replace(R2, """").equals(fastq.getName().replace(R1, """")); + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/config/SampleConfiguration.java",".java","606","27","package com.hartwig.platinum.config; + +import java.util.List; +import java.util.Optional; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; + +import org.immutables.value.Value; + +@Value.Immutable +@Value.Style(jdkOnly = true) +@JsonDeserialize(as = ImmutableSampleConfiguration.class) +public interface SampleConfiguration { + + String name(); + + List primaryTumorDoids(); + + List tumors(); + + Optional normal(); + + static ImmutableSampleConfiguration.Builder builder() { + return ImmutableSampleConfiguration.builder(); + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/config/GcpConfiguration.java",".java","2671","105","package com.hartwig.platinum.config; + +import static java.lang.String.format; + +import java.time.Duration; +import java.util.List; +import java.util.Optional; +import java.util.function.Supplier; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; + +import org.immutables.value.Value; + +@Value.Immutable +@JsonDeserialize(as = ImmutableGcpConfiguration.class) +@Value.Style(jdkOnly = true) +public interface GcpConfiguration { + + String DEFAULT_NETWORK_NAME = ""default""; + + Optional project(); + + Optional region(); + + Optional nodePoolConfiguration(); + + default String projectOrThrow() { + return project().orElseThrow(missing(""project"")); + } + + default String regionOrThrow() { + return region().orElseThrow(missing(""region"")); + } + + default GcpConfiguration withRegion(final String region) { + return GcpConfiguration.builder().from(this).region(region).build(); + } + + default GcpConfiguration withProject(final String project) { + return GcpConfiguration.builder().from(this).project(project).build(); + } + + @Value.Default + default boolean privateCluster() { + return false; + } + + @Value.Default + default boolean preemptibleCluster() { + return true; + } + + @Value.Default + default int maxNodes() { + return 10; + } + + List zones(); + + Optional secondaryRangeNamePods(); + + Optional secondaryRangeNameServices(); + + Optional jobTtl(); + + @Value.Default + default String masterIpv4CidrBlock() { + return ""172.16.0.32/28""; + } + + @Value.Default + default String network() { + return DEFAULT_NETWORK_NAME; + } + + @Value.Default + default String subnet() { + return DEFAULT_NETWORK_NAME; + } + + default String networkUrl() { + return isUrl(network()) ? network() : format(""projects/%s/global/networks/%s"", projectOrThrow(), network()); + } + + default String subnetUrl() { + return isUrl(subnet()) ? subnet() : format(""projects/%s/regions/%s/subnetworks/%s"", projectOrThrow(), regionOrThrow(), subnet()); + } + + private boolean isUrl(final String argument) { + return argument.startsWith(""projects""); + } + + List networkTags(); + + static ImmutableGcpConfiguration.Builder builder() { + return ImmutableGcpConfiguration.builder(); + } + + private Supplier missing(final String field) { + return () -> new IllegalStateException(String.format(""[%s] was not configured. You can configure [%s] in either the CLI or gcp json"", + field, + field)); + } + +}","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/config/FastqConfiguration.java",".java","296","14","package com.hartwig.platinum.config; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; + +import org.immutables.value.Value; + +@Value.Immutable +@JsonDeserialize(as = ImmutableFastqConfiguration.class) +public interface FastqConfiguration { + + String read1(); + + String read2(); +}","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/config/ServiceAccountConfiguration.java",".java","511","20","package com.hartwig.platinum.config; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; + +import org.immutables.value.Value; + +@JsonDeserialize(as = ImmutableServiceAccountConfiguration.class) +@Value.Style(jdkOnly = true) +@Value.Immutable +public interface ServiceAccountConfiguration { + + String gcpEmailAddress(); + + String kubernetesServiceAccount(); + + static ImmutableServiceAccountConfiguration.Builder builder() { + return ImmutableServiceAccountConfiguration.builder(); + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/config/Validation.java",".java","909","23","package com.hartwig.platinum.config; + +public class Validation { + + private static final int MAX_LENGTH = 49; + + public static void apply(final String runName, final PlatinumConfiguration configuration) { + checkSamplePlusRunNameIsNotTooLong(runName, configuration); + } + + private static void checkSamplePlusRunNameIsNotTooLong(final String runName, final PlatinumConfiguration configuration) { + for (SampleConfiguration sample : configuration.samples()) { + if (runName.length() + sample.name().length() >= MAX_LENGTH) { + throw new IllegalArgumentException(String.format( + ""Invalid input: Combination of run name [%s] and sample name [%s] should not exceed [%s] characters. Shorten one of them."", + runName, + sample.name(), + MAX_LENGTH)); + } + } + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/config/OverrideableArguments.java",".java","984","33","package com.hartwig.platinum.config; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.immutables.value.Value; + +@Value.Immutable +public interface OverrideableArguments { + + Map arguments(); + + default List asCommand(final String commandName) { + return Stream.concat(Stream.of(commandName), arguments().entrySet().stream().flatMap(e -> Stream.of(e.getKey(), e.getValue()))) + .collect(Collectors.toList()); + } + + default OverrideableArguments override(OverrideableArguments arguments) { + Map merged = new HashMap<>(); + merged.putAll(arguments()); + merged.putAll(arguments.arguments()); + return of(merged); + } + + static OverrideableArguments of(Map argumentPairs) { + return ImmutableOverrideableArguments.builder().arguments(argumentPairs).build(); + } + +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/config/PlatinumConfiguration.java",".java","2797","100","package com.hartwig.platinum.config; + +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; + +import org.immutables.value.Value; +import org.immutables.value.Value.Immutable; +import org.immutables.value.Value.Style; + +@Immutable +@Style(jdkOnly = true) +@JsonDeserialize(as = ImmutablePlatinumConfiguration.class) +public interface PlatinumConfiguration { + + @Value.Default + default String image() { + return ""eu.gcr.io/hmf-images/pipeline5:public-v5.29""; + } + + @Value.Default + default GcpConfiguration gcp() { + return GcpConfiguration.builder().build(); + } + + @Value.Default + default boolean namespaced() { + return false; + } + + @Value.Default + default boolean inCluster() { + return false; + } + + Optional batch(); + + Optional outputBucket(); + + Optional cmek(); + + ServiceAccountConfiguration serviceAccount(); + + Optional cluster(); + + Optional hmfConfiguration(); + + Optional keystorePassword(); + + default PlatinumConfiguration withGcp(final GcpConfiguration gcp) { + return builder().from(this).gcp(gcp).build(); + } + + Map argumentOverrides(); + + List samples(); + + List sampleIds(); + + Optional sampleBucket(); + + @Value.Default + default boolean createRun() { + return false; + } + + @Value.Default + default boolean retryFailed() { + return false; + } + + static ImmutablePlatinumConfiguration.Builder builder() { + return ImmutablePlatinumConfiguration.builder(); + } + + static PlatinumConfiguration from(final String inputFile) { + ObjectMapper objectMapper = inputFile.endsWith(""yaml"") ? new ObjectMapper(new YAMLFactory()) : new ObjectMapper(); + objectMapper.findAndRegisterModules(); + try { + PlatinumConfiguration platinumConfiguration = objectMapper.readValue(new File(inputFile), new TypeReference<>() { + }); + if (!platinumConfiguration.samples().isEmpty() && !platinumConfiguration.sampleIds().isEmpty()) { + throw new IllegalArgumentException(""Cannot specify both a list of sample jsons and a list of biopsies. "" + + ""Split this configuration into two platinum runs.""); + } + return platinumConfiguration; + } catch (IOException ioe) { + throw new RuntimeException(""Could not parse input"", ioe); + } + } +} + +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/config/RawDataConfiguration.java",".java","550","24","package com.hartwig.platinum.config; + +import java.util.List; +import java.util.Optional; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; + +import org.immutables.value.Value; + +@Value.Immutable +@Value.Style(jdkOnly = true) +@JsonDeserialize(as = ImmutableRawDataConfiguration.class) +public interface RawDataConfiguration { + + String name(); + + Optional bam(); + + List fastq(); + + static ImmutableRawDataConfiguration.Builder builder() { + return ImmutableRawDataConfiguration.builder(); + } +}","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/config/version/PipelineVersion.java",".java","1606","43","package com.hartwig.platinum.config.version; + +import static java.lang.String.format; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class PipelineVersion { + private static final Pattern VERSION_PATTERN = Pattern.compile(""^(\\d+)\\.(\\d+)\\.(\\d+)(?:-((?:alpha|beta)(?:\\.[0-9]+)*))?$""); + String padVersionStringToSemanticVersion(final String candidate) { + Matcher matcher = VERSION_PATTERN.matcher(candidate); + ArrayList versionsGiven; + + if (matcher.find()) { + versionsGiven = new ArrayList<>(List.of(matcher.group(1), matcher.group(2), matcher.group(3))); + } else { + versionsGiven = new ArrayList<>(List.of(candidate.split(""\\.""))); + } + + if (versionsGiven.size() > 3) { + throw new IllegalArgumentException(format(""Unrecognised pipeline version string [%s]"", candidate)); + } + int i; + int numMissing = 3 - versionsGiven.size(); + for (i = 0; i < numMissing; i++) { + versionsGiven.add(""0""); + } + return String.join(""."", versionsGiven); + } + + String extractVersionFromDockerImageName(final String pipelineDockerImageName) { + List tokens = List.of(pipelineDockerImageName.split("":"")); + if (tokens.size() == 1) { + throw new IllegalArgumentException(format(""Could not find version string in pipeline Docker image name [%s]"", + pipelineDockerImageName)); + } else { + return tokens.get(tokens.size() - 1); + } + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/main/java/com/hartwig/platinum/config/version/VersionCompatibility.java",".java","1646","36","package com.hartwig.platinum.config.version; + +import static java.lang.String.format; + +import com.vdurmont.semver4j.Semver; + +public class VersionCompatibility { + public static final String UNLIMITED = ""unlimited""; + public static final String SMALLEST_VERSION = ""0.0.0""; + private static final String LARGEST_VERSION = format(""%d.%d.%d"", Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); + private final Semver minimum; + private final Semver maximum; + private final String maximumForDisplay; + private final PipelineVersion pipelineVersion; + + public VersionCompatibility(final String minInclusive, final String maxInclusive, final PipelineVersion pipelineVersion) { + this.pipelineVersion = pipelineVersion; + minimum = new Semver(pipelineVersion.padVersionStringToSemanticVersion(minInclusive)); + if (maxInclusive.equals(UNLIMITED)) { + maximumForDisplay = maxInclusive; + maximum = new Semver(LARGEST_VERSION); + } else { + maximumForDisplay = pipelineVersion.padVersionStringToSemanticVersion(maxInclusive); + maximum = new Semver(maximumForDisplay); + } + } + + public void check(final String candidate) { + String padded = pipelineVersion.padVersionStringToSemanticVersion(pipelineVersion.extractVersionFromDockerImageName(candidate)); + if (!(minimum.isLowerThanOrEqualTo(padded) && maximum.isGreaterThanOrEqualTo(padded))) { + throw new IllegalArgumentException(format(""Pipeline5 version must be between [%s] and [%s] (requested [%s])"", + minimum, maximumForDisplay, candidate)); + } + } +} +","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/test/java/com/hartwig/platinum/ApiRerunTest.java",".java","3680","87","package com.hartwig.platinum; + +import static java.util.Collections.emptyList; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.List; + +import com.hartwig.ApiException; +import com.hartwig.api.RunApi; +import com.hartwig.api.SetApi; +import com.hartwig.api.model.CreateRun; +import com.hartwig.api.model.Ini; +import com.hartwig.api.model.Run; +import com.hartwig.api.model.RunCreated; +import com.hartwig.api.model.Sample; +import com.hartwig.api.model.SampleSet; +import com.hartwig.api.model.SampleType; +import com.hartwig.api.model.Status; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; + +public class ApiRerunTest { + private final String bucket = ""bucket""; + private final String version = ""notarealversion""; + private final String biopsy = ""sample""; + private final Long sampleSetId = 2L; + private final Run validatedRun = new Run().status(Status.VALIDATED); + private final Run existingReRun = new Run().status(Status.PENDING).id(3L); + private RunApi runs; + private SetApi sets; + private SampleSet sampleSet; + + @Before + public void setup() { + runs = mock(RunApi.class); + sets = mock(SetApi.class); + + Long sampleId = 1L; + List samples = List.of(new Sample().name(biopsy).id(sampleId)); + sampleSet = new SampleSet().id(sampleSetId); + + when(runs.callList(null, null, sampleSet.getId(), null, null, null, null, null, null)).thenReturn(List.of(validatedRun)); + when(sets.canonical(biopsy, SampleType.TUMOR)).thenReturn(sampleSet); + } + + @Test + public void shouldReturnIdOfExistingRunIfItIsNotInvalidated() { + when(runs.callList(null, Ini.RERUN_INI, sampleSet.getId(), version, version, null, null, null, null)).thenReturn(List.of(existingReRun)); + assertThat(new ApiRerun(runs, sets, bucket, version).create(biopsy)).isEqualTo(3L); + verify(runs, never()).create(any()); + } + + @Test + public void shouldThrowIllegalArgumentExceptionIfNoCanonicalSetExistsForSample() { + when(sets.canonical(any(), any())).thenThrow(new ApiException()); + assertThatThrownBy(() -> new ApiRerun(runs, sets, bucket, version).create(biopsy)).isInstanceOf(IllegalArgumentException.class); + verify(runs, never()).create(any()); + } + + @Test + public void shouldCreateRunForSampleIfNoneExists() { + when(runs.callList(null, Ini.RERUN_INI, sampleSet.getId(), version, version, null, null, null, null)).thenReturn(emptyList()); + ArgumentCaptor createRunCaptor = ArgumentCaptor.forClass(CreateRun.class); + when(runs.create(createRunCaptor.capture())).thenReturn(new RunCreated().id(3L)); + + assertThat(new ApiRerun(runs, sets, bucket, version).create(biopsy)).isNotNull(); + CreateRun createRun = createRunCaptor.getValue(); + assertThat(createRun).isNotNull(); + assertThat(createRun.getCluster()).isEqualTo(""gcp""); + assertThat(createRun.getBucket()).isEqualTo(bucket); + assertThat(createRun.getIni()).isEqualTo(Ini.RERUN_INI); + assertThat(createRun.getSetId()).isEqualTo(sampleSetId); + assertThat(createRun.getVersion()).isEqualTo(version); + assertThat(createRun.getContext()).isEqualTo(""RESEARCH""); + assertThat(createRun.getStatus()).isEqualTo(Status.PENDING); + assertThat(createRun.getIsHidden()).isEqualTo(true); + } +}","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/test/java/com/hartwig/platinum/iam/PipelineIamPolicyTest.java",".java","2644","48","package com.hartwig.platinum.iam; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import com.google.api.services.cloudresourcemanager.CloudResourceManager; +import com.google.api.services.cloudresourcemanager.model.Binding; +import com.google.api.services.cloudresourcemanager.model.GetIamPolicyRequest; +import com.google.api.services.cloudresourcemanager.model.Policy; +import com.google.api.services.cloudresourcemanager.model.SetIamPolicyRequest; +import com.google.api.services.iam.v1.model.ServiceAccount; + +import org.junit.Test; +import org.mockito.ArgumentCaptor; + +public class PipelineIamPolicyTest { + + private static final String PROJECT_ID = ""projects/test""; + private static final String EMAIL = ""platinum-test@service-account.com""; + private static final String IDENTITY = ""serviceAccount:"" + EMAIL; + + @Test + public void addsServiceAccountRolesToExistingPolicy() throws Exception { + CloudResourceManager resourceManager = mock(CloudResourceManager.class); + CloudResourceManager.Projects projects = mock(CloudResourceManager.Projects.class); + CloudResourceManager.Projects.GetIamPolicy getIamPolicy = mock(CloudResourceManager.Projects.GetIamPolicy.class); + CloudResourceManager.Projects.SetIamPolicy setIamPolicy = mock(CloudResourceManager.Projects.SetIamPolicy.class); + Policy policy = new Policy().setBindings(new ArrayList<>()); + when(resourceManager.projects()).thenReturn(projects); + when(projects.getIamPolicy(""projects/test"", new GetIamPolicyRequest())).thenReturn(getIamPolicy); + when(getIamPolicy.execute()).thenReturn(policy); + + ArgumentCaptor projectArgumentCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor policyArgumentCaptor = ArgumentCaptor.forClass(SetIamPolicyRequest.class); + when(projects.setIamPolicy(projectArgumentCaptor.capture(), policyArgumentCaptor.capture())).thenReturn(setIamPolicy); + PipelineIamPolicy victim = new PipelineIamPolicy(resourceManager); + victim.apply(new ServiceAccount().setEmail(EMAIL).setProjectId(PROJECT_ID)); + assertThat(projectArgumentCaptor.getValue()).isEqualTo(PROJECT_ID); + assertThat(policyArgumentCaptor.getValue().getPolicy().getBindings()).contains(new Binding().setMembers(List.of(IDENTITY)) + .setRole(PipelineIamPolicy.COMPUTE_ADMIN), + new Binding().setMembers(List.of(IDENTITY)).setRole(PipelineIamPolicy.STORAGE_ADMIN)); + } + +}","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/test/java/com/hartwig/platinum/pdl/ConvertFromGCSPathsTest.java",".java","6981","140","package com.hartwig.platinum.pdl; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import java.util.function.Supplier; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import com.hartwig.pdl.LaneInput; +import com.hartwig.pdl.PipelineInput; +import com.hartwig.platinum.config.FastqConfiguration; +import com.hartwig.platinum.config.ImmutableFastqConfiguration; +import com.hartwig.platinum.config.PlatinumConfiguration; +import com.hartwig.platinum.config.RawDataConfiguration; +import com.hartwig.platinum.config.SampleConfiguration; +import com.hartwig.platinum.config.ServiceAccountConfiguration; + +import org.junit.Test; + +public class ConvertFromGCSPathsTest { + + @Test(expected = IllegalArgumentException.class) + public void throwsIllegalArgumentWhenSampleNameExceeds55Chars() { + new ConvertFromGCSPaths().apply(createConfiguration(List.of(SampleConfiguration.builder() + .name(stringOf(55)) + .normal(fastqData(""normal"")) + .build()))); + } + + @Test + public void decomposesMultiNormalSamplesIntoPairs() { + List> pipelineInputs = + new ConvertFromGCSPaths().apply(createConfiguration(List.of(SampleConfiguration.builder() + .name(""sample"") + .tumors(List.of(fastqData(""first_tumor""), fastqData(""second_tumor""))) + .normal(fastqData(""normal"")) + .build()))); + assertThat(pipelineInputs).hasSize(2); + PipelineInput firstPair = pipelineInputs.get(0).get(); + assertThat(firstPair.setName()).isEqualTo(""sample-t1""); + assertThat(firstPair.tumor().orElseThrow().name()).isEqualTo(""first_tumor""); + assertThat(firstPair.reference().orElseThrow().name()).isEqualTo(""normal""); + PipelineInput secondPair = pipelineInputs.get(1).get(); + assertThat(secondPair.setName()).isEqualTo(""sample-t2""); + assertThat(secondPair.tumor().orElseThrow().name()).isEqualTo(""second_tumor""); + assertThat(secondPair.reference().orElseThrow().name()).isEqualTo(""normal""); + } + + @Test + public void populatesTumorAndNormalLanes() { + List> pairs = new ConvertFromGCSPaths().apply(createConfiguration(List.of(SampleConfiguration.builder() + .name(""sample"") + .tumors(List.of(fastqData(""first_tumor"", + ImmutableFastqConfiguration.builder().read1(""first_tumor_read1.fastq"").read2(""first_tumor_read2.fastq"").build()))) + .normal(fastqData(""normal"", + ImmutableFastqConfiguration.builder().read1(""normal_read1.fastq"").read2(""normal_read2.fastq"").build())) + .build()))); + PipelineInput pair = pairs.get(0).get(); + assertThat(pair.tumor().orElseThrow().lanes()).containsOnly(LaneInput.builder() + .laneNumber(""1"") + .firstOfPairPath(""first_tumor_read1.fastq"") + .secondOfPairPath(""first_tumor_read2.fastq"") + .build()); + assertThat(pair.reference().orElseThrow().lanes()).containsOnly(LaneInput.builder() + .laneNumber(""1"") + .firstOfPairPath(""normal_read1.fastq"") + .secondOfPairPath(""normal_read2.fastq"") + .build()); + } + + @Test + public void handlesBamInput() { + String firstTumorBamPath = ""first_tumor_bam_path""; + String normalBamPath = ""normal_bam_path""; + List> pairs = new ConvertFromGCSPaths().apply(createConfiguration(List.of(SampleConfiguration.builder() + .name(""sample"") + .tumors(List.of(bamData(""first_tumor"", firstTumorBamPath))) + .normal(bamData(""normal"", normalBamPath)) + .build()))); + PipelineInput pair = pairs.get(0).get(); + assertThat(pair.tumor().orElseThrow().bam().orElseThrow()).isEqualTo(firstTumorBamPath); + assertThat(pair.reference().orElseThrow().bam().orElseThrow()).isEqualTo(normalBamPath); + } + + @Test + public void handlesTumorBamWithNormalFastq() { + String firstTumorBamPath = ""first_tumor_bam_path""; + List> pairs = new ConvertFromGCSPaths().apply(createConfiguration(List.of(SampleConfiguration.builder() + .name(""sample"") + .tumors(List.of(bamData(""first_tumor"", firstTumorBamPath))) + .normal(fastqData(""normal"", + ImmutableFastqConfiguration.builder().read1(""normal_read1.fastq"").read2(""normal_read2.fastq"").build())) + .build()))); + PipelineInput pair = pairs.get(0).get(); + assertThat(pair.tumor().orElseThrow().bam().orElseThrow()).isEqualTo(firstTumorBamPath); + assertThat(pair.reference().orElseThrow().lanes()).containsOnly(LaneInput.builder() + .laneNumber(""1"") + .firstOfPairPath(""normal_read1.fastq"") + .secondOfPairPath(""normal_read2.fastq"") + .build()); + } + + @Test + public void handlesTumorFastqWithNormalBam() { + String normalBamPath = ""normal_bam_path""; + List> pairs = new ConvertFromGCSPaths().apply(createConfiguration(List.of(SampleConfiguration.builder() + .name(""sample"") + .tumors(List.of(fastqData(""first_tumor"", + ImmutableFastqConfiguration.builder().read1(""first_tumor_read1.fastq"").read2(""first_tumor_read2.fastq"").build()))) + .normal(bamData(""normal"", normalBamPath)) + .build()))); + PipelineInput pair = pairs.get(0).get(); + assertThat(pair.tumor().orElseThrow().lanes()).containsOnly(LaneInput.builder() + .laneNumber(""1"") + .firstOfPairPath(""first_tumor_read1.fastq"") + .secondOfPairPath(""first_tumor_read2.fastq"") + .build()); + assertThat(pair.reference().orElseThrow().bam().orElseThrow()).isEqualTo(normalBamPath); + } + + public RawDataConfiguration fastqData(final String first_tumor, final FastqConfiguration... fastq) { + return RawDataConfiguration.builder().name(first_tumor).addFastq(fastq).build(); + } + + public RawDataConfiguration bamData(final String first_tumor, final String bam_path) { + return RawDataConfiguration.builder().name(first_tumor).bam(bam_path).build(); + } + + public String stringOf(final int chars) { + return IntStream.rangeClosed(0, chars - 1).boxed().map(i -> "" "").collect(Collectors.joining()); + } + + private PlatinumConfiguration createConfiguration(List sampleConfigurations) { + return PlatinumConfiguration.builder() + .samples(sampleConfigurations) + .serviceAccount(ServiceAccountConfiguration.builder().kubernetesServiceAccount(""ksa"").gcpEmailAddress(""email"").build()) + .build(); + } +}","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/test/java/com/hartwig/platinum/kubernetes/ProcessRunnerTest.java",".java","789","27","package com.hartwig.platinum.kubernetes; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import org.junit.Test; + +public class ProcessRunnerTest { + @Test + public void shouldReturnTrueWhenProcessSucceeds() { + ProcessRunner victim = new ProcessRunner(); + assertThat(victim.execute(List.of(""/usr/bin/true""))).isTrue(); + } + + @Test + public void shouldReturnFalseWhenProcessFails() { + ProcessRunner victim = new ProcessRunner(); + assertThat(victim.execute(List.of(""/usr/bin/false""))).isFalse(); + } + + @Test + public void shouldReturnFalseWhenProcessBuilderThrows() { + ProcessRunner victim = new ProcessRunner(); + assertThat(victim.execute(List.of(""/a/b/c/not_a_real_program""))).isFalse(); + } +}","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/test/java/com/hartwig/platinum/kubernetes/JobSubmitterTest.java",".java","4077","104","package com.hartwig.platinum.kubernetes; + +import static com.hartwig.platinum.kubernetes.KubernetesCluster.NAMESPACE; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Map; +import java.util.stream.Collectors; + +import com.hartwig.platinum.kubernetes.pipeline.PipelineJob; + +import org.junit.Before; +import org.junit.Test; + +import io.fabric8.kubernetes.api.model.batch.v1.Job; +import io.fabric8.kubernetes.api.model.batch.v1.JobBuilder; +import io.fabric8.kubernetes.api.model.batch.v1.JobCondition; +import io.fabric8.kubernetes.api.model.batch.v1.JobSpec; +import io.fabric8.kubernetes.api.model.batch.v1.JobStatus; +import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; +import io.fabric8.kubernetes.client.dsl.ScalableResource; + +public class JobSubmitterTest { + private static final String JOB_NAME = ""job1""; + @SuppressWarnings(""rawtypes"") + private final NonNamespaceOperation jobs = mock(NonNamespaceOperation.class); + @SuppressWarnings(""unchecked"") + private final ScalableResource scalableJob = mock(ScalableResource.class); + private final PipelineJob pipelineJob = mock(PipelineJob.class); + private final JobSpec jobSpec = mock(JobSpec.class); + private JobSubmitter victim; + private KubernetesClientProxy kubernetesClientProxy; + private Job job; + + @Before + @SuppressWarnings(""unchecked"") + public void setup() { + kubernetesClientProxy = mock(KubernetesClientProxy.class); + victim = new JobSubmitter(kubernetesClientProxy, false); + + when(pipelineJob.getName()).thenReturn(JOB_NAME); + when(pipelineJob.asKubernetes()).thenReturn(jobSpec); + when(kubernetesClientProxy.jobs()).thenReturn(jobs); + when(jobs.withName(JOB_NAME)).thenReturn(scalableJob); + + job = new JobBuilder().withNewMetadata().withName(JOB_NAME).withNamespace(NAMESPACE).endMetadata().withSpec(jobSpec).build(); + } + + @Test + public void shouldSubmitNewJobIfNamedJobDoesNotExist() { + verifyWhetherJobCreatedAndReturnValueIs(true, true); + } + + @Test + public void shouldNotSubmitAnythingIfJobCompletedAlready() { + setupJobConditions(Map.of(""Complete"", ""True"", ""OtherState"", ""True"")); + verifyWhetherJobCreatedAndReturnValueIs(false, false); + } + + @Test + public void shouldNotSubmitAnythingIfJobFailedAndRetryIsFalse() { + setupJobConditions(Map.of(""Failed"", ""True"", ""Complete"", ""False"")); + verifyWhetherJobCreatedAndReturnValueIs(false, false); + } + + @Test + public void shouldResubmitFailedJobIfRetryIsTrue() { + victim = new JobSubmitter(kubernetesClientProxy, true); + setupJobConditions(Map.of(""Failed"", ""True"", ""Running"", ""False"")); + verifyWhetherJobCreatedAndReturnValueIs(true, true); + } + + @Test + public void shouldNotResubmitRunningJobButShouldTellSchedulerItDidSubmitIt() { + setupJobConditions(Map.of(""Complete"", ""False"")); + verifyWhetherJobCreatedAndReturnValueIs(false, true); + } + + private void setupJobConditions(Map statuses) { + Job existingJob = mock(Job.class); + JobStatus jobStatus = mock(JobStatus.class); + when(existingJob.getStatus()).thenReturn(jobStatus); + when(jobStatus.getConditions()).thenReturn(statuses.keySet() + .stream() + .map(status -> new JobCondition(null, null, null, null, statuses.get(status), status)) + .collect(Collectors.toList())); + when(scalableJob.get()).thenReturn(existingJob); + } + + @SuppressWarnings(""unchecked"") + private void verifyWhetherJobCreatedAndReturnValueIs(boolean jobCreated, boolean returnValue) { + assertThat(victim.submit(pipelineJob)).isEqualTo(returnValue); + if (jobCreated) { + verify(jobs).create(job); + } else { + verify(jobs, never()).create(any()); + } + } +}","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/test/java/com/hartwig/platinum/kubernetes/KubernetesClusterTest.java",".java","7885","159","package com.hartwig.platinum.kubernetes; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +import com.hartwig.pdl.PipelineInput; +import com.hartwig.pdl.SampleInput; +import com.hartwig.platinum.config.GcpConfiguration; +import com.hartwig.platinum.config.ImmutableGcpConfiguration; +import com.hartwig.platinum.config.ImmutablePlatinumConfiguration; +import com.hartwig.platinum.config.PlatinumConfiguration; +import com.hartwig.platinum.config.ServiceAccountConfiguration; +import com.hartwig.platinum.kubernetes.pipeline.ImmutableSampleArgument; +import com.hartwig.platinum.kubernetes.pipeline.PipelineConfigMapBuilder; +import com.hartwig.platinum.kubernetes.pipeline.PipelineJob; +import com.hartwig.platinum.kubernetes.pipeline.SampleArgument; +import com.hartwig.platinum.scheduling.JobScheduler; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; + +import io.fabric8.kubernetes.api.model.EnvVar; +import io.fabric8.kubernetes.api.model.Volume; +import io.fabric8.kubernetes.api.model.VolumeBuilder; + +public class KubernetesClusterTest { + private static final String CONFIG = ""config""; + private static final String TUMOR_NAME = ""tumor-name""; + private static final String REFERENCE_NAME = ""reference-name""; + private static final List SAMPLES = List.of(sample()); + private List> pipelineInputs; + private KubernetesCluster victim; + private JobScheduler scheduler; + private PipelineConfigMapBuilder configMaps; + private ImmutablePlatinumConfiguration.Builder configBuilder; + private ArgumentCaptor jobCaptor; + + @Before + public void setUp() { + scheduler = mock(JobScheduler.class); + configMaps = mock(PipelineConfigMapBuilder.class); + SampleInput tumor = SampleInput.builder().name(TUMOR_NAME).turquoiseSubject(TUMOR_NAME).build(); + PipelineInput input1 = PipelineInput.builder().setName(""setName"").tumor(tumor).build(); + pipelineInputs = List.of(() -> input1); + when(configMaps.forSample(any(), any())).thenReturn(new VolumeBuilder().withName(CONFIG).build()); + ServiceAccountConfiguration serviceAccountConfiguration = + ServiceAccountConfiguration.builder().kubernetesServiceAccount(""platinum-sa"").gcpEmailAddress(""e@mail.com"").build(); + ImmutableGcpConfiguration gcpConfiguration = GcpConfiguration.builder().project(""project"").region(""region"").build(); + configBuilder = PlatinumConfiguration.builder().gcp(gcpConfiguration).serviceAccount(serviceAccountConfiguration); + jobCaptor = ArgumentCaptor.forClass(PipelineJob.class); + } + + @Test + public void addsJksVolumeAndContainerIfPasswordSpecified() { + victim = victimise(configBuilder.keystorePassword(""changeit"").build()); + victim.submit(); + verify(scheduler).submit(jobCaptor.capture()); + PipelineJob result = jobCaptor.getValue(); + assertThat(result.getVolumes()).extracting(Volume::getName).contains(""jks""); + assertThat(result.getContainer().getEnv()).hasSize(1); + EnvVar env = result.getContainer().getEnv().get(0); + assertThat(env.getName()).isEqualTo(""JAVA_OPTS""); + assertThat(env.getValue()).isEqualTo(""-Djavax.net.ssl.keyStore=/jks/api.jks -Djavax.net.ssl.keyStorePassword=changeit""); + } + + @Test + public void submitsJobsToTheScheduler() { + victimise(configBuilder.keystorePassword(""changeit"").build()).submit(); + verify(scheduler).submit(jobCaptor.capture()); + assertThat(jobCaptor.getAllValues().size()).isEqualTo(SAMPLES.size()); + } + + @Test + public void addsConfigMapAndSecretVolumes() { + victim = victimise(configBuilder.build()); + victim.submit(); + verify(scheduler).submit(jobCaptor.capture()); + assertThat(jobCaptor.getValue().getVolumes()).extracting(Volume::getName).containsExactly(CONFIG); + } + + @Test + public void addsConfigMapForSampleToEachJob() { + String nameA = TUMOR_NAME + ""-a""; + String nameB = TUMOR_NAME + ""-b""; + PipelineInput inputA = PipelineInput.builder().setName(""set-a"").tumor(SampleInput.builder().name(nameA).turquoiseSubject(nameA).build()).build(); + PipelineInput inputB = PipelineInput.builder().setName(""set-b"").tumor(SampleInput.builder().name(nameB).turquoiseSubject(nameB).build()).build(); + pipelineInputs = List.of(() -> inputA, () -> inputB); + + when(configMaps.forSample(nameA, inputA)).thenReturn(new VolumeBuilder().withName(""config-a"").build()); + when(configMaps.forSample(nameB, inputB)).thenReturn(new VolumeBuilder().withName(""config-b"").build()); + victimise(configBuilder.build()).submit(); + verify(scheduler, times(2)).submit(jobCaptor.capture()); + List allJobs = jobCaptor.getAllValues(); + List jobsA = allJobs.stream().filter(j -> j.getName().equals(nameA + ""-test"")).collect(Collectors.toList()); + assertThat(jobsA.size()).isEqualTo(1); + assertThat(jobsA.get(0).getVolumes().stream().filter(v -> v.getName().equals(""config-a"")).collect(Collectors.toList())).hasSize(1); + List jobsB = allJobs.stream().filter(j -> j.getName().equals(nameB + ""-test"")).collect(Collectors.toList()); + assertThat(jobsB.size()).isEqualTo(1); + assertThat(jobsB.get(0).getVolumes().stream().filter(v -> v.getName().equals(""config-b"")).collect(Collectors.toList())).hasSize(1); + } + + @Test + public void usesReferenceSampleNameWhenTumorSampleUnspecified() { + PipelineInput input = PipelineInput.builder().setName(""set"").reference(SampleInput.builder().name(REFERENCE_NAME).turquoiseSubject(REFERENCE_NAME).build()).build(); + pipelineInputs = List.of(() -> input); + + victimise(configBuilder.build()).submit(); + verify(scheduler).submit(jobCaptor.capture()); + assertThat(jobCaptor.getAllValues().size()).isEqualTo(1); + PipelineJob job = jobCaptor.getValue(); + assertThat(job.getName()).isEqualTo(REFERENCE_NAME + ""-test""); + } + + @Test + public void usesTumorSampleNameWhenBothSamplesSpecified() { + PipelineInput input = PipelineInput.builder().setName(""set"").reference(SampleInput.builder().name(REFERENCE_NAME).turquoiseSubject(REFERENCE_NAME).build()) + .tumor(SampleInput.builder().name(TUMOR_NAME).turquoiseSubject(TUMOR_NAME).build()).build(); + pipelineInputs = List.of(() -> input); + + victimise(configBuilder.build()).submit(); + verify(scheduler).submit(jobCaptor.capture()); + assertThat(jobCaptor.getAllValues().size()).isEqualTo(1); + PipelineJob job = jobCaptor.getValue(); + assertThat(job.getName()).isEqualTo(TUMOR_NAME + ""-test""); + } + + @Test + public void ignoresSampleWhenNeitherTumorNorReferenceSpecified() { + PipelineInput input = PipelineInput.builder().setName(""set"").build(); + pipelineInputs = List.of(() -> input); + + victimise(configBuilder.build()).submit(); + verify(scheduler, never()).submit(any()); + } + + private static ImmutableSampleArgument sample() { + return ImmutableSampleArgument.builder().id(""sample"").build(); + } + + private KubernetesCluster victimise(PlatinumConfiguration configuration) { + return new KubernetesCluster(""test"", + scheduler, + pipelineInputs, + configMaps, + ""output-bucket"", + configuration, + TargetNodePool.defaultPool()); + } +}","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/test/java/com/hartwig/platinum/kubernetes/KubernetesEngineTest.java",".java","8756","186","package com.hartwig.platinum.kubernetes; + +import static java.lang.String.format; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.util.Collections; +import java.util.List; + +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.services.container.Container; +import com.google.api.services.container.Container.Projects; +import com.google.api.services.container.Container.Projects.Locations; +import com.google.api.services.container.Container.Projects.Locations.Clusters; +import com.google.api.services.container.Container.Projects.Locations.Clusters.Create; +import com.google.api.services.container.Container.Projects.Locations.Clusters.Get; +import com.google.api.services.container.Container.Projects.Locations.Operations; +import com.google.api.services.container.model.Cluster; +import com.google.api.services.container.model.CreateClusterRequest; +import com.google.api.services.container.model.Operation; +import com.hartwig.platinum.config.GcpConfiguration; +import com.hartwig.platinum.config.ImmutablePlatinumConfiguration; +import com.hartwig.platinum.config.PlatinumConfiguration; +import com.hartwig.platinum.config.ServiceAccountConfiguration; +import com.hartwig.platinum.scheduling.JobScheduler; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.ArgumentMatcher; + +public class KubernetesEngineTest { + private static final String PROJECT = ""project""; + private static final String REGION = ""region""; + private static final ImmutablePlatinumConfiguration CONFIGURATION = PlatinumConfiguration.builder() + .gcp(GcpConfiguration.builder().project(PROJECT).region(REGION).build()) + .serviceAccount(ServiceAccountConfiguration.builder() + .gcpEmailAddress(""platinum@example.com"") + .kubernetesServiceAccount(""platinum-sa"") + .build()) + .build(); + public static final String CLUSTER_NAME = ""clusterName""; + public static final String RUN_NAME = ""runName""; + public static final String BUCKET = ""bucket""; + public static final String SERVICE_ACCOUNT = ""service_account""; + private Locations locations; + private Clusters clusters; + private ProcessRunner processRunner; + private KubernetesClientProxy kubernetesClientProxy; + private KubernetesEngine victim; + + @Before + public void setup() { + final Projects projects = mock(Projects.class); + processRunner = mock(ProcessRunner.class); + final Container container = mock(Container.class); + locations = mock(Locations.class); + clusters = mock(Clusters.class); + JobScheduler jobScheduler = mock(JobScheduler.class); + kubernetesClientProxy = mock(KubernetesClientProxy.class); + + when(container.projects()).thenReturn(projects); + when(projects.locations()).thenReturn(locations); + when(locations.clusters()).thenReturn(clusters); + when(processRunner.execute(anyList())).thenReturn(true); + victim = new KubernetesEngine(container, processRunner, CONFIGURATION, jobScheduler, kubernetesClientProxy); + } + + @Test + public void shouldReturnExistingInstanceIfFound() throws IOException { + mocksForClusterExists(); + victim.findOrCreate(CLUSTER_NAME, RUN_NAME, Collections.emptyList(), BUCKET); + verify(clusters).get(anyString()); + verify(clusters, never()).create(any(), any()); + } + + @Test + public void shouldCreateAndReturnInstanceWhenNoneExists() throws IOException { + Get foundOperation = mock(Get.class); + Create created = mock(Create.class); + Operation executedCreate = mock(Operation.class); + + when(clusters.get(anyString())).thenReturn(foundOperation); + when(foundOperation.execute()).thenThrow(GoogleJsonResponseException.class); + when(clusters.create(eq(format(""projects/%s/locations/%s"", PROJECT, REGION)), any())).thenReturn(created); + when(created.execute()).thenReturn(executedCreate); + when(executedCreate.getName()).thenReturn(""created""); + + mockForClusterCreation(); + + victim.findOrCreate(CLUSTER_NAME, RUN_NAME, Collections.emptyList(), BUCKET); + verify(created).execute(); + } + + @Test + public void shouldPollUntilCreateClusterOperationHasCompleted() throws Exception { + Get foundOperation = mock(Get.class); + Create created = mock(Create.class); + Operation executedCreate = mock(Operation.class); + + when(clusters.get(anyString())).thenReturn(foundOperation); + when(foundOperation.execute()).thenThrow(GoogleJsonResponseException.class); + when(clusters.create(eq(format(""projects/%s/locations/%s"", PROJECT, REGION)), any())).thenReturn(created); + when(created.execute()).thenReturn(executedCreate); + when(executedCreate.getName()).thenReturn(""created""); + + Operations operations = mock(Operations.class); + Operations.Get operationsGet = mock(Operations.Get.class); + Operation executedOperationsGet = mock(Operation.class); + when(locations.operations()).thenReturn(operations); + when(operations.get(anyString())).thenReturn(operationsGet); + when(operationsGet.execute()).thenReturn(executedOperationsGet); + when(executedOperationsGet.getStatus()).thenReturn(null).thenReturn(""RUNNING"").thenReturn(""DONE""); + + victim.findOrCreate(CLUSTER_NAME, RUN_NAME, Collections.emptyList(), BUCKET); + verify(executedOperationsGet, times(3)).getStatus(); + } + + @Test(expected = RuntimeException.class) + public void shouldThrowIfAuthoriseFails() { + mocksForClusterExists(); + doThrow(RuntimeException.class).when(kubernetesClientProxy).authorise(); + when(processRunner.execute(argThat(startsWithGcloud()))).thenReturn(false); + victim.findOrCreate(CLUSTER_NAME, RUN_NAME, Collections.emptyList(), BUCKET); + } + + @Test + public void usesConfiguredClusterName() throws Exception { + + Get foundOperation = mock(Get.class); + Create created = mock(Create.class); + Operation executedCreate = mock(Operation.class); + + when(clusters.get(anyString())).thenReturn(foundOperation); + when(clusters.create(eq(format(""projects/%s/locations/%s"", PROJECT, REGION)), any())).thenReturn(created); + when(created.execute()).thenReturn(executedCreate); + when(executedCreate.getName()).thenReturn(""created""); + + when(clusters.get(anyString())).thenReturn(foundOperation); + when(foundOperation.execute()).thenThrow(GoogleJsonResponseException.class); + ArgumentCaptor createRequest = ArgumentCaptor.forClass(CreateClusterRequest.class); + when(clusters.create(eq(format(""projects/%s/locations/%s"", PROJECT, REGION)), createRequest.capture())).thenReturn(created); + when(created.execute()).thenReturn(executedCreate); + when(executedCreate.getName()).thenReturn(""created""); + mockForClusterCreation(); + victim.findOrCreate(CLUSTER_NAME, RUN_NAME, Collections.emptyList(), BUCKET); + + assertThat(createRequest.getValue().getCluster().getName()).isEqualTo(CLUSTER_NAME); + } + + public void mockForClusterCreation() throws IOException { + Operations operations = mock(Operations.class); + Operations.Get operationsGet = mock(Operations.Get.class); + Operation executedOperationsGet = mock(Operation.class); + when(locations.operations()).thenReturn(operations); + when(operations.get(anyString())).thenReturn(operationsGet); + when(operationsGet.execute()).thenReturn(executedOperationsGet); + when(executedOperationsGet.getStatus()).thenReturn(""DONE""); + } + + private void mocksForClusterExists() { + try { + Get foundOperation = mock(Get.class); + when(clusters.get(anyString())).thenReturn(foundOperation); + when(foundOperation.execute()).thenReturn(mock(Cluster.class)); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private ArgumentMatcher> startsWithGcloud() { + return argument -> argument.get(0).equals(""gcloud""); + } +}","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/test/java/com/hartwig/platinum/kubernetes/KubernetesUtilTest.java",".java","1222","36","package com.hartwig.platinum.kubernetes; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class KubernetesUtilTest { + @Test + public void testValidInput() { + String input = ""this_is_a-valid-input string""; + String expectedLabel = ""this-is-a-valid-input-string""; + String actualLabel = KubernetesUtil.toValidRFC1123Label(input); + assertEquals(expectedLabel, actualLabel); + } + + @Test + public void testValidInput2Strings() { + String input = ""this_is_a-valid""; + String input2 = ""input string""; + String expectedLabel = ""this-is-a-valid-input-string""; + String actualLabel = KubernetesUtil.toValidRFC1123Label(input, input2); + assertEquals(expectedLabel, actualLabel); + } + + @Test(expected = IllegalArgumentException.class) + public void testInvalidInput() { + String input = ""This is an invalid input string! It's too long and has spaces!""; + KubernetesUtil.toValidRFC1123Label(input); + } + + @Test(expected = IllegalArgumentException.class) + public void testInvalidUnicode() { + String input = ""this-is-an-íñválid-input-stríng""; + KubernetesUtil.toValidRFC1123Label(input); + } +}","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/test/java/com/hartwig/platinum/kubernetes/pipeline/PipelineArgumentsTest.java",".java","2266","61","package com.hartwig.platinum.kubernetes.pipeline; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import java.util.Map; + +import com.hartwig.platinum.config.GcpConfiguration; +import com.hartwig.platinum.config.PlatinumConfiguration; +import com.hartwig.platinum.config.ServiceAccountConfiguration; + +import org.junit.Test; + +public class PipelineArgumentsTest { + + @Test + public void addsNewOverrideIfNotInDefault() { + PipelineArguments victim = createVictimWithOverrides(""-arg"", ""value""); + assertThat(asCommand(victim)).containsOnlyOnce(""-arg"", ""value""); + } + + @Test + public void addsDashIfNotInArgument() { + PipelineArguments victim = createVictimWithOverrides(""arg"", ""value""); + assertThat(asCommand(victim)).containsOnlyOnce(""-arg"", ""value""); + } + + @Test + public void doesNotOverrideFixedValues() { + PipelineArguments victim = createVictimWithOverrides(""-region"", ""different""); + assertThat(asCommand(victim)).containsOnlyOnce(""-region"", ""region""); + } + + @Test + public void allowsOverridingOfDefaults() { + PipelineArguments victim = createVictimWithOverrides(""-output_cram"", ""true""); + assertThat(asCommand(victim)).containsOnlyOnce(""-output_cram"", ""true""); + } + + @Test(expected = IllegalArgumentException.class) + public void doesNotAllowOverrideOfApi() { + createVictimWithOverrides(""hmf_api_url"", ""whatever""); + } + + private List asCommand(final PipelineArguments victim) { + return victim.asCommand(SampleArgument.sampleJson(""tumor-run"", ""run"")); + } + + private PipelineArguments createVictimWithOverrides(final String key, final String value) { + return new PipelineArguments(Map.of(key, value), + ""output"", + ""email"", + PlatinumConfiguration.builder() + .gcp(GcpConfiguration.builder().region(""region"").project(""project"").privateCluster(false).build()) + .serviceAccount(ServiceAccountConfiguration.builder() + .kubernetesServiceAccount(""ksa"") + .gcpEmailAddress(""email"") + .build()) + .build()); + } +}","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/test/java/com/hartwig/platinum/kubernetes/pipeline/PipelineConfigMapVolumeTest.java",".java","940","27","package com.hartwig.platinum.kubernetes.pipeline; + +import static java.lang.String.format; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import java.util.Map; + +import com.hartwig.platinum.kubernetes.KubernetesClientProxy; +import com.hartwig.platinum.kubernetes.pipeline.PipelineConfigMapVolume.PipelineConfigMapVolumeBuilder; + +import org.junit.Test; + +public class PipelineConfigMapVolumeTest { + @Test + @SuppressWarnings(""unchecked"") + public void shouldBuildVolume() { + String runName = ""run-name""; + String sample = ""sample""; + String content = ""content""; + KubernetesClientProxy kubernetesClient = mock(KubernetesClientProxy.class); + new PipelineConfigMapVolumeBuilder(kubernetesClient).of(runName, sample, content).asKubernetes(); + + verify(kubernetesClient).ensureConfigMapVolumeExists(format(""%s-%s"", runName, sample), Map.of(sample, content)); + } +}","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/test/java/com/hartwig/platinum/kubernetes/pipeline/PipelineJobTest.java",".java","2319","68","package com.hartwig.platinum.kubernetes.pipeline; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.Duration; +import java.util.List; +import java.util.Map; + +import com.hartwig.platinum.kubernetes.TargetNodePool; + +import org.junit.Before; +import org.junit.Test; + +import io.fabric8.kubernetes.api.model.ConfigMapVolumeSource; +import io.fabric8.kubernetes.api.model.Container; +import io.fabric8.kubernetes.api.model.PodSpec; +import io.fabric8.kubernetes.api.model.Volume; +import io.fabric8.kubernetes.api.model.VolumeBuilder; +import io.fabric8.kubernetes.api.model.batch.v1.JobSpec; + +public class PipelineJobTest { + private PipelineJob victim; + + @Before + public void setup() { + String name = ""config-map""; + List volumes = List.of(new VolumeBuilder().withName(name).editOrNewConfigMap().withName(name).endConfigMap().build()); + victim = new PipelineJob(""sample-run"", new Container(), volumes, ""platinum-sa"", TargetNodePool.defaultPool(), Duration.ZERO); + } + + @Test + public void namesJobWithRunAndSample() { + assertThat(victim.getName()).isEqualTo(""sample-run""); + } + + private PodSpec assertSpecNotNull() { + JobSpec jobSpec = victim.asKubernetes(); + assertThat(jobSpec.getTemplate()).isNotNull(); + assertThat(jobSpec.getTemplate().getSpec()).isNotNull(); + return jobSpec.getTemplate().getSpec(); + } + + @Test + public void setsServiceAccount() { + PodSpec podSpec = assertSpecNotNull(); + assertThat(podSpec.getServiceAccountName()).isEqualTo(""platinum-sa""); + } + + @Test + public void willOnlyRunOnWorkloadIdentityEnabledNodes() { + PodSpec podSpec = assertSpecNotNull(); + assertThat(podSpec.getNodeSelector()).isEqualTo(Map.of(""iam.gke.io/gke-metadata-server-enabled"", ""true"")); + } + + @Test + public void setsRestartPolicy() { + assertThat(assertSpecNotNull().getRestartPolicy()).isEqualTo(""Never""); + } + + @Test + public void setsConfigMapVolume() { + PodSpec podSpec = assertSpecNotNull(); + assertThat(podSpec.getVolumes()).isNotNull(); + ConfigMapVolumeSource configMap = podSpec.getVolumes().get(0).getConfigMap(); + assertThat(configMap).isNotNull(); + assertThat(configMap.getName()).isEqualTo(""config-map""); + } +}","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/test/java/com/hartwig/platinum/scheduling/ConstantJobCountSchedulerTest.java",".java","5941","152","package com.hartwig.platinum.scheduling; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Collections; +import java.util.List; + +import com.hartwig.platinum.kubernetes.JobSubmitter; +import com.hartwig.platinum.kubernetes.KubernetesClientProxy; +import com.hartwig.platinum.kubernetes.pipeline.PipelineJob; + +import org.junit.Before; +import org.junit.Test; + +import io.fabric8.kubernetes.api.model.batch.v1.Job; +import io.fabric8.kubernetes.api.model.batch.v1.JobCondition; +import io.fabric8.kubernetes.api.model.batch.v1.JobStatus; +import io.fabric8.kubernetes.client.KubernetesClientException; +import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; +import io.fabric8.kubernetes.client.dsl.ScalableResource; + +public class ConstantJobCountSchedulerTest { + private final JobSubmitter jobSubmitter = mock(JobSubmitter.class); + private final KubernetesClientProxy kubernetesClientProxy = mock(KubernetesClientProxy.class); + private final Delay submissionDelay = mock(Delay.class); + private final PipelineJob job1 = mock(PipelineJob.class); + private final PipelineJob job2 = mock(PipelineJob.class); + private final PipelineJob job3 = mock(PipelineJob.class); + @SuppressWarnings(""unchecked"") + private final ScalableResource scalableJob1 = mock(ScalableResource.class); + @SuppressWarnings(""unchecked"") + private final ScalableResource scalableJob2 = mock(ScalableResource.class); + @SuppressWarnings(""unchecked"") + private final ScalableResource scalableJob3 = mock(ScalableResource.class); + @SuppressWarnings(""rawtypes"") + private final NonNamespaceOperation jobs = mock(NonNamespaceOperation.class); + private final Job kubeJob1 = mock(Job.class); + private final Job kubeJob2 = mock(Job.class); + private final Job kubeJob3 = mock(Job.class); + private JobStatus kubeJob1Status; + private static final String CONDITION_COMPLETE = ""Complete""; + private static final String CONDITION_FAILED = ""Failed""; + private JobStatus kubeJob2Status; + private JobStatus kubeJob3Status; + + private static enum Condition { + COMPLETE(""Complete""), + FAILED(""Failed""); + + private final String type; + + Condition(String type) { + this.type = type; + } + } + + private ConstantJobCountScheduler victim; + + @Before + @SuppressWarnings(""unchecked"") + public void setup() { + when(job1.getName()).thenReturn(""job1""); + when(job2.getName()).thenReturn(""job2""); + when(job3.getName()).thenReturn(""job3""); + + when(jobSubmitter.submit(any(PipelineJob.class))).thenReturn(true); + when(kubernetesClientProxy.jobs()).thenReturn(jobs); + + when(jobs.withName(""job1"")).thenReturn(scalableJob1); + when(jobs.withName(""job2"")).thenReturn(scalableJob2); + when(jobs.withName(""job3"")).thenReturn(scalableJob3); + + when(scalableJob1.get()).thenReturn(kubeJob1); + when(scalableJob2.get()).thenReturn(kubeJob2); + when(scalableJob3.get()).thenReturn(kubeJob3); + + kubeJob1Status = mock(JobStatus.class); + kubeJob2Status = mock(JobStatus.class); + kubeJob3Status = mock(JobStatus.class); + + when(kubeJob1.getStatus()).thenReturn(kubeJob1Status); + when(kubeJob2.getStatus()).thenReturn(kubeJob2Status); + when(kubeJob3.getStatus()).thenReturn(kubeJob3Status); + + when(kubeJob1Status.getConditions()).thenReturn(Collections.emptyList()); + when(kubeJob2Status.getConditions()).thenReturn(Collections.emptyList()); + when(kubeJob3Status.getConditions()).thenReturn(Collections.emptyList()); + + victim = new ConstantJobCountScheduler(jobSubmitter, kubernetesClientProxy, 2, submissionDelay, Delay.forMilliseconds(1)); + } + + @Test + public void shouldWaitUntilThereIsSpaceToScheduleJob() { + when(kubeJob1Status.getConditions()).thenReturn(Collections.emptyList()).thenReturn(List.of(mockCondition(CONDITION_COMPLETE))); + + victim.submit(job1); + victim.submit(job2); + victim.submit(job3); + + verify(submissionDelay, times(3)).threadSleep(); + verify(jobSubmitter).submit(job3); + } + + @Test + public void shouldNotRescheduleJobThatHasDisappeared() { + when(scalableJob1.get()).thenReturn(kubeJob1).thenReturn(null); + when(kubeJob1Status.getConditions()).thenReturn(Collections.emptyList()); + + victim.submit(job1); + victim.submit(job2); + victim.submit(job3); + + verify(jobSubmitter, times(1)).submit(job1); + } + + @Test + public void shouldReAuthoriseWhenKubernetesClientExceptionOccurs() { + when(scalableJob1.get()).thenThrow(KubernetesClientException.class).thenReturn(kubeJob1); + List conditions = List.of(mockCondition(CONDITION_COMPLETE)); + when(kubeJob1Status.getConditions()).thenReturn(conditions); + + victim.submit(job1); + victim.submit(job2); + victim.submit(job3); + + verify(kubernetesClientProxy).authorise(); + } + + @Test + @SuppressWarnings(""unchecked"") + public void shouldResubmitFailedJob() { + List jobConditions = List.of(mockCondition(CONDITION_FAILED)); + when(kubeJob1Status.getConditions()).thenReturn(jobConditions).thenReturn(List.of(mockCondition(CONDITION_COMPLETE))); + victim.submit(job1); + victim.submit(job2); + victim.submit(job3); + + verify(jobs).delete(kubeJob1); + verify(jobSubmitter, times(2)).submit(job1); + } + + private static JobCondition mockCondition(String condition) { + JobCondition jobCondition = mock(JobCondition.class); + when(jobCondition.getStatus()).thenReturn(""True""); + when(jobCondition.getType()).thenReturn(condition); + return jobCondition; + } +}","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/test/java/com/hartwig/platinum/scheduling/JobSchedulerTest.java",".java","2306","47","package com.hartwig.platinum.scheduling; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +import java.util.Optional; + +import com.hartwig.platinum.config.BatchConfiguration; +import com.hartwig.platinum.config.ImmutableBatchConfiguration; +import com.hartwig.platinum.config.PlatinumConfiguration; +import com.hartwig.platinum.config.ServiceAccountConfiguration; +import com.hartwig.platinum.kubernetes.JobSubmitter; +import com.hartwig.platinum.kubernetes.KubernetesClientProxy; + +import org.junit.Test; + +public class JobSchedulerTest { + private final JobSubmitter jobSubmitter = mock(JobSubmitter.class); + private final KubernetesClientProxy kubernetesClientProxy = mock(KubernetesClientProxy.class); + private static final ServiceAccountConfiguration SA = + ServiceAccountConfiguration.builder().kubernetesServiceAccount(""ksa"").gcpEmailAddress(""email"").build(); + + @Test + public void shouldConstructTimedBatchSchedulerInstanceIfDelaySpecified() { + assertThat(createFromConfiguration(20)).isInstanceOf(TimedBatchScheduler.class); + } + + @Test + public void shouldConstructConstantJobCountSchedulerInstanceIfBatchSizeSpecifiedWithoutDelay() { + assertThat(createFromConfiguration(null)).isInstanceOf(ConstantJobCountScheduler.class); + } + + @Test + public void shouldConstructConstantJobCountSchedulerOfSizeOneIfBatchConfigurationUnspecified() { + PlatinumConfiguration configuration = PlatinumConfiguration.builder().serviceAccount(SA).build(); + assertThat(JobScheduler.fromConfiguration(configuration, jobSubmitter, kubernetesClientProxy)).isInstanceOf( + ConstantJobCountScheduler.class); + } + + private JobScheduler createFromConfiguration(Integer delay) { + ImmutableBatchConfiguration.Builder batchConfigurationBuilder = ImmutableBatchConfiguration.builder().size(10); + Optional.ofNullable(delay).ifPresent(batchConfigurationBuilder::delay); + BatchConfiguration batchConfiguration = batchConfigurationBuilder.build(); + PlatinumConfiguration configuration = PlatinumConfiguration.builder().batch(batchConfiguration).serviceAccount(SA).build(); + return JobScheduler.fromConfiguration(configuration, jobSubmitter, kubernetesClientProxy); + } +}","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/test/java/com/hartwig/platinum/storage/OutputBucketTest.java",".java","4066","87","package com.hartwig.platinum.storage; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.cloud.Policy; +import com.google.cloud.storage.Bucket; +import com.google.cloud.storage.BucketInfo; +import com.google.cloud.storage.Storage; +import com.hartwig.platinum.config.GcpConfiguration; +import com.hartwig.platinum.config.PlatinumConfiguration; +import com.hartwig.platinum.config.ServiceAccountConfiguration; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; + +public class OutputBucketTest { + + private static final String RUN_NAME = ""test""; + private static final String BUCKET_NAME = ""platinum-output-test""; + public static final String REGION = ""europe-west4""; + private static final PlatinumConfiguration CONFIGURATION = PlatinumConfiguration.builder() + .gcp(GcpConfiguration.builder().build()) + .serviceAccount(ServiceAccountConfiguration.builder().kubernetesServiceAccount(""ksa"").gcpEmailAddress(""gcp"").build()) + .build(); + private static final String CMEK_KEY = ""/location/of/key""; + private Storage storage; + private Bucket bucket; + private OutputBucket victim; + + @Before + public void setUp() { + storage = mock(Storage.class); + bucket = mock(Bucket.class); + when(bucket.getName()).thenReturn(BUCKET_NAME); + when(bucket.getLocation()).thenReturn(REGION); + when(storage.getIamPolicy(BUCKET_NAME)).thenReturn(Policy.newBuilder().build()); + victim = OutputBucket.from(storage); + } + + @Test + public void createsNewBucketInSpecifiedLocation() { + ArgumentCaptor bucketInfoArgumentCaptor = ArgumentCaptor.forClass(BucketInfo.class); + when(storage.create(bucketInfoArgumentCaptor.capture())).thenReturn(bucket); + String bucketName = victim.findOrCreate(RUN_NAME, REGION, CONFIGURATION); + assertThat(bucketName).isEqualTo(BUCKET_NAME); + BucketInfo bucketInfo = bucketInfoArgumentCaptor.getValue(); + assertThat(bucketInfo.getLocation()).isEqualTo(REGION); + } + + @Test + public void usingExistingBucketWhenFound() { + ArgumentCaptor bucketInfoArgumentCaptor = ArgumentCaptor.forClass(BucketInfo.class); + when(storage.create(bucketInfoArgumentCaptor.capture())).thenReturn(bucket); + when(storage.get(BUCKET_NAME)).thenReturn(bucket); + String bucketName = victim.findOrCreate(RUN_NAME, REGION, CONFIGURATION); + verify(storage, never()).create(Mockito.any()); + assertThat(bucketName).isEqualTo(BUCKET_NAME); + } + + @Test + public void usesBucketFromConfigurationIfPresent() { + ArgumentCaptor bucketInfoArgumentCaptor = ArgumentCaptor.forClass(BucketInfo.class); + when(storage.create(bucketInfoArgumentCaptor.capture())).thenReturn(bucket); + String configuredBucket = ""configuredBucket""; + when(storage.getIamPolicy(configuredBucket)).thenReturn(Policy.newBuilder().build()); + String bucketName = victim.findOrCreate(RUN_NAME, + REGION, + PlatinumConfiguration.builder().from(CONFIGURATION).outputBucket(configuredBucket).build()); + assertThat(bucketName).isEqualTo(BUCKET_NAME); + BucketInfo bucketInfo = bucketInfoArgumentCaptor.getValue(); + assertThat(bucketInfo.getName()).isEqualTo(configuredBucket); + } + + @Test + public void appliesCmekIfSpecifiedInConfig() { + ArgumentCaptor bucketInfoArgumentCaptor = ArgumentCaptor.forClass(BucketInfo.class); + when(storage.create(bucketInfoArgumentCaptor.capture())).thenReturn(bucket); + victim.findOrCreate(RUN_NAME, REGION, PlatinumConfiguration.builder().from(CONFIGURATION).cmek(CMEK_KEY).build()); + assertThat(bucketInfoArgumentCaptor.getValue().getDefaultKmsKeyName()).isEqualTo(CMEK_KEY); + } +}","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/test/java/com/hartwig/platinum/config/SampleBucketTest.java",".java","4261","87","package com.hartwig.platinum.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Collections; +import java.util.List; + +import com.google.api.gax.paging.Page; +import com.google.cloud.storage.Blob; +import com.google.cloud.storage.Bucket; +import com.google.cloud.storage.Storage; + +import org.junit.Test; + +@SuppressWarnings(""unchecked"") +public class SampleBucketTest { + + @Test + public void emptyBucketReturnsEmptySamples() { + Bucket bucket = mock(Bucket.class); + Page page = mock(Page.class); + when(page.iterateAll()).thenReturn(Collections.emptyList()); + when(bucket.list(Storage.BlobListOption.currentDirectory())).thenReturn(page); + SampleBucket victim = new SampleBucket(bucket); + assertThat(victim.apply()).isEmpty(); + } + + @Test + public void createsSampleConfigurationFromBucketPath() { + Bucket bucket = mock(Bucket.class); + when(bucket.getName()).thenReturn(""bucket""); + Page samplePage = mock(Page.class); + Blob setDirectory = blob(""COLO829/""); + when(samplePage.iterateAll()).thenReturn(List.of(setDirectory)); + when(bucket.list(Storage.BlobListOption.currentDirectory())).thenReturn(samplePage); + + Blob normalDirectory = blob(""COLO829/NORMAL/COLO829R""); + Page normalDirectoryPage = mock(Page.class); + when(normalDirectoryPage.iterateAll()).thenReturn(List.of(normalDirectory)); + when(bucket.list(Storage.BlobListOption.prefix(""COLO829/NORMAL""), Storage.BlobListOption.currentDirectory())).thenReturn( + normalDirectoryPage); + + Blob normalFastqR1 = blob(""COLO829/NORMAL/COLO829R/COLO829R_R1_001.fastq.gz""); + Blob normalFastqR2 = blob(""COLO829/NORMAL/COLO829R/COLO829R_R2_001.fastq.gz""); + Page normalFastqPage = mock(Page.class); + when(normalFastqPage.iterateAll()).thenReturn(List.of(normalFastqR1, normalFastqR2)); + when(bucket.list(Storage.BlobListOption.prefix(""COLO829/NORMAL""))).thenReturn(normalFastqPage); + + Blob tumorDirectory = blob(""COLO829/NORMAL/COLO829T""); + Page tumorDirectoryPage = mock(Page.class); + when(tumorDirectoryPage.iterateAll()).thenReturn(List.of(tumorDirectory)); + when(bucket.list(Storage.BlobListOption.prefix(""COLO829/TUMOR""), Storage.BlobListOption.currentDirectory())).thenReturn( + tumorDirectoryPage); + + Blob tumorFastqR1 = blob(""COLO829/TUMOR/COLO829T/COLO829T_R1_001.fastq.gz""); + Blob tumorFastqR2 = blob(""COLO829/TUMOR/COLO829T/COLO829T_R2_001.fastq.gz""); + Page tumorFastqPage = mock(Page.class); + when(tumorFastqPage.iterateAll()).thenReturn(List.of(tumorFastqR1, tumorFastqR2)); + when(bucket.list(Storage.BlobListOption.prefix(""COLO829/TUMOR""))).thenReturn(tumorFastqPage); + + SampleBucket victim = new SampleBucket(bucket); + final List result = victim.apply(); + assertThat(result).hasSize(1); + SampleConfiguration sampleConfiguration = result.get(0); + assertThat(sampleConfiguration.name()).isEqualTo(""COLO829""); + assertThat(sampleConfiguration.normal().orElseThrow().name()).isEqualTo(""COLO829R""); + assertThat(sampleConfiguration.tumors().get(0).name()).isEqualTo(""COLO829T""); + + assertThat(sampleConfiguration.normal().orElseThrow().fastq().get(0).read1()).isEqualTo( + ""bucket/COLO829/NORMAL/COLO829R"" + ""/COLO829R_R1_001.fastq"" + "".gz""); + assertThat(sampleConfiguration.normal().orElseThrow().fastq().get(0).read2()).isEqualTo( + ""bucket/COLO829/NORMAL/COLO829R"" + ""/COLO829R_R2_001.fastq"" + "".gz""); + assertThat(sampleConfiguration.tumors().get(0).fastq().get(0).read1()).isEqualTo( + ""bucket/COLO829/TUMOR/COLO829T/COLO829T_R1_001"" + "".fastq.gz""); + assertThat(sampleConfiguration.tumors().get(0).fastq().get(0).read2()).isEqualTo( + ""bucket/COLO829/TUMOR/COLO829T/COLO829T_R2_001"" + "".fastq.gz""); + } + + private Blob blob(final String name) { + Blob blob = mock(Blob.class); + when(blob.getName()).thenReturn(name); + return blob; + } + +}","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/test/java/com/hartwig/platinum/config/ValidationTest.java",".java","1049","27","package com.hartwig.platinum.config; + +import org.junit.Test; + +public class ValidationTest { + + @Test(expected = IllegalArgumentException.class) + public void failsValidationWhenSampleNamePlusRunNameExceeds49() { + Validation.apply(""this-is-a-long-run-name"", configWithSampleName(""this-is-a-long-sample-name"")); + } + + @Test + public void passesValidation() { + Validation.apply(""run"", configWithSampleName(""sample"")); + } + + private PlatinumConfiguration configWithSampleName(String sampleName) { + return PlatinumConfiguration.builder() + .addSamples(SampleConfiguration.builder() + .name(sampleName) + .addTumors(RawDataConfiguration.builder().name(""tumor"").build()) + .normal(RawDataConfiguration.builder().name(""normal"").build()) + .build()) + .serviceAccount(ServiceAccountConfiguration.builder().kubernetesServiceAccount(""ksa"").gcpEmailAddress(""email"").build()) + .build(); + } +}","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/test/java/com/hartwig/platinum/config/version/PipelineVersionTest.java",".java","1324","37","package com.hartwig.platinum.config.version; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; + +public class PipelineVersionTest { + @Test + public void shouldPadVersionWithSingleNumber() { + assertThat(new PipelineVersion().padVersionStringToSemanticVersion(""4"")).isEqualTo(""4.0.0""); + } + + @Test + public void shouldPadVersionWithTwoNumbers() { + assertThat(new PipelineVersion().padVersionStringToSemanticVersion(""4.0"")).isEqualTo(""4.0.0""); + } + + @Test + public void shouldReturnFullVersionUnchanged() { + assertThat(new PipelineVersion().padVersionStringToSemanticVersion(""4.0.0"")).isEqualTo(""4.0.0""); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldThrowIfCandidateHasTooManyTuples() { + new PipelineVersion().padVersionStringToSemanticVersion(""1.2.3.4""); + } + + @Test + public void shouldExtractPipelineVersionFromDockerUrl() { + assertThat(new PipelineVersion().extractVersionFromDockerImageName(""eu.gcr.io/hmf-build/pipeline5:5.33.5"")).isEqualTo(""5.33.5""); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldThrowIfDockerUrlContainsNoVersionDelimiter() { + new PipelineVersion().extractVersionFromDockerImageName(""eu.gcr.io/hmf-build/pipeline5.5.33""); + } +}","Java" +"Pharmacogenetics","hartwigmedical/platinum","src/test/java/com/hartwig/platinum/config/version/VersionCompatibilityTest.java",".java","1621","46","package com.hartwig.platinum.config.version; + +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.junit.Before; +import org.junit.Test; + +public class VersionCompatibilityTest { + private PipelineVersion pipelineVersion; + private VersionCompatibility versionCompatibility; + + @Before + public void setup() { + pipelineVersion = mock(PipelineVersion.class); + when(pipelineVersion.padVersionStringToSemanticVersion(anyString())).thenAnswer(i -> i.getArguments()[0]); + when(pipelineVersion.extractVersionFromDockerImageName(anyString())).thenAnswer(i -> i.getArguments()[0]); + versionCompatibility = new VersionCompatibility(""1.0.0"", ""2.0.0"", pipelineVersion); + } + + @Test + public void shouldAcceptInRangeVersion() { + versionCompatibility.check(""1.1.0""); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldRejectTooOldVersion() { + versionCompatibility.check(""0.5.0""); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldRejectTooNewVersion() { + versionCompatibility.check(""3.0.0""); + } + + @Test + public void shouldAcceptArbitrarilyOldVersionWhenMinSetToSmallest() { + new VersionCompatibility(VersionCompatibility.SMALLEST_VERSION, ""2.0.0"", pipelineVersion).check(""0.0.1""); + } + + @Test + public void shouldAcceptArbitrarilyNewVersionWhenNoMaxIsSetToLargest() { + new VersionCompatibility(""1.0.0"", VersionCompatibility.UNLIMITED, pipelineVersion).check(""10000.10000.5324""); + } +}","Java" +"Pharmacogenetics","PreMedKB/PAnno","setup.py",".py","1754","53","#!/usr/bin/env python +# -*- coding: UTF-8 -*- + +""""""The setup script."""""" + +from setuptools import setup, find_packages + +readme = open('README.md').read() +history = open('HISTORY.md').read() + +requirements = ['pandas', 'numpy', 'pyranges'] +test_requirements = ['pandas', 'numpy', 'pyranges'] + +setup( + author=""Yaqing Liu"", + author_email='yaqing.liu@outlook.com', + python_requires='>=3.7', + classifiers=[ + 'Development Status :: 2 - Pre-Alpha', + ""Environment :: Console"", + ""Environment :: Web Environment"", + ""Intended Audience :: Science/Research"", + ""License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)"", + 'Natural Language :: English', + ""Operating System :: MacOS :: MacOS X"", + ""Operating System :: POSIX"", + ""Operating System :: Unix"", + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Programming Language :: Python :: 3.10', + ], + description=""PAnno is a Pharmacogenomics Annotation tool for clinical genomic testing."", + entry_points={ + 'console_scripts': [ + 'panno=panno.panno:main', + ], + }, + install_requires=requirements, + long_description=readme + '\n\n' + history, + long_description_content_type='text/markdown', + include_package_data=True, + keywords=['pharmacogenomics', 'pharmacology', 'drug responses', 'genomics', 'bioinformatics'], + name='panno', + packages=find_packages(include=['panno', 'panno.*']), + test_suite='tests', + tests_require=test_requirements, + url='https://github.com/PreMedKB/PAnno', + version='0.3.1', + zip_safe=False, +) +","Python" +"Pharmacogenetics","PreMedKB/PAnno","HISTORY.md",".md","0","0","","Markdown" +"Pharmacogenetics","PreMedKB/PAnno","panno/panno.py",".py","4519","114","#!/usr/bin/python +# -*- coding: UTF-8 -*- + +""""""Console script for panno."""""" + +from panno import genotype_resolution, clinical_annotation, pgx_report, predict_diplotype +import getopt, sys, os, re, pyranges +import pandas as pd + +def main(): + + version = 'v0.3.1' + help = ''' + Usage: panno -s sample_id -i germline_vcf -p population -o outdir + + PAnno takes the variant calling format (VCF) file and population information as input + and outputs an HTML report of drug responses with prescription recommendations. + + Options: + + -s, --sample_id TEXT Sample ID that will be displayed in the PAnno report. + + -i, --germline_vcf TEXT Unannotated VCF file, preferably germline variant. + + -p, --population [AAC|AME|EAS|EUR|LAT|NEA|OCE|SAS|SSA] + The three-letter abbreviation for biogeographic groups: + AAC (African American/Afro-Caribbean), AME (American), + EAS (East Asian), EUR (European), LAT (Latino), + NEA (Near Eastern), OCE (Oceanian), + SAS (Central/South Asian), SSA (Sub-Saharan African). + + -o, --outdir TEXT Create report in the specified output path. + + -v, --version Show the version and exit. + + -h, --help Show this message and exit. + ''' + + try: + opts, args = getopt.getopt(sys.argv[1:], ""hvs:i:p:o:"", [""help"", ""version"", ""sample_id="", ""germline_vcf="", ""population="", ""outdir=""]) + if not opts: + print(help) + sys.exit() + except getopt.GetoptError: + print(help) + + for opt, arg in opts: + if opt in (""-h"", ""--help""): + print(help) + sys.exit() + elif opt in (""-v"", ""--version""): + print(version) + sys.exit() + elif opt in (""-s"", ""--sample_id""): + sample_id = arg + elif opt in (""-i"", ""--germline_vcf""): + germline_vcf = arg + elif opt in (""-p"", ""--population""): + population = arg + elif opt in (""-o"", ""--output""): + outdir = arg + + ## Check input arguments + if 'sample_id' not in locals().keys(): + print('\nThe sample ID (-s or --sample_id) is a required parameter, please enter it.') + sys.exit(1) + + if 'germline_vcf' not in locals().keys(): + print('\nThe germline VCF (-i or --germline_vcf) is a required parameter, please enter it.') + sys.exit(1) + elif not os.path.exists(germline_vcf): + print('\n[ERROR] The input germline VCF file does not exist, please check your file path.') + sys.exit(1) + + if 'population' not in locals().keys(): + print('\nThe population (-p or --population) is a required parameter, please enter it.') + sys.exit(1) + else: + population = population.upper() + pop_dic = {'AAC': 'African American/Afro-Caribbean', 'AME': 'American', 'SAS': 'Central/South Asian', 'EAS': 'East Asian', 'EUR': 'European', 'LAT': 'Latino', 'NEA': 'Near Eastern', 'OCE': 'Oceanian', 'SSA': 'Sub-Saharan African'} + if population not in pop_dic.keys(): + print('\n[ERROR] The input population is not included in PAnno. Please check if the abbreviation is used correctly.') + sys.exit(1) + + if 'outdir' not in locals().keys(): + print('\nThe directory for output (-o or --outdir) is a required parameter, please enter it.') + sys.exit(1) + elif not os.path.exists(outdir): + print('\n[WARNING] The directory %s does not exist.' % outdir) + try: + print(' - PAnno is trying to create it.') + os.mkdir(outdir) + except: + print(' - [ERROR] Directory creation failed. Please enter a directory that already exists to re-run PAnno.') + sys.exit(1) + fp = os.path.join(outdir, ""%s.PAnno.html"" % sample_id) + + + ## Start running PAnno + print('\nParsing PGx related diplotypes ...') + dic_diplotype, dic_rs2gt, hla_subtypes = genotype_resolution.resolution(pop_dic[population], germline_vcf) + print('Annotating clinical information ...') + summary, prescribing_info, multi_var, single_var, phenotype_predict, clinical_anno = clinical_annotation.annotation(dic_diplotype, dic_rs2gt, hla_subtypes) + print('Generating PAnno report ...') + race = ""%s (%s)"" % (pop_dic[population], population) + pgx_report.report(race, summary, prescribing_info, multi_var, single_var, phenotype_predict, clinical_anno, fp, sample_id) + + # Finish the task + print('\nYour PAnno report has been completed and is located at %s.' % fp) + print('\n ^ _ ^\n\n') + + +if __name__ == ""__main__"": + main()","Python" +"Pharmacogenetics","PreMedKB/PAnno","panno/predict_diplotype.py",".py","13266","301","#!/usr/bin/python +# -*- coding: UTF-8 -*- + + +import numpy as np +import re, itertools, json, os + + +def parse_input_allele(filtered_vcf, info): + hap_define = info['haplotype_definition'] + hap_define_display = info['haplotype_definition_display'] + ref_hap = info['reference_haplotype'] + + vcf_df_all = filtered_vcf.copy() + vcf_df = vcf_df_all[vcf_df_all['#CHROM'] == info['chrom']] + cols = vcf_df.columns.to_list() + + vcf_alleles = {}; vcf_alleles_display = {} + hap_pos = list(hap_define[ref_hap].keys()) + for source_pos in hap_pos: + # ref_hap_base, Only two loci of CYP2D6 gene will have more than one ref_hap_base + ref_hap_base = hap_define[ref_hap][source_pos] + ref_hap_base_display = hap_define_display[ref_hap][source_pos].split(':')[-1] + + # Get all possible bases at this position + defined = [] + for key in hap_define.keys(): + defined.extend(hap_define[key][source_pos]) + defined = list(set(defined)) + + # Transfer the positions into the format of list + pos_rs = source_pos.split(':') + pos = [] + tmp = pos_rs[0].split('-') + if len(tmp) > 1: + for p in range(int(tmp[0]), int(tmp[1])+1): + pos.append(p) + else: + pos = [int(pos_rs[0])] + + ###### Start to parse the input vcf + # Filter by pos and rs_id + mat = vcf_df[(vcf_df['POS'].isin(pos)) | (vcf_df['ID'] == pos_rs[1])] + if mat.empty: + vcf_alleles[source_pos] = (ref_hap_base, ref_hap_base) + vcf_alleles_display[source_pos] = 'Missing' + else: + is_wild_type = 1 + for index, row in mat.iterrows(): + cols = mat.columns.to_list() + format = row[cols.index(""FORMAT"")].split("":"") + gt = row[-1].split("":"")[format.index(""GT"")] + if re.findall('0', gt) == ['0', '0']: + continue + else: + ## Only process the first line which genotype is not wild type. + ## !!! Therefore, the end of 'else' is break + tuple_res = (); tuple_res_display = () + is_wild_type = 0 + ref = row[cols.index(""REF"")] + alts = row[cols.index(""ALT"")].split("","") + opts = [ref]; opts.extend(alts) + gts = re.split('/|\|', gt) + if len(gts) == 1: # chrX + gts.append(gts[0]) + for gt_index in gts: + base = None; base_raw = None + if gt_index == '0': + base = ref_hap_base; base_raw = ref_hap_base_display + else: + alt = opts[int(gt_index)] + # SNP # + if len(alt) == len(ref): + base = alt + base_raw = alt + ### ! If alt was not match the definition, try to combine with the following position base and test again + # Del # + elif len(alt) < len(ref): + base = 'del%s' % ref[len(alt):] + if base not in defined: + pos_of_mat = mat.index.to_list() + pos_order = pos_of_mat.index(index) + if pos_order < len(pos_of_mat)-1 and mat.loc[pos_of_mat[pos_order+1], 'POS'] == row.POS+1: + new_row = mat.loc[pos_of_mat[pos_order+1],] + base = 'del%s' % ref[len(alt)+1:] + new_row.REF + elif int(row.POS) == 42128173 and base == 'delCTT': + base = 'delTCT' + ## A smooth judge part + if base not in defined: + # small indel + if ref_hap_base[0].startswith('ref') and base[-1] == ref_hap_base[0][-2]: + base = 'del' + base[4:] + ref_hap_base[0][-1] + # long del + else: + modd = ref_hap_base[0].replace('ref', '') + if re.search(modd, base): + matched_span = re.search(modd, base).span() + if modd.startswith(base[matched_span[1]:]): + base = 'del' + modd * int((matched_span[1] - matched_span[0])/len(modd) + 1) + else: + base = 'del' + modd * int((matched_span[1] - matched_span[0])/len(modd)) + base_raw = base + if base not in defined: + print('Warning in Del!'); print(row.T); print(pos); print(base) + # Ins # + elif len(alt) > len(ref): + base = 'ins%s' % alt[len(ref):] + if base not in defined: + pos_of_mat = mat.index.to_list() + pos_order = pos_of_mat.index(index) + if pos_order < len(pos_of_mat)-1 and mat.loc[pos_of_mat[pos_order+1], 'POS'] == row.POS+1: + new_row = mat.loc[pos_of_mat[pos_order+1],] + base = 'ins%s' % alt[len(ref)+1:] + new_row.REF + ## A smooth judge part + if base not in defined: + # small indel + if ref_hap_base[0].startswith('ref') and base[-1] == ref_hap_base[0][-2]: + base = 'ins' + base[4:] + ref_hap_base[0][-1] + # long dup + else: + flag = 0; modd = 'modd' + if ref_hap_base[0].startswith('ref') is False: + for r in defined: + if r.startswith('delins'): + modd = 'C'; flag = 1; break + else: + modd = ref_hap_base[0].replace('ref', '') + # print(mat, defined, ref_hap_base, base, ref, alt, ref_hap) + if modd != 'modd': + if re.search(modd, base): + matched_span = re.search(modd, base).span() + if modd.startswith(base[matched_span[1]:]): + base = 'ins' + modd * int((matched_span[1] - matched_span[0])/len(modd) + 1) + else: + base = 'ins' + modd * int((matched_span[1] - matched_span[0])/len(modd)) + if flag == 1: + base = 'del' + base + 'C' + base_raw = alt + if base not in defined: + print('Warning in Ins or Dup on %s:%s! Input variant is %s, while the definition is %s.' % (info['chrom'], pos, base, '|'.join(defined))) + print(row.to_dict()) + ## Add the result into tuple_res + tuple_res = tuple_res + (base,) + tuple_res_display = tuple_res_display + (base_raw,) + break + + if is_wild_type == 1: + vcf_alleles[source_pos] = (ref_hap_base, ref_hap_base) + vcf_alleles_display[source_pos] = ref_hap_base_display + '/' + ref_hap_base_display + else: + vcf_alleles[source_pos] = tuple_res + # vcf_alleles_display[source_pos] = ';'.join(['|'.join(res) for res in list(zip(tuple_res_display[0], tuple_res_display[1]))]) + vcf_alleles_display[source_pos] = tuple_res_display[0] + '/' + tuple_res_display[1] + if None in tuple_res: + print('Warning! None was reported.') + + # Check the format of output + fine_vcf_alleles = {} + for source_pos in vcf_alleles.keys(): + tuple_res = () + for base in vcf_alleles[source_pos]: + if type(base) != list: + tuple_res = tuple_res + ([base],) + else: + tuple_res = tuple_res + (base,) + fine_vcf_alleles[source_pos] = tuple_res + + return(fine_vcf_alleles, vcf_alleles_display) + + +def predict_diplotype(vcf_alleles, info, race): + hap_define = info['haplotype_definition'] + # CYP2C19 order + all_hap = list(hap_define.keys()) + if all_hap[0] == '*38': + all_hap = ['*1', '*2', '*3', '*4', '*5', '*6', '*7', '*8', '*9', '*10', '*11', '*12', '*13', '*14', '*15', '*16', '*17', '*18', '*19', '*22', '*23', '*24', '*25', '*26', '*28', '*29', '*30', '*31', '*32', '*33', '*34', '*35', '*38', '*39'] + hap_mutated_loci = info['haplotype_mutated_loci'] + diplotype_candidates = list(itertools.combinations_with_replacement(all_hap, 2)) + ### 1st Ranking by haplotype definition + candidate = {} + for dip in diplotype_candidates: + hap1 = hap_define[dip[0]] + hap2 = hap_define[dip[1]] + ## Calculate difference + difference_step1 = dict(zip(vcf_alleles.keys(), [np.nan] * len(hap1))) + for pos_rs in vcf_alleles.keys(): + defined_alleles = list(itertools.product(hap1[pos_rs], hap2[pos_rs])) + tuple_res = vcf_alleles[pos_rs] + alleles = list(itertools.product(tuple_res[0], tuple_res[1])) + # Must sort the results + defined_alleles = [sorted(ele) for ele in defined_alleles] + alleles = [sorted(ele) for ele in alleles] + # Extact matched + score1 = []; score2 = [] + for allele in alleles: + if allele in defined_alleles: + #difference_step1[pos_rs] = 0 + score1 = [0]; score2 = [0] + break + else: + diff = [] + ### Part 1: Input vcf can have more variants than definition but less is better. + for define in defined_alleles: + in_vcf_notin_defined = len(set(allele).difference(set(define))) + if in_vcf_notin_defined == 1: + score1.append(-1) + else: + score1.append(-2) + ### Part 2: Haplotype muated loci. We need to make a case-by-case judgment. + # When only one haplotype is involved in a locus, we do not need to ensure that both strands meet the requirements. + allele_cp = allele + for hap in dip: + score2_hap = 0 + # It is possible to delete both items of allele for degenerate bases. + if len(allele_cp) == 0: + allele_cp = allele + if pos_rs in hap_mutated_loci[hap]: + star_define = hap_define[hap][pos_rs] + star_matched = set(allele_cp).intersection(set(star_define)) + for m in star_matched: + allele_cp.remove(m) + if len(allele_cp) == 2: + score2_hap = -99 + score2.append(score2_hap) + # Add the results of score1 and score2 + difference_step1[pos_rs] = max(score1) + min(score2) + # print(pos_rs, score1, score2) + if min(difference_step1.values()) > -99: + candidate['%s/%s' % (dip[0], dip[1])] = difference_step1 + + # print(candidate.keys()) + # Whether is 0 + exact_match_res = [] + for dip in candidate.keys(): + # print(dip, candidate[dip].values()) + if set(candidate[dip].values()) == {0}: + exact_match_res.append(dip) + + # 1. select diplotypes which 1st rank is max + rank_step1 = {} + for dip in candidate.keys(): + rank_step1[dip] = sum(candidate[dip].values()) + + uniq_diff = sorted(set(rank_step1.values())) + rank_step1_res = [k for k,v in rank_step1.items() if v == max(uniq_diff)]#; rank_step1_res + # 2. only ranked the above diplotypes with population frequency + dip_freq = info['diplotype_frequency'] + rank_step2 = {} + for dip in rank_step1_res: + rank_step2[dip] = dip_freq[dip][race] + uniq_freq = sorted(set(rank_step2.values())) + final_rank_res = [k for k,v in rank_step2.items() if v == max(uniq_freq)]#; final_rank_res + return(""; "".join(exact_match_res), ""; "".join(rank_step1_res), ""; "".join(final_rank_res)) + + +def predict(filtered_vcf, race, gene_list): + panno_dip_fp = os.path.join(os.path.dirname(__file__), 'assets/pgx_diplotypes.json') + # panno_dip_fp = ""./panno/assets/pgx_diplotypes.json"" + panno_dip_base = json.loads(open(panno_dip_fp).read()) + dic_diplotype = {} + dic_diplotype_detail = {} + for gene in gene_list: + info = panno_dip_base[gene] + hap_define_display = info['haplotype_definition_display'] + vcf_alleles, vcf_alleles_display = parse_input_allele(filtered_vcf, info) + exact_match_res, rank_step1_res, final_rank_res = predict_diplotype(vcf_alleles, info, race) + + if final_rank_res == '': + final_rank_res = '-' + + # Detail of diplotypes + if final_rank_res != '-': + tmp = re.split('; |/', final_rank_res) + haplotypes = sorted(set(tmp), key = tmp.index) + else: + haplotypes = [info['reference_haplotype']] + diplotype_details = [] + for source_pos in vcf_alleles_display.keys(): + detected_allele = vcf_alleles_display[source_pos] + base_all = [] + for hap in haplotypes: + chrom, nc, ng, rs, pc, base = hap_define_display[hap][source_pos].split(':') + # position + matchobj = re.search(r'\w\.(\d+)\_(\d+)(del|ins)(\w*)', ng) + if matchobj: + pos = int(matchobj.group(1)) + else: + matchobj = re.search(r'\w\.(\d+)(\w*)', ng) + if matchobj: + pos = matchobj.group(1) + else: + print(ng) + base_all.append(hap + ':' + base) + identified_allele = '; '.join(base_all) + diplotype_details.append((chrom, pos, nc, ng, rs, pc, identified_allele, detected_allele)) + + # Collect the results + dic_diplotype[gene] = {'exact_res': exact_match_res, 'step1_res': rank_step1_res, 'step2_res': final_rank_res, 'detail': diplotype_details} + + return(dic_diplotype) +","Python" +"Pharmacogenetics","PreMedKB/PAnno","panno/__init__.py",".py","165","8","""""""Top-level package for PAnno."""""" + +from __future__ import absolute_import + +__author__ = """"""Yaqing Liu"""""" +__email__ = 'yaqing.liu@outlook.com' +__version__ = '0.3.1' +","Python" +"Pharmacogenetics","PreMedKB/PAnno","panno/test.py",".py","1253","25","import getopt, sys, os +from panno import genotype_resolution, clinical_annotation, pgx_report, predict_diplotype + +demos = {'NA10859':'EUR', 'NA19147': 'AAC', 'NA19785':'LAT', 'HG00436':'EAS'} +pop_dic = {'AAC': 'African American/Afro-Caribbean', 'AME': 'American', 'SAS': 'Central/South Asian', 'EAS': 'East Asian', 'EUR': 'European', 'LAT': 'Latino', 'NEA': 'Near Eastern', 'OCE': 'Oceanian', 'SSA': 'Sub-Saharan African'} + +for sample_id in demos.keys(): + germline_vcf = ""./demo/%s.pgx.vcf"" % sample_id + population = demos[sample_id] + race=pop_dic[population] + outdir=""./demo"" + + ## Start running PAnno + print('\nParsing PGx related genotypes ...') + dic_diplotype, dic_rs2gt, hla_subtypes = genotype_resolution.resolution(pop_dic[population], germline_vcf) + + print('Annotating clinical information ...') + summary, prescribing_info, multi_var, single_var, phenotype_predict, clinical_anno = clinical_annotation.annotation(dic_diplotype, dic_rs2gt, hla_subtypes) + + print('Generating PAnno report ...') + race = ""%s (%s)"" % (pop_dic[population], population) + fp = os.path.join(outdir, ""%s.PAnno.html"" % sample_id) + pgx_report.report(race, summary, prescribing_info, multi_var, single_var, phenotype_predict, clinical_anno, fp, sample_id) + +","Python" +"Pharmacogenetics","PreMedKB/PAnno","panno/clinical_annotation.py",".py","12848","248","#!/usr/bin/python +# -*- coding: UTF-8 -*- + + +import sqlite3, os, re +import pandas as pd +import numpy as np + + +def annotation(dic_diplotype, dic_rs2gt, hla_subtypes): + + ## Connected database + pgx_kb_fp = os.path.join(os.path.dirname(__file__), 'assets/pgx_kb.sqlite3') + # pgx_kb_fp = ""./panno/assets/pgx_kb.sqlite3"" + conn = sqlite3.connect(pgx_kb_fp) + cursor = conn.cursor() + + # DiplotypePhenotype + dip_phe = cursor.execute(""SELECT Gene, Allele1, Allele2, ActivityScore, Phenotype FROM DiplotypePhenotype;"") + dip_phe = cursor.fetchall() + dip_phe_df = pd.DataFrame(dip_phe, columns=['Gene', 'Allele1', 'Allele2', 'ActivityScore', 'Phenotype']) + # Guidelines: CPIC, DPWG, RNPGx, CPNDS + guide = cursor.execute(""SELECT * FROM GuidelineMerge WHERE Source NOT IN ('AusNZ', 'SEFF', 'ACR', 'CFF');"") + guide = cursor.fetchall() + guide_df = pd.DataFrame(guide, columns=['ID', 'Source', 'PAID', 'Summary', 'Phenotype', 'Genotype', 'Recommendation', 'Avoid', 'Alternate', 'Dosing', 'Gene', 'Drug', 'GeneID', 'DrugID']) + rule = cursor.execute(""SELECT Gene, Variant, Allele1, Allele2, Phenotype, GuidelineID FROM GuidelineRule;"") + rule = cursor.fetchall() + rule_df = pd.DataFrame(rule, columns=['Gene', 'Variant', 'Allele1', 'Allele2', 'Phenotype', 'GuidelineID']) + rule_df1 = rule_df[rule_df.Allele2 != ''] + rule_df2 = rule_df[rule_df.Allele2 == ''] + + #### Matched rules + matched_ids = [] + detected_allele = [] # Gene, Variant, Diplotype, Phenotype + # 1. Diplotypes + for gene in dic_diplotype.keys(): + for panno_dip in dic_diplotype[gene]['step2_res'].split(""; ""): + if panno_dip != '-': + allele1 = panno_dip.split(""/"")[0]; allele2 = panno_dip.split(""/"")[1] + # Match phenotype from CPIC tables, if there is no matched items, use the res.Phenotype + sub_dip_phe = pd.concat([dip_phe_df[(dip_phe_df.Gene == gene) & (dip_phe_df.Allele1 == allele1) & (dip_phe_df.Allele2 == allele2)], dip_phe_df[(dip_phe_df.Gene == gene) & (dip_phe_df.Allele1 == allele2) & (dip_phe_df.Allele2 == allele1)]], axis = 0) + # rule_df1 + res = pd.concat([rule_df1[(rule_df1.Gene == gene) & (rule_df1.Allele1 == allele1) & (rule_df1.Allele2 == allele2)], rule_df1[(rule_df1.Gene == gene) & (rule_df1.Allele1 == allele2) & (rule_df1.Allele2 == allele1)]], axis = 0) + matched_ids.extend(res.GuidelineID.to_list()) + if res.empty is False: + if sub_dip_phe.empty is False: + phenotype = sub_dip_phe.Phenotype.to_list()[0] + else: + phenotype = '-'#res.Phenotype.to_list()[0] + detected_allele.append([gene, res.Variant.to_list()[0], panno_dip, phenotype]) + # rule_df2 + res = rule_df2[(rule_df2.Gene == gene) & ((rule_df2.Allele1 == allele1) | (rule_df2.Allele1 == allele2))] + matched_ids.extend(res.GuidelineID.to_list()) + if res.empty is False: + if sub_dip_phe.empty is False: + phenotype = sub_dip_phe.Phenotype.to_list()[0] + else: + phenotype = '-'#res.Phenotype.to_list()[0] + detected_allele.append([gene, res.Variant.to_list()[0], panno_dip, phenotype]) + + # 2. SNP/Indels + rsids = rule_df[rule_df.Variant.str.startswith('rs')].Variant.drop_duplicates().to_list() + for rsid in rsids: + if rsid in dic_rs2gt.keys(): + allele1 = dic_rs2gt[rsid][0]; allele2 = dic_rs2gt[rsid][1] + res = pd.concat([rule_df1[(rule_df1.Gene == gene) & (rule_df1.Allele1 == allele1) & (rule_df1.Allele2 == allele2)], rule_df1[(rule_df1.Gene == gene) & (rule_df1.Allele1 == allele2) & (rule_df1.Allele2 == allele1)]], axis = 0) + matched_ids.extend(res.GuidelineID.to_list()) + if res.empty is False: + detected_allele.append([gene, res.Variant.to_list()[0], '%s%s' % (allele1, allele2), res.Phenotype.to_list()[0]]) + + # 3. HLA + detected_hla = [] + hla_df = rule_df[rule_df.Gene.str.startswith('HLA')] + for index, row in hla_df.iterrows(): + gene = row.Gene; var = row.Allele1 + if var in hla_subtypes[gene].keys(): + if hla_subtypes[gene][var] == 0: + phenotype = 'negative' + detected = 'Zero copy' + hla_var = '%s%s %s' % (gene, var, phenotype) + else: + phenotype = 'positive' + hla_var = '%s%s positive' % (gene, var, phenotype) + if hla_subtypes[gene][var] == 1: + detected = 'One copy' + else: + detected = 'Two copies' + if hla_var == row.Variant: + matched_ids.append(row.GuidelineID) + else: + phenotype = '-' + detected = 'Missing' + detected_hla.append([gene, var, detected, phenotype]) + + # Matched guidelines + mg = guide_df[guide_df.ID.isin(matched_ids)] + # 1. Avoid + avoid_df = mg[mg.Avoid == 1] + avoid_drug = avoid_df.Drug.drop_duplicates().to_list(); len(avoid_drug) + # 2. Caution + caution_df = mg[(mg.Drug.isin(avoid_drug) == False) & ((mg.Alternate == 1) | (mg.Dosing == 1))] + caution_drug = caution_df.Drug.drop_duplicates().to_list(); len(caution_drug) + # 3. Routine + routine_df = mg[(mg.Drug.isin(avoid_drug) == False) & (mg.Drug.isin(caution_drug) == False)] + routine_drug = routine_df.Drug.drop_duplicates().to_list(); len(routine_drug) + + ###--------- Section 1: Summary ---------### + avoid_drug.sort(); caution_drug.sort(); routine_drug.sort() + summary = {'Avoid': avoid_drug, 'Caution': caution_drug, 'Routine': routine_drug} + + ###--------- Section 2: Prescribing Info ---------### + detected_allele.extend(detected_hla) + prescribing_info = pd.DataFrame(detected_allele, columns=['Gene', 'Variant', 'Diplotype', 'Phenotype']).drop_duplicates().merge(mg.drop(columns=['Phenotype']), on=['Gene']) + prescribing_info = prescribing_info[['Drug', 'Gene', 'Variant', 'Diplotype', 'Phenotype', 'Summary', 'Recommendation', 'Source', 'PAID', 'Avoid', 'Alternate', 'Dosing']].sort_values(by=['Drug']) + + ###--------- Section 3: Diplotype Detail ---------### + ## MultiVar + multi = [""CACNA1S"", ""CFTR"", ""CYP2B6"", ""CYP2C8"", ""CYP2C9"", ""CYP2C19"", ""CYP2D6"", ""CYP3A4"", ""CYP3A5"", ""CYP4F2"", ""DPYD"", ""NUDT15"", ""RYR1"", ""SLCO1B1"", ""TPMT"", ""UGT1A1""] + multi_df = [] + for gene in multi: + gene_detail = dic_diplotype[gene]['detail'] + for pos_res in gene_detail: + # chrom, pos, nc, ng, rs, pc, identified_allele, detected_allele + position = str(pos_res[0]) + ':' + str(pos_res[1]) + multi_df.append([gene, dic_diplotype[gene]['step2_res'], position, pos_res[4], pos_res[5], pos_res[6], pos_res[7]]) + + multi_var = pd.DataFrame(multi_df, columns=['Gene', 'Diplotype', 'Position', 'Variant', 'Effect on Protein', 'Definition of Alleles', 'Variant Call']) + + ## SingleVar + # 1. HLA + hla_list = cursor.execute(""SELECT DISTINCT Gene, Allele1 FROM ClinAnn WHERE Gene LIKE 'HLA%' AND EvidenceLevel != 3;"") + hla_list = cursor.fetchall() + for item in hla_list: + gene = item[0]; var = item[1] + if var in hla_subtypes[gene].keys(): + if hla_subtypes[gene][var] == 0: + phenotype = 'negative' + detected = 'Zero copy' + else: + phenotype = 'positive' + if hla_subtypes[gene][var] == 1: + detected = 'One copy' + else: + detected = 'Two copies' + else: + phenotype = '-' + detected = 'Missing' + detected_hla.append([gene, var, detected, phenotype]) + detected_hla_df = pd.DataFrame(detected_hla, columns=['Gene', 'Variant', 'Variant Call', 'Phenotype']).drop(columns=['Phenotype']) + + # 1. SNP/Indel + rsid_anno = cursor.execute('SELECT DISTINCT Gene, Variant FROM ClinAnn WHERE EvidenceLevel != 3 AND Variant LIKE ""rs%"" AND (Gene != ""IFNL3"" OR Variant != ""rs12979860"");') + rsid_anno = cursor.fetchall() + rsid_anno_df = pd.DataFrame(rsid_anno, columns = ['Gene', 'Variant']) + rsid_guide_df = rule_df[rule_df.Variant.str.startswith('rs')][['Gene', 'Variant']] + rsid_df = pd.concat([rsid_anno_df, rsid_guide_df], axis = 0).drop_duplicates().reset_index(drop = True) + rsid_df.insert(2, 'Variant Call', 'Missing') + for index, row in rsid_df.iterrows(): + rsid = row.Variant + if row.Variant in dic_rs2gt.keys(): + allele1 = dic_rs2gt[rsid][0]; allele2 = dic_rs2gt[rsid][1] + row['Variant Call'] = '%s/%s' % (allele1, allele2) + rsid_df.iloc[index] = row + + single_var = pd.concat([rsid_df, detected_hla_df], axis = 0).drop_duplicates().sort_values(by=['Gene', 'Variant']) + + + ######## Find ClinAnn and extract the table + ann = cursor.execute(""SELECT * FROM ClinAnn WHERE EvidenceLevel != '3';"")# OR (Gene IN (SELECT Gene FROM GuidelineMerge) AND Drug IN (SELECT Drug FROM GuidelineMerge));"") + ann = cursor.fetchall() + ann_df = pd.DataFrame(ann, columns=['ID', 'CAID', 'Gene', 'Variant', 'Allele1', 'Allele2', 'Annotation1', 'Annotation2', 'Function1', 'Function2', 'Score1', 'Score2', 'CPICPhenotype', 'PAnnoPhenotype', 'Drug', 'Phenotypes', 'EvidenceLevel', 'LevelOverride', 'LevelModifier', 'Score', 'PMIDCount', 'EvidenceCount', 'Specialty', 'PhenotypeCategory']) + ann_df.PhenotypeCategory = ann_df.PhenotypeCategory.replace('Metabolism/PK', 'Metabolism') + + # 0. Filter rs12979860 (IFNL3 and IFNL4) + rm_index = ann_df[(ann_df.Variant == 'rs12979860') & (ann_df.Gene == 'IFNL3')].ID.to_list() + ann_df = ann_df[ann_df.ID.isin(rm_index) == False] + + # 1. Filter by variant + ann_df_retain = pd.DataFrame() + for index, row in single_var.iterrows(): + if row['Variant Call'] != 'Missing': + if row['Variant'].startswith('rs'): + allele1 = row['Variant Call'].split('/')[0] + allele2 = row['Variant Call'].split('/')[1] + res = ann_df[(ann_df.Gene == row.Gene) & (ann_df.Variant == row.Variant) & (((ann_df.Allele1 == allele1) & (ann_df.Allele2 == allele2)) | ((ann_df.Allele1 == allele2) & (ann_df.Allele2 == allele1)))] + res.insert(0, 'VariantNew', row['Variant']) + res.insert(1, 'Diplotype', row['Variant Call']) + elif row['Variant Call'] != 'Zero copy': + res = ann_df[(ann_df.Gene == row.Gene) & ((ann_df.Allele1 == row.Variant) | (ann_df.Allele2 == row.Variant))] + res.insert(0, 'VariantNew', row['Variant']) + res.insert(1, 'Diplotype', row['Variant Call']) + ann_df_retain = pd.concat([ann_df_retain, res]) + + for index, row in multi_var[['Gene', 'Diplotype']].drop_duplicates().iterrows(): + gene = row.Gene + allele1 = row.Diplotype.split('/')[0]; allele2 = row.Diplotype.split('/')[1] + res = ann_df[(ann_df.Gene == row.Gene) & (((ann_df.Allele1 == allele1) & (ann_df.Allele2 == allele2)) | ((ann_df.Allele1 == allele2) & (ann_df.Allele2 == allele1)))] + res.insert(0, 'VariantNew', '') + res.insert(1, 'Diplotype', row.Diplotype) + ann_df_retain = pd.concat([ann_df_retain, res]) + + # 2. Filter by drug, remove the avoid use drugs + ann_df_retain = ann_df_retain[ann_df_retain.Drug.isin(routine_drug + caution_drug)].reset_index(drop = True) + # # Check whether drugs are included in ann_df + # for drug in routine_drug + caution_drug: + # if ann_df_retain[ann_df_retain.Drug == drug].empty: + # print(drug) + + ###--------- Section 4: Phenotype Prediction ---------### + summary['NotInAnno'] = mg[mg.Drug.isin(ann_df.Drug.to_list()) == False].Drug.drop_duplicates().to_list() + # Categorize by phenotypes and drugs + ann_df_retain.insert(0, 'PAnnoScore', np.nan) + for index, row in ann_df_retain.iterrows(): + if np.isnan(row.Score2) and row.Variant.startswith('rs'): + row.PAnnoScore = row.Score1 + row.Score1 + else: + row.PAnnoScore = row.Score1 + row.Score2 + ann_df_retain.iloc[index] = row + + phenotype_predict = pd.DataFrame() + categories = ['Toxicity', 'Dosage', 'Efficacy', 'Metabolism', 'Other'] + for cat in categories: + cat_df = ann_df_retain[ann_df_retain.PhenotypeCategory == cat] + # Calculating cat_pgx + cat_pgx = cat_df.groupby(""Drug"")[['PAnnoScore']].mean() + cat_pgx_count = cat_df.groupby(""Drug"")[['PAnnoScore']].count().rename(columns={'PAnnoScore': 'Count'}) + cat_pgx = cat_pgx.merge(cat_pgx_count, left_index=True, right_index=True) + cat_pgx['PhenotypeCategory'] = cat + cat_pgx['Prediction'] = '' + cat_pgx.insert(0, 'Drug', cat_pgx.index) + cat_pgx = cat_pgx.reset_index(drop=True) + for index, row in cat_pgx.iterrows(): + if row.PAnnoScore <= 1.5: + cat_pgx.loc[index, 'Prediction'] = 'Decreased' + elif row.PAnnoScore >= 2.5: + cat_pgx.loc[index, 'Prediction'] = 'Increased' + else: + cat_pgx.loc[index, 'Prediction'] = 'Normal' + phenotype_predict = pd.concat([phenotype_predict, cat_pgx]).sort_values(by=['Drug']) + + ###--------- Section 5: Clinical Annotation ---------### + clinical_anno = ann_df_retain[['Drug', 'Gene', 'VariantNew', 'Diplotype', 'PhenotypeCategory', 'EvidenceLevel', 'PAnnoPhenotype', 'CAID']].rename(columns={'VariantNew': 'Variant'}).drop_duplicates().sort_values(by=['Drug']) + + cursor.close() + conn.close() + + return(summary, prescribing_info, multi_var, single_var, phenotype_predict, clinical_anno) +","Python" +"Pharmacogenetics","PreMedKB/PAnno","panno/genotype_resolution.py",".py","4015","97","#!/usr/bin/python +# -*- coding: UTF-8 -*- + + +from panno import predict_diplotype +import re, os, pyranges +import pandas as pd + +def resolution(race, germline_vcf): + + panno_bed_fp = os.path.join(os.path.dirname(__file__), 'assets/pgx_loci.bed') + # panno_bed_fp='./panno/assets/pgx_loci.bed' + ## Filter loci based on PharmGKB's bed file: delete all loci in the user's vcf that are not in the panno.bed file + ## Extract the user's bed file: skip the lines starting with '##' + vcf = [] + vcf_bed = [] + with open(germline_vcf, ""r"", encoding = ""utf-8"") as file: + for line in file: + if 'CHROM' in line: + colnames = line.strip().split('\t') + if line[0] != '#': + info = line.strip().split('\t') + vcf.append(info) + vcf_bed.append([info[0], info[1], info[1]]) + + vcf_bed_df = pd.DataFrame(vcf_bed, columns=['Chromosome', 'Start', 'End']) + panno_bed = pd.read_csv(panno_bed_fp, sep=""\t"", names=['Chromosome', 'Start', 'End', 'rsid']) + vcf_bed_df['Chromosome'] = vcf_bed_df['Chromosome'].map(lambda x: re.sub('chr|Chr|CHR', '', x)).astype('str') + panno_bed['Chromosome'] = panno_bed['Chromosome'].map(lambda x: re.sub('chr|Chr|CHR', '', x)).astype('str') + + ## Filter the BED of the input VCF based on the overlap with PAnno BED + gr1, gr2 = pyranges.PyRanges(vcf_bed_df), pyranges.PyRanges(panno_bed.iloc[:,:3]) + # pyranges will not process the item with equal start and end, which is different from pybedtools + gr1.End, gr2.End = gr1.End + 1, gr2.End + 1 + filter_bed = gr1.overlap(gr2).df + filter_bed.End = filter_bed.End - 1 + + ## Convert the input VCF into a data frame and filter it + vcf_df = pd.DataFrame(vcf, columns=colnames) + vcf_df.loc[:,'#CHROM'] = vcf_df['#CHROM'].map(lambda x: re.sub('chr|Chr|CHR', '', x)).astype('str') + vcf_df.loc[:,colnames[1]] = vcf_df[colnames[1]].astype('int32') + filter_bed = filter_bed.iloc[:, 0:2].rename(columns={'Chromosome': colnames[0], 'Start': colnames[1]}) + filtered_vcf = pd.merge(vcf_df, filter_bed, how='inner', on=colnames[:2]) + + ## Class 1: Diplotype + gene_list = [""G6PD"", ""MT-RNR1"", ""ABCG2"", ""CACNA1S"", ""CFTR"", ""IFNL3"", ""VKORC1"", ""RYR1"", + ""CYP2B6"", ""CYP2C8"", ""CYP2C9"", ""CYP2C19"", ""CYP2D6"", + ""CYP3A4"", ""CYP3A5"", ""CYP4F2"", ""DPYD"", ""NUDT15"", + ""SLCO1B1"", ""TPMT"", ""UGT1A1""] + dic_diplotype = predict_diplotype.predict(filtered_vcf, race, gene_list) + ## Class 2: HLA genes + hla_subtypes = {""HLA-A"": {}, ""HLA-B"": {}, ""HLA-C"": {}, ""HLA-DRB1"": {}, ""HLA-DPB1"": {}} + ## Class 3: Genotypes of detected positions + dic_rs2gt = {} + format_index = colnames.index(""FORMAT"") + # Reload panno_bed + panno_bed_rsid = panno_bed.dropna() + for index, row in filtered_vcf.iterrows(): + info = row.to_list() + format = info[format_index].split("":"") + gt_index = format.index(""GT"") + gt = info[-1].split("":"")[gt_index] + if re.findall('0', gt) == ['0', '0']: + genotype = 0 + elif re.findall('0', gt) == ['0']: + genotype = 1 + else: + genotype = 2 + # HLA genes + if row[0].startswith('HLA'): + gene = row[0].split('*')[0] + if gene in hla_subtypes.keys(): + hla_subtypes[gene].update({'*%s' % row[0].split('*')[1]: genotype}) + # hla_subtypes[row[0]] = genotype + # If the variant was within the clinical relevant list, add it into dis_rs2gt + tmp = panno_bed_rsid[(panno_bed_rsid.Chromosome == info[0]) & (panno_bed_rsid.Start == info[1])].rsid.to_list() + if tmp != []: + rsids = tmp + elif info[2] in panno_bed_rsid.rsid.to_list(): # The genome coordinates of a rsID may not complete. + rsids = [info[2]] + else: + rsids = None + + if rsids: + ref = info[3] + alts = info[4].split(',') + alleles = [ref] + alts + var = [] + for g in re.split('\||/', gt): + var.append(alleles[int(g)]) + for rsid in rsids: + # Variants in chrX, chrY + if len(var) == 1: + var.append('') + dic_rs2gt[rsid] = tuple(var) + + return(dic_diplotype, dic_rs2gt, hla_subtypes)","Python" +"Pharmacogenetics","PreMedKB/PAnno","panno/pgx_report.py",".py","25763","478","#!/usr/bin/python +# -*- coding: UTF-8 -*- + + +import time, os, base64 +from itertools import * + + +def report (race, summary, prescribing_info, multi_var, single_var, phenotype_predict, clinical_anno, fp, sample_id): + with open(fp, 'w+', encoding=""utf-8"") as f: + ## Style + css_fp = os.path.join(os.path.dirname(__file__), 'assets/custom.css') + logo_fp = os.path.join(os.path.dirname(__file__), 'assets/panno_logo.png') + icon_fp = os.path.join(os.path.dirname(__file__), 'assets/panno_icon.png') + # css_fp = os.path.join('./panno/assets/custom.css') + # logo_fp = os.path.join('./panno/assets/panno_logo.png') + # icon_fp = os.path.join('./panno/assets/panno_icon.png') + logo_base64 = base64.b64encode(open(logo_fp, ""rb"").read()).decode() + icon_base64 = base64.b64encode(open(icon_fp, ""rb"").read()).decode() + + head_nav="""""" + + + + + + + PAnno Report + + + + + + + + +
+ """""" + print(head_nav%(icon_base64, open(css_fp).read(), icon_base64, 'v0.3.1'), file=f) + + + ## Part 0: Basic information + basic_info = """""" +

+ + + +

+

+ An automated clinical pharmacogenomics annotation tool to report drug responses and prescribing recommendations by parsing the germline variants. +

+
+

Sample ID: %s
Biogeographic Group: %s
Report Time: %s

+
+ """""" + print(basic_info%(logo_base64, sample_id, race, time.asctime(time.localtime(time.time()))), file=f) + + + ## Part 1: Sort disclaimer + disclaimer_short = """""" +
+ Disclaimer: The PAnno report iterates as the release version changes. In the current release, you should only use it to evaluate whether PAnno will compile and run properly on your system. All information in the report is interpreted directly from the uploaded VCF file. Users recognize that they use it at their own risk. +
+ """""" + print(disclaimer_short, file=f) + + + ## Part 2: Pharmacogenomics Annotation + part2_header = """""" +

Summary

+

+ Drugs are classified to indicate whether the clinical guidelines recommend a prescribing change based on the given diplotypes. Original prescribing information was collected by PharmGKB, primarily from the Clinical Pharmacogenetics Implementation Consortium (CPIC), the Dutch Pharmacogenetics Working Group (DPWG), the Canadian Pharmacogenomics Network for Drug Safety (CPNDS), the French National Network of Pharmacogenetics (RNPGx). +

+ + """""" + print(part2_header, file=f) + + print('Avoid use
Avoidance of a drug is clearly stated in the prescribing recommendations for the given diplotype.
',file=f) + + header = '\n' + i = 0 + while i' + if summary['Avoid'][i] is not None: + a1 = summary['Avoid'][i] + else: + a1 = '' + if (i+1) < len(summary['Avoid']): + a2 = summary['Avoid'][i+1] + else: + a2 = '' + if (i+2) < len(summary['Avoid']): + a3 = summary['Avoid'][i+2] + else: + a3 = '' + if (i+3) < len(summary['Avoid']): + a4 = summary['Avoid'][i+3] + else: + a4 = '' + if (i+4) < len(summary['Avoid']): + a5 = summary['Avoid'][i+4] + else: + a5 = '' + if (i+5) < len(summary['Avoid']): + a6 = summary['Avoid'][i+5] + else: + a6 = '' + if (i+6) < len(summary['Avoid']): + a7 = summary['Avoid'][i+6] + else: + a7 = '' + header = header + '' % (a1,a1,a2,a2,a3,a3,a4,a4,a5,a5,a6,a6,a7,a7) + header = header + '' + i = i+7 + header = header + '\n
%s%s%s%s%s%s%s
' + print(header, file=f) + + print('Use with caution
Prescribing changes are recommended for the given diplotype, e.g., dose adjustment and alternative medication. In addition, prescribing recommendations that differ in specific populations or require consideration of multiple diplotypes are included in this category.
',file=f) + header = '\n' + i = 0 + while i' + if summary['Caution'][i] is not None: + a1 = summary['Caution'][i] + else: + a1 = '' + if (i+1) < len(summary['Caution']): + a2 = summary['Caution'][i+1] + else: + a2 = '' + if (i+2) < len(summary['Caution']): + a3 = summary['Caution'][i+2] + else: + a3 = '' + if (i+3) < len(summary['Caution']): + a4 = summary['Caution'][i+3] + else: + a4 = '' + if (i+4) < len(summary['Caution']): + a5 = summary['Caution'][i+4] + else: + a5 = '' + if (i+5) < len(summary['Caution']): + a6 = summary['Caution'][i+5] + else: + a6 = '' + if (i+6) < len(summary['Caution']): + a7 = summary['Caution'][i+6] + else: + a7 = '' + header = header + '' % (a1,a1,a2,a2,a3,a3,a4,a4,a5,a5,a6,a6,a7,a7) + header = header + '' + i = i+7 + header = header + '\n
%s%s%s%s%s%s%s
' + print(header, file=f) + + print('Routine use
There is no recommended prescribing change for the given diplotype.
',file=f) + header = '\n' + i = 0 + while i' + if summary['Routine'][i] is not None: + a1 = summary['Routine'][i] + else: + a1 = '' + if (i+1) < len(summary['Routine']): + a2 = summary['Routine'][i+1] + else: + a2 = '' + if (i+2) < len(summary['Routine']): + a3 = summary['Routine'][i+2] + else: + a3 = '' + if (i+3) < len(summary['Routine']): + a4 = summary['Routine'][i+3] + else: + a4 = '' + if (i+4) < len(summary['Routine']): + a5 = summary['Routine'][i+4] + else: + a5 = '' + if (i+5) < len(summary['Routine']): + a6 = summary['Routine'][i+5] + else: + a6 = '' + if (i+6) < len(summary['Routine']): + a7 = summary['Routine'][i+6] + else: + a7 = '' + header = header + '' % (a1,a1,a2,a2,a3,a3,a4,a4,a5,a5,a6,a6,a7,a7) + header = header + '' + i = i+7 + header = header + '\n
%s%s%s%s%s%s%s
' + print(header, file=f) + + + ## Part 3: Prescribing Info + print('

Prescribing Info

', file=f) + + for drug in list(prescribing_info.Drug.drop_duplicates()): + print('

%s

' % (drug,drug), file=f) + drug_sub = prescribing_info[prescribing_info.Drug == drug] + for gene in list(drug_sub.Gene.drop_duplicates()): + drug_by_gene = drug_sub[drug_sub.Gene == gene] + # Clean the output + phenotype = list(drug_by_gene.Phenotype.drop_duplicates()) + diplotype = list(drug_by_gene.Diplotype.drop_duplicates()) + if len(phenotype) > 1: + # print(phenotype) + phenotype = [phenotype[0]] + # if len(diplotype) > 1: + # print(diplotype) + + print('

Gene: %s    Diplotype: %s    Phenotype: %s

' % (gene, ''.join(diplotype) , ''.join(phenotype)), file=f) + + drug_guide = drug_by_gene[['PAID', 'Source', 'Summary','Recommendation']].copy() + drug_guide = drug_guide.drop_duplicates() + for index, row in drug_guide.iterrows(): + summary_text = row.Summary.replace(' """"The genotype', ' The genotype').replace('""""', '""').replace(""''"", ""'"").strip('""').strip(""'"") + recommend_text = row.Recommendation.replace(' """"The genotype', ' The genotype').replace('""""', '""').replace(""''"", ""'"").strip('""').strip(""'"") + print('
%s
Summary: %s
Recommendation: %s
' % (""https://www.pharmgkb.org/guidelineAnnotation/""+row.PAID, row.Source, summary_text, recommend_text), file=f) + + + ## Part 4: Diplotype Detail + print('

Diplotype Detail

', file=f) + print('

Multi-variant allele

', file=f) + print('

PAnno ranking model is applied to predict diplotypes consisting of multiple variants. The diplotypes are inferred by integrating allele definition consistency as well as the population allele frequency. PGx genes include CYP2B6, CYP2C19, CYP2C8, CYP2C9, CYP2D6, CYP3A4, CYP3A5, CYP4F2, DPYD, NUDT15, SLCO1B1, TPMT, and UGT1A1. Note that PAnno assumes that no variation occurs for the missing positions in the submitted VCF file.

', file=f) + for gene in [""CYP2B6"", ""CYP2C8"", ""CYP2C9"", ""CYP2C19"", ""CYP2D6"", ""CYP3A4"", ""CYP3A5"", ""CYP4F2"", ""DPYD"", ""NUDT15"", ""SLCO1B1"", ""TPMT"", ""UGT1A1""]: + diplotype_by_gene = multi_var[multi_var.Gene == gene] + dip = list(diplotype_by_gene.Diplotype.drop_duplicates()) + if len(dip) > 1: + print('Warning: There is more than one diplotype of %s inferred by PAnno.' % gene) + print('

%s: %s

' % (gene, ''.join(dip)), file=f) + if (gene == ""CYP2B6""): + print('
Please notice that CYP2B6*29, CYP2B6*30 are not considered in the current version, which could potentially have an impact on the results.
', file=f) + if (gene == ""CYP2C19""): + print('
Please notice that CYP2C19*36, CYP2C19*37 are not considered in the current version, which could potentially have an impact on the results.
', file=f) + if (gene == ""CYP2D6""): + print('
Please notice that CYP2D6*5, CYP2D6*13, CYP2D6*61, CYP2D6*63, CYP2D6*68 and CYP2D6 CNVs are not considered in the current version, which could potentially have an impact on the results.
', file=f) + if (gene == ""SLCO1B1""): + print('
Please notice that SLCO1B1*48, SLCO1B1*49 are not considered in the current version, which could potentially have an impact on the results.
', file=f) + + alleles_definition = diplotype_by_gene['Definition of Alleles'].str.split(""; |:"", expand=True) + if alleles_definition.shape[1] == 4: + col_d1 = 'Definition of %s' % alleles_definition.iloc[0,0] + col_d2 = 'Definition of %s' % alleles_definition.iloc[0,2] + diplotype_by_gene.insert(diplotype_by_gene.shape[1], col_d1, alleles_definition.iloc[:,1]) + diplotype_by_gene.insert(diplotype_by_gene.shape[1], col_d2, alleles_definition.iloc[:,3]) + header = '\n' % (col_d1, col_d2) + for index, row in diplotype_by_gene.iterrows(): + co = 'color:#7C3A37;' if (row['Variant Call'] == ""Missing"") else 'color:#444' + header = header + '\n' % (row['Position'], row['Variant'] , row['Effect on Protein'], row[col_d1], row[col_d2], co, row['Variant Call']) + elif alleles_definition.shape[1] == 2: + col_d1 = 'Definition of %s' % alleles_definition.iloc[0,0] + diplotype_by_gene.insert(diplotype_by_gene.shape[1], col_d1, alleles_definition.iloc[:,1]) + header = '
PositionVariantEffect on Protein%s%sVariant Call
%s%s%s%s%s%s
\n' % col_d1 + for index, row in diplotype_by_gene.iterrows(): + co = 'color:#7C3A37;' if (row['Variant Call'] == ""Missing"") else 'color:#444' + header = header + '\n' % (row['Position'], row['Variant'] , row['Effect on Protein'], row[col_d1], co, row['Variant Call']) + else: + for index, row in diplotype_by_gene.iterrows(): + co = 'color:#7C3A37;' if (row['Variant Call'] == ""Missing"") else 'color:#444' + header = header + '\n' % (row['Position'], row['Variant'] , row['Effect on Protein'], row['Definition of Alleles'], co, row['Variant Call']) + header = header + '\n
PositionVariantEffect on Protein%sVariant Call
%s%s%s%s%s
%s%s%s%s%s
' + print(header, file=f) + + print('

Single-variant allele

', file=f) + print('

Single-variant alleles constitute diplotypes that do not involve the judgment of multiple variants and the corresponding genes generally have not yet been standardized by a nomenclature committee, such as rs9923231 for VKORC1.

', file=f) + header = '\n' + for index, row in single_var.iterrows(): + co = 'color:#7C3A37;' if (row['Variant Call'] == ""Missing"") else 'color:#444' + header = header + '\n' % (row.Gene, row.Variant, co,row['Variant Call']) + header = header + '\n
GeneVariantVariant Call
%s%s%s
' + print(header, file=f) + + + ## Part 5: Phenotype Prediction + if summary['Avoid']: + drug1 = ', '.join(summary['Avoid']) + else: + drug1 = 'N/A' + if summary['NotInAnno']: + drug2 = ', '.join(summary['NotInAnno']) + else: + drug2 = 'N/A' + + phenotype_header = """""" +

Phenotype Prediction

+

For the clinically available drugs, PAnno integrates the effects of multiple diplotypes for each drug in terms of toxicity, dosage, efficacy, and metabolism. The predicted phenotypes are based on PharmGKB's high-confidence clinical annotations (evidence levels 1A, 1B, 2A, 2B) and are indicated as decreased, normal, and increased.

+
+ Drugs not further annotated due to ""Avoid use"": %s.
Drugs not included in clinical annotations used by PAnno: %s. +
+ """""" + print(phenotype_header%(drug1, drug2), file=f) + + header = '\n' + for drug in list(phenotype_predict.Drug.drop_duplicates()): + drug_sub = phenotype_predict[phenotype_predict.Drug == drug] + toxicity = '' + dosage = '' + efficacy = '' + metabolism = '' + other = '' + for index, row in drug_sub.iterrows(): + if row.PhenotypeCategory == 'Toxicity': + toxicity = row.Prediction + if row.PhenotypeCategory == 'Dosage': + dosage = row.Prediction + if row.PhenotypeCategory == 'Efficacy': + efficacy = row.Prediction + if row.PhenotypeCategory == 'Metabolism': + metabolism = row.Prediction + if row.PhenotypeCategory == 'Other': + other = row.Prediction + + # End of one drug + if toxicity == '': + toxicity = '-' + if dosage == '': + dosage = '-' + if efficacy == '': + efficacy = '-' + if metabolism == '': + metabolism = '-' + if toxicity == 'Normal': + col2 = 'color:#35787F' + col3 = '◎ ' + elif toxicity == 'Increased': + col2 = 'color:#BC3837' + col3='⤊ ' + elif toxicity == 'Decreased': + col2 ='color:#563E82' + col3='⤋ ' + else: + col2 ='color:#000000' + col3='' + + if dosage == 'Normal': + col4 = 'color:#35787F' + col5 = '◎ ' + elif dosage == 'Increased': + col4 = 'color:#BC3837' + col5='⤊ ' + elif dosage == 'Decreased': + col4 ='color:#563E82' + col5='⤋ ' + else: + col4 ='color:#000000' + col5='' + + if efficacy == 'Normal': + col6 = 'color:#35787F' + col7 = '◎ ' + elif efficacy == 'Increased': + col6 = 'color:#BC3837' + col7='⤊ ' + elif efficacy == 'Decreased': + col6 ='color:#563E82' + col7='⤋ ' + else: + col6 ='color:#000000' + col7='' + + if efficacy == 'Normal': + col6 = 'color:#35787F' + col7 = '◎ ' + elif efficacy == 'Increased': + col6 = 'color:#BC3837' + col7='⤊ ' + elif efficacy == 'Decreased': + col6 ='color:#563E82' + col7='⤋ ' + else: + col6 ='color:#000000' + col7='' + + if metabolism == 'Normal': + col8 = 'color:#35787F' + col9 = '◎ ' + elif metabolism == 'Increased': + col8 = 'color:#BC3837' + col9='⤊ ' + elif metabolism == 'Decreased': + col8 ='color:#563E82' + col9='⤋ ' + else: + col8 ='color:#000000' + col9='' + + header = header + '\n' % (drug, col2, col3+toxicity, col4, col5+dosage, col6, col7+efficacy, col8, col9+metabolism) + + header = header + '\n
DrugToxicityDosageEfficacyMetabolism
%s%s%s%s%s
' + print(header, file=f) + + + # Part 6: Clinical Annotation + print('

Clinical Annotation

', file=f) + print('

This section lists the clinical annotations on which the phenotype predictions are based.

', file=f) + + header = '\n' + for drug in list(clinical_anno.Drug.drop_duplicates()): + drug_sub = clinical_anno[clinical_anno.Drug == drug] + # There needs to be a value dedicated to statistics corresponding to several catagories. + count = len(drug_sub.PhenotypeCategory.drop_duplicates()) + header = header + '\n' % (len(drug_sub)+count,drug) + for category in ['Toxicity','Dosage','Efficacy','Metabolism','Other']: + drug_by_cat = drug_sub[drug_sub.PhenotypeCategory == category].sort_values(by=['EvidenceLevel', 'Gene', 'Variant', 'Diplotype']) + if len(drug_by_cat) > 0: + header = header + '\n' % (len(drug_by_cat)+1,category) + for index, row in drug_by_cat.iterrows(): + # col1 = 'color:#25B16B' if ((row['EvidenceLevel'] == ""1A"") or (row['EvidenceLevel'] == ""1B"")) else 'color:#216ED4' + col1 = 'level-1a1b' if ((row['EvidenceLevel'] == ""1A"") or (row['EvidenceLevel'] == ""1B"")) else 'level-2a2b' + if row.PAnnoPhenotype == ""Normal"": + col2 = 'color:#35787F' + col3 = '◎ ' + elif row.PAnnoPhenotype == ""Increased"": + col2 = 'color:#BC3837' + col3='⤊ ' + else: + col2 ='color:#563E82' + col3='⤋ ' + + header = header + '\n' % (row.Gene, row.Variant, row.Diplotype, col1, row.EvidenceLevel, col2, col3+row.PAnnoPhenotype, ""https://www.pharmgkb.org/clinicalAnnotation/""+str(row.CAID),row.CAID) + # for index, row in drug_by_cat.iterrows(): + # header = header + '\n' % (row.Gene, row.Variant, row.Diplotype, row.EvidenceLevel, row.PAnnoPhenotype, ""https://www.pharmgkb.org/clinicalAnnotation/""+str(row.CAID)) + header = header + '\n
DrugCategoryGeneVariantDiplotypeLevelPhenotypePharmGKB ID
%s%s
%s%s%s%s%s%s
%s%s%s%s%s
' + print(header, file=f) + + + # Part 7: About + disclaimer = """""" +

About

+

+ The report incorporates analyses of peer-reviewed studies and other publicly available information identified by PAnno by State Key Laboratory of Genetic Engineering from the School of Life Sciences and Human Phenome Institute, Fudan University, Shanghai, China. These analyses and information may include associations between a molecular alteration (or lack of alteration) and one or more drugs with potential clinical benefit (or potential lack of clinical benefit), including drug candidates that are being studied in clinical research.
+ Note: A finding of biomarker alteration does not necessarily indicate pharmacologic effectiveness (or lack thereof) of any drug or treatment regimen; a finding of no biomarker alteration does not necessarily indicate lack of pharmacologic effectiveness (or effectiveness) of any drug or treatment regimen.
+ No Guarantee of Clinical Benefit: This Report makes no promises or guarantees that a particular drug will be effective in the treatment of disease in any patient. This report also makes no promises or guarantees that a drug with a potential lack of clinical benefit will provide no clinical benefit.
+ Treatment Decisions are Responsibility of Physician: Drugs referenced in this report may not be suitable for a particular patient. The selection of any, all, or none of the drugs associated with potential clinical benefit (or potential lack of clinical benefit) resides entirely within the discretion of the treating physician. Indeed, the information in this report must be considered in conjunction with all other relevant information regarding a particular patient, before the patient's treating physician recommends a course of treatment. Decisions on patient care and treatment must be based on the independent medical judgment of the treating physician, taking into consideration all applicable information concerning the patient's condition, such as patient and family history, physical examinations, information from other diagnostic tests, and patient preferences, following the standard of care in a given community. A treating physician's decisions should not be based on a single test, such as this test or the information contained in this report.
+ When using results obtained from PAnno, you agree to cite PAnno. +

+
+ +
+

+ + PAnno v0.3.1 + + - Written by Yaqing Liu, et al., + available at GitHub, + PyPI, and Conda. +
+ Copyright © 2021-2022 Center for Pharmacogenomics, Fudan University, China. All Rights Reserved. +

+
+ + + + """""" + print(disclaimer, file=f)","Python" +"Pharmacogenetics","PreMedKB/PAnno","conda.recipe/build.sh",".sh","116","4","# $PYTHON -m pip install . --no-deps --ignore-installed -vv +# Install PAnno +# $PYTHON setup.py install +pip install .","Shell" +"Pharmacogenetics","PreMedKB/PAnno","docs/conf.py",".py","4746","163","#!/usr/bin/env python +# +# panno documentation build configuration file, created by +# sphinx-quickstart on Fri Jun 9 13:47:02 2017. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +# If extensions (or modules to document with autodoc) are in another +# directory, add these directories to sys.path here. If the directory is +# relative to the documentation root, use os.path.abspath to make it +# absolute, like shown here. +# +import os +import sys +sys.path.insert(0, os.path.abspath('..')) + +import panno + +# -- General configuration --------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +# source_suffix = ['.rst', '.md'] +source_suffix = '.rst' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = 'PAnno' +copyright = ""2022, Yaqing Liu"" +author = ""Yaqing Liu"" + +# The version info for the project you're documenting, acts as replacement +# for |version| and |release|, also used in various other places throughout +# the built documents. +# +# The short X.Y version. +version = panno.__version__ +# The full version, including alpha/beta/rc tags. +release = panno.__version__ + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set ""language"" from the command line for these cases. +language = None + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This patterns also effect to html_static_path and html_extra_path +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = False + + +# -- Options for HTML output ------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = 'alabaster' + +# Theme options are theme-specific and customize the look and feel of a +# theme further. For a list of options available for each theme, see the +# documentation. +# +# html_theme_options = {} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named ""default.css"" will overwrite the builtin ""default.css"". +html_static_path = ['_static'] + + +# -- Options for HTMLHelp output --------------------------------------- + +# Output file base name for HTML help builder. +htmlhelp_basename = 'pannodoc' + + +# -- Options for LaTeX output ------------------------------------------ + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass +# [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'panno.tex', + 'PAnno Documentation', + 'Yaqing Liu', 'manual'), +] + + +# -- Options for manual page output ------------------------------------ + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'panno', + 'PAnno Documentation', + [author], 1) +] + + +# -- Options for Texinfo output ---------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'panno', + 'PAnno Documentation', + author, + 'panno', + 'One line description of project.', + 'Miscellaneous'), +] + + + +","Python" +"Pharmacogenetics","PreMedKB/PAnno","tests/test_panno.py",".py","394","22","#!/usr/bin/env python + +""""""Tests for `panno` package."""""" + + +import unittest + +from premedkb_panno import panno + + +class TestCpat(unittest.TestCase): + """"""Tests for `premedkb_panno` package."""""" + + def setUp(self): + """"""Set up test fixtures, if any."""""" + + def tearDown(self): + """"""Tear down test fixtures, if any."""""" + + def test_000_something(self): + """"""Test something."""""" +","Python" +"Pharmacogenetics","PreMedKB/PAnno","tests/__init__.py",".py","35","2","""""""Unit test package for panno."""""" +","Python" +"Pharmacogenetics","sbslee/fuc","setup.py",".py","836","28","from setuptools import setup, find_packages + +exec(open('fuc/version.py').read()) + +requirements = [ + 'biopython', 'lxml', 'matplotlib', 'matplotlib-venn', 'numpy', 'pandas', + 'pyranges', 'pysam', 'scipy', 'seaborn', 'statsmodels' +] + +setup( + name='fuc', + version=__version__, + author='Seung-been ""Steven"" Lee', + author_email='sbstevenlee@gmail.com', + description='Frequently used commands in bioinformatics', + long_description=open('README.rst').read(), + long_description_content_type='text/x-rst', + url='https://github.com/sbslee/fuc', + packages=find_packages(), + license='MIT', + install_requires=requirements, + classifiers=[ + 'Programming Language :: Python :: 3', + 'License :: OSI Approved :: MIT License' + ], + entry_points={'console_scripts': ['fuc=fuc.__main__:main']} +) +","Python" +"Pharmacogenetics","sbslee/fuc","test.py",".py","4683","123","import os +import unittest +import subprocess + +from fuc.api.common import FUC_PATH +from fuc import pyvcf, pybed, pyfq, pygff + +vcf_file1 = f'{FUC_PATH}/data/vcf/1.vcf' +vcf_file2 = f'{FUC_PATH}/data/vcf/2.vcf' +vcf_file3 = f'{FUC_PATH}/data/vcf/3.vcf' +bed_file1 = f'{FUC_PATH}/data/bed/1.bed' +bed_file2 = f'{FUC_PATH}/data/bed/2.bed' +fq_file1 = f'{FUC_PATH}/data/fq/1.fastq' +text_file1 = f'{FUC_PATH}/data/text/1.txt' +text_file2 = f'{FUC_PATH}/data/text/2.txt' + +class TestPyvcf(unittest.TestCase): + + def test_shape(self): + vf = pyvcf.VcfFrame.from_file(vcf_file1) + self.assertEqual(vf.shape, (5, 4)) + + def test_filter_empty(self): + vf = pyvcf.VcfFrame.from_file(vcf_file2) + vf = vf.filter_empty() + self.assertEqual(vf.df.shape, (4, 11)) + + def test_filter_bed(self): + vf = pyvcf.VcfFrame.from_file(vcf_file1) + bf = pybed.BedFrame.from_file(f'{FUC_PATH}/data/bed/1.bed') + vf = vf.filter_bed(bf) + self.assertEqual(vf.df.shape, (3, 13)) + + def test_merge(self): + vf1 = pyvcf.VcfFrame.from_file(vcf_file1) + vf2 = pyvcf.VcfFrame.from_file(vcf_file2) + vf3 = vf1.merge(vf2, how='outer', format='GT:DP') + self.assertEqual(vf3.df.shape, (9, 15)) + + def test_calculate_concordance(self): + vf = pyvcf.VcfFrame.from_file(vcf_file1) + self.assertEqual(vf.calculate_concordance('Steven', 'Sarah'), (1, 0, 0, 3)) + + def test_filter_multialt(self): + vf = pyvcf.VcfFrame.from_file(vcf_file1) + vf = vf.filter_multialt() + self.assertEqual(vf.shape[0], 4) + + def test_subset(self): + vf = pyvcf.VcfFrame.from_file(vcf_file1) + vf = vf.subset(['Sarah', 'John']) + self.assertEqual(len(vf.samples), 2) + + def test_sites_only(self): + vf = pyvcf.VcfFrame.from_file(vcf_file3) + self.assertEqual(vf.shape, (5, 0)) + +class TestPybed(unittest.TestCase): + + def test_intersect(self): + bf1 = pybed.BedFrame.from_file(f'{FUC_PATH}/data/bed/1.bed') + bf2 = pybed.BedFrame.from_file(f'{FUC_PATH}/data/bed/2.bed') + bf3 = pybed.BedFrame.from_file(f'{FUC_PATH}/data/bed/3.bed') + bf4 = bf1.intersect(bf2) + self.assertEqual(bf3.to_string(), bf4.to_string()) + +class TestPyfq(unittest.TestCase): + + def test_shape(self): + qf = pyfq.FqFrame.from_file(f'{FUC_PATH}/data/fq/1.fastq') + self.assertEqual(qf.shape, (5, 4)) + +class TestPygff(unittest.TestCase): + + def test_from_file(self): + gf = pygff.GffFrame.from_file(f'{FUC_PATH}/data/gff/fasta.gff') + self.assertEqual(gf.df.shape, (12, 9)) + self.assertEqual(len(gf.fasta), 2) + +class TestCli(unittest.TestCase): + def test_bfintxn(self): + result = subprocess.run(['fuc', 'bed-intxn', bed_file1, bed_file2], capture_output=True, text=True, check=True) + self.assertEqual(len(result.stdout.split('\n')), 5) + + def test_bfsum(self): + result = subprocess.run(['fuc', 'bed-sum', bed_file1], capture_output=True, text=True, check=True) + self.assertTrue('Total' in result.stdout) + + def test_dfmerge(self): + result = subprocess.run(['fuc', 'tbl-merge', text_file1, text_file2], capture_output=True, text=True, check=True) + self.assertTrue('Sarah' in result.stdout) + + def test_dfsum(self): + result = subprocess.run(['fuc', 'tbl-sum', text_file1], capture_output=True, text=True, check=True) + self.assertTrue('max' in result.stdout) + + def test_fuccompf(self): + result = subprocess.run(['fuc', 'fuc-compf', vcf_file1, vcf_file1], capture_output=True, text=True, check=True) + self.assertTrue('True' in result.stdout) + + def test_fucexist(self): + result = subprocess.run(['fuc', 'fuc-exist', vcf_file1], capture_output=True, text=True, check=True) + self.assertTrue('True' in result.stdout) + + def test_fucfind(self): + result = subprocess.run('fuc fuc-find ""*.vcf"" -r', shell=True, capture_output=True, text=True, check=True) + self.assertTrue('1.vcf' in result.stdout) + + def test_qfcount(self): + result = subprocess.run(['fuc', 'fq-count', fq_file1], capture_output=True, text=True, check=True) + self.assertEqual(int(result.stdout.strip()), 5) + + def test_qfsum(self): + result = subprocess.run(['fuc', 'fq-sum', fq_file1], capture_output=True, text=True, check=True) + self.assertTrue('# Total: 5' in result.stdout) + + def test_vfmerge(self): + result = subprocess.run(['fuc', 'vcf-merge', vcf_file1, vcf_file2, '--how', 'outer'], capture_output=True, text=True, check=True) + self.assertEqual(len(result.stdout.strip().split('\n')), 10) + +if __name__ == '__main__': + unittest.main() +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/version.py",".py","23","2","__version__ = '0.38.0' +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/__init__.py",".py","19","2","from .api import * +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/__main__.py",".py","879","37","import argparse + +from .version import __version__ +from .cli import commands + +def main(): + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.RawTextHelpFormatter, + ) + parser.add_argument( + '-h', + '--help', + action='help', + default=argparse.SUPPRESS, + help='Show this help message and exit.', + ) + parser.add_argument( + '-v', + '--version', + action='version', + version=f'%(prog)s {__version__}', + help='Show the version number and exit.' + ) + subparsers = parser.add_subparsers( + dest='command', + metavar='COMMAND', + required=True, + ) + for name, command in commands.items(): + command.create_parser(subparsers) + args = parser.parse_args() + commands[args.command].main(args) + +if __name__ == '__main__': + main() +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/ngs_fq2bam.py",".py","8241","306","import os +import sys +import shutil + +from .. import api + +import pandas as pd + +description = """""" +Pipeline for converting FASTQ files to analysis-ready BAM files. + +Here, ""analysis-ready"" means that the final BAM files are: 1) aligned to a +reference genome, 2) sorted by genomic coordinate, 3) marked for duplicate +reads, 4) recalibrated by BQSR model, and 5) ready for downstream analyses +such as variant calling. + +By default, the pipeline will be run in a local environment. Use --qsub to +leverage a parallel environment, in which case SGE is required. + +External dependencies: + - [Required] BWA: Required for read alignment (i.e. BWA-MEM). + - [Required] SAMtools: Required for sorting and indexing BAM files. + - [Required] GATK: Required for marking duplicate reads and recalibrating BAM files. + - [Optional] SGE: Required for job submission (i.e. qsub). + +Manifest columns: + - Name: Sample name. + - Read1: Path to forward FASTA file. + - Read2: Path to reverse FASTA file. +"""""" + +epilog = f"""""" +[Example] Run in local environment: + $ fuc {api.common._script_name()} \\ + manifest.csv \\ + ref.fa \\ + output_dir \\ + ""-Xmx15g -Xms15g"" \\ + 1.vcf 2.vcf 3.vcf \\ + --thread 10 + $ sh output_dir/shell/runme.sh + +[Example] Run in parallel environment with specific queue: + $ fuc {api.common._script_name()} \\ + manifest.csv \\ + ref.fa \\ + output_dir \\ + ""-Xmx15g -Xms15g"" \\ + 1.vcf 2.vcf 3.vcf \\ + --qsub ""-q queue_name -pe pe_name 10"" \\ + --thread 10 + $ sh output_dir/shell/runme.sh + +[Example] Run in parallel environment with specific nodes: + $ fuc {api.common._script_name()} \\ + manifest.csv \\ + ref.fa \\ + output_dir \\ + ""-Xmx15g -Xms15g"" \\ + 1.vcf 2.vcf 3.vcf \\ + --qsub ""-l h='node_A|node_B' -pe pe_name 10"" \\ + --thread 10 + $ sh output_dir/shell/runme.sh +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Pipeline for converting FASTQ files to analysis-ready BAM +files."""""" + ) + parser.add_argument( + 'manifest', + help= +""""""Sample manifest CSV file."""""" + ) + parser.add_argument( + 'fasta', + help= +""""""Reference FASTA file."""""" + ) + parser.add_argument( + 'output', + type=os.path.abspath, + help= +""""""Output directory."""""" + ) + parser.add_argument( + 'java', + help= +""""""Java resoruce to request for GATK."""""" + ) + parser.add_argument( + 'vcf', + type=str, + nargs='+', + help= +""""""One or more reference VCF files containing known variant +sites (e.g. 1000 Genomes Project)."""""" + ) + parser.add_argument( + '--qsub', + metavar='TEXT', + type=str, + help= +""""""SGE resoruce to request for qsub."""""" + ) + parser.add_argument( + '--bed', + metavar='PATH', + type=str, + help= +""""""BED file."""""" + ) + parser.add_argument( + '--thread', + metavar='INT', + type=int, + default=1, + help= +""""""Number of threads to use (default: 1)."""""" + ) + parser.add_argument( + '--platform', + metavar='TEXT', + type=str, + default='Illumina', + help= +""""""Sequencing platform (default: 'Illumina')."""""" + ) + parser.add_argument( + '--job', + metavar='TEXT', + type=str, + help= +""""""Job submission ID for SGE."""""" + ) + parser.add_argument( + '--force', + action='store_true', + help= +""""""Overwrite the output directory if it already exists."""""" + ) + parser.add_argument( + '--keep', + action='store_true', + help= +""""""Keep temporary files."""""" + ) + +def main(args): + if os.path.exists(args.output) and args.force: + shutil.rmtree(args.output) + + os.mkdir(args.output) + os.mkdir(f'{args.output}/shell') + os.mkdir(f'{args.output}/log') + os.mkdir(f'{args.output}/temp') + + with open(f'{args.output}/command.txt', 'w') as f: + f.write(' '.join(sys.argv) + '\n') + + df = pd.read_csv(args.manifest) + + if args.keep: + remove = '# rm' + else: + remove = 'rm' + + java_shared = f'-XX:ParallelGCThreads={args.thread} -XX:ConcGCThreads={args.thread}' + + is_local = args.qsub is None + + if is_local: + conda_env = f'# source activate {api.common.conda_env()}' + else: + conda_env = f'source activate {api.common.conda_env()}' + + for i, r in df.iterrows(): + with open(f'{args.output}/shell/S1-{r.Name}.sh', 'w') as f: + + ########### + # BWA-MEM # + ########### + + command1 = 'bwa mem' + command1 += f' -M -R $group -t {args.thread}' + command1 += f' {args.fasta} {r.Read1} {r.Read2} |' + command1 += f' samtools sort -@ {args.thread}' + command1 += f' -o {args.output}/temp/{r.Name}.sorted.bam -' + + ################## + # MarkDuplicates # + ################## + + command2 = 'gatk MarkDuplicates' + command2 += f' --QUIET' + command2 += f' --java-options ""{java_shared} {args.java}""' + command2 += f' -I {args.output}/temp/{r.Name}.sorted.bam' + command2 += f' -O {args.output}/temp/{r.Name}.sorted.markdup.bam' + command2 += f' -M {args.output}/temp/{r.Name}.metrics' + + #################### + # BaseRecalibrator # + #################### + + command3 = 'gatk BaseRecalibrator' + command3 += f' --QUIET' + command3 += f' --java-options ""{java_shared} {args.java}""' + command3 += f' -R {args.fasta}' + command3 += f' -I {args.output}/temp/{r.Name}.sorted.markdup.bam' + command3 += f' -O {args.output}/temp/{r.Name}.table' + command3 += ' ' + ' '.join([f'--known-sites {x}' for x in args.vcf]) + if args.bed is not None: + command3 += f' -L {args.bed}' + + ############# + # ApplyBQSR # + ############# + + command4 = 'gatk ApplyBQSR' + command4 += f' --QUIET' + command4 += f' --java-options ""{java_shared} {args.java}""' + command4 += f' -bqsr {args.output}/temp/{r.Name}.table' + command4 += f' -I {args.output}/temp/{r.Name}.sorted.markdup.bam' + command4 += f' -O {args.output}/{r.Name}.sorted.markdup.recal.bam' + if args.bed is not None: + command4 += f' -L {args.bed}' + + f.write( +f""""""#!/bin/bash + +# Activate conda environment. +{conda_env} + +# Get read group information. +first=`zcat {r.Read1} | head -1` +flowcell=`echo ""$first"" | awk -F "" "" '{{print $1}}' | awk -F "":"" '{{print $3}}'` +if [ -z ""${{flowcell}}"" ]; then + flowcell=no_flowcell +fi +barcode=`echo ""$first"" | awk -F "" "" '{{print $2}}' | awk -F "":"" '{{print $4}}'` +if [ -z ""${{barcode}}"" ]; then + barcode=no_barcode +fi +group=""@RG\\tID:$flowcell\\tPU:$flowcell.$barcode\\tSM:{r.Name}\\tPL:{args.platform}\\tLB:{r.Name}"" + +# Align and sort seuqnece reads. Assign read group as well. +{command1} + +if [ $? -eq 0 ]; then + echo ""Successfully finished aligning and sorting seuqnece reads"" +else + echo ""Failed to align and sort seuqnece reads, aborting"" + exit 1 +fi + +# Mark duplicate reads. +{command2} + +# Index BAM file. +samtools index {args.output}/temp/{r.Name}.sorted.markdup.bam + +# Build BQSR model. +{command3} + +# Apply BQSR model. +{command4} + +# Remove temporary files. +{remove} {args.output}/temp/{r.Name}.metrics +{remove} {args.output}/temp/{r.Name}.table +{remove} {args.output}/temp/{r.Name}.sorted.bam +{remove} {args.output}/temp/{r.Name}.sorted.markdup.bam +{remove} {args.output}/temp/{r.Name}.sorted.markdup.bam.bai +"""""") + + if args.job is None: + jid = '' + else: + jid = args.job + '-' + + with open(f'{args.output}/shell/runme.sh', 'w') as f: + + if is_local: + command5 = f'sh $p/shell/S1-$sample.sh > $p/log/S1-$sample.o 2> $p/log/S1-$sample.e' + else: + command5 = f'qsub {args.qsub} -S /bin/bash -e $p/log -o $p/log -N {jid}S1-$sample $p/shell/S1-$sample.sh' + + f.write( +f""""""#!/bin/bash + +p={args.output} + +samples=({"" "".join(df.Name)}) + +for sample in ${{samples[@]}} +do + {command5} +done +"""""") +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/bam_slice.py",".py","1869","67","import sys + +from .. import api + +description = """""" +Slice a BAM file. +"""""" + +epilog = f"""""" +[Example] Specify regions manually: + $ fuc {api.common._script_name()} in.bam 1:100-300 2:400-700 > out.bam + +[Example] Speicfy regions with a BED file: + $ fuc {api.common._script_name()} in.bam regions.bed > out.bam + +[Example] Slice a CRAM file: + $ fuc {api.common._script_name()} in.bam regions.bed --format CRAM --fasta ref.fa > out.cram +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Slice a BAM file."""""" + ) + parser.add_argument( + 'bam', + help= +""""""Input BAM file. It must be already indexed to allow random +access. You can index a BAM file with the bam-index command."""""" + ) + parser.add_argument( + 'regions', + nargs='+', + help= +""""""One or more regions to be sliced. Each region must have the +format chrom:start-end and be a half-open interval with +(start, end]. This means, for example, chr1:100-103 will +extract positions 101, 102, and 103. Alternatively, you can +provide a BED file (compressed or uncompressed) to specify +regions. Note that the 'chr' prefix in contig names (e.g. +'chr1' vs. '1') will be automatically added or removed as +necessary to match the input BED's contig names."""""" + ) + parser.add_argument( + '--format', + metavar='TEXT', + default='BAM', + choices=['SAM', 'BAM', 'CRAM'], + help= +""""""Output format (default: 'BAM') (choices: 'SAM', 'BAM', +'CRAM')."""""" + ) + parser.add_argument( + '--fasta', + metavar='PATH', + help= +""""""FASTA file. Required when --format is 'CRAM'."""""" + ) + +def main(args): + api.pybam.slice(args.bam, args.regions, format=args.format, + path='-', fasta=args.fasta) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/bed_intxn.py",".py","784","36","import sys + +from .. import api + +description = """""" +Find the intersection of BED files. +"""""" + +epilog = f"""""" +[Example] Find the intersection of three BED files: + $ fuc {api.common._script_name()} in1.bed in2.bed in3.bed > out.bed +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Find the intersection of BED files."""""" + ) + parser.add_argument( + 'bed', + nargs='+', + help= +""""""Input BED files."""""" + ) + +def main(args): + bfs = [api.pybed.BedFrame.from_file(x) for x in args.bed] + final_bf = bfs[0] + for bf in bfs[1:]: + final_bf = final_bf.intersect(bf) + sys.stdout.write(final_bf.to_string()) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/fuc_find.py",".py","1478","60","import os +from pathlib import Path + +from .. import api + +description = """""" +Retrieve absolute paths of files whose name matches a specified pattern, +optionally recursively. +"""""" + +epilog = f"""""" +[Example] Retrieve VCF files in the current directory only: + $ fuc {api.common._script_name()} ""*.vcf"" + +[Example] Retrieve VCF files recursively: + $ fuc {api.common._script_name()} ""*.vcf"" -r + +[Example] Retrieve VCF files in a specific directory: + $ fuc {api.common._script_name()} ""*.vcf"" -d /path/to/dir +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Retrieve absolute paths of files whose name matches a +specified pattern, optionally recursively."""""" + ) + parser.add_argument( + 'pattern', + help= +""""""Filename pattern."""""" + ) + parser.add_argument( + '-r', + '--recursive', + action='store_true', + help= +""""""Turn on recursive retrieving."""""" + ) + parser.add_argument( + '-d', + '--directory', + metavar='PATH', + default=os.getcwd(), + help= +""""""Directory to search in (default: current directory)."""""" + ) + +def main(args): + if args.recursive: + for path in Path(args.directory).rglob(args.pattern): + print(path.absolute()) + else: + for path in Path(args.directory).glob(args.pattern): + print(path.absolute()) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/bam_rename.py",".py","2022","77","import sys +import tempfile + +from .. import api + +import pysam + +description = """""" +Rename the sample in a BAM file. +"""""" + +epilog = f"""""" +[Example] Write a new BAM file after renaming: + $ fuc {api.common._script_name()} in.bam NA12878 > out.bam +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Rename the sample in a BAM file."""""" + ) + parser.add_argument( + 'bam', + help= +""""""Input alignment file."""""" + ) + parser.add_argument( + 'name', + help= +""""""New sample name."""""" + ) + +def main(args): + # Detect the input format. + try: + with open(args.bam, 'r') as f: + for line in f: + is_sam = True + break + except UnicodeDecodeError: + is_sam = False + + # Rename the sample(s). + old_lines = pysam.view('-H', args.bam, '--no-PG').strip().split('\n') + new_lines = [] + for old_line in old_lines: + old_fields = old_line.split('\t') + if old_fields[0] != '@RG': + new_lines.append(old_line) + continue + new_fields = [] + for old_field in old_fields: + if 'SM:' not in old_field: + new_fields.append(old_field) + continue + new_fields.append(f'SM:{args.name}') + new_lines.append('\t'.join(new_fields)) + + # Write the output file. + if is_sam: + for new_line in new_lines: + sys.stdout.write(new_line + '\n') + alignments = pysam.view(args.bam, '--no-PG') + sys.stdout.write(alignments) + else: + with tempfile.TemporaryDirectory() as t: + with open(f'{t}/header.sam', 'w') as f: + f.write('\n'.join(new_lines)) + alignments = pysam.reheader(f'{t}/header.sam', + args.bam, + '--no-PG') + sys.stdout.buffer.write(alignments) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/tbl_merge.py",".py","2296","92","import sys + +from .. import api + +import pandas as pd + +description = """""" +Merge two table files. + +This command will merge two table files using one or more shared columns. +The command essentially wraps the 'pandas.DataFrame.merge' method from the +pandas package. For details on the merging algorithms, please visit the +method's documentation page. +"""""" + +epilog = f"""""" +[Example] Merge two tables: + $ fuc {api.common._script_name()} left.tsv right.tsv > merged.tsv + +[Example] When the left table is a CSV: + $ fuc {api.common._script_name()} left.csv right.tsv --lsep , > merged.tsv + +[Example] Merge with the outer algorithm: + $ fuc {api.common._script_name()} left.tsv right.tsv --how outer > merged.tsv +"""""" + +CHOICES = ['left', 'right', 'outer', 'inner', 'cross'] + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Merge two table files."""""" + ) + parser.add_argument( + 'left', + help= +""""""Input left file."""""" + ) + parser.add_argument( + 'right', + help= +""""""Input right file."""""" + ) + parser.add_argument( + '--how', + metavar='TEXT', + choices=CHOICES, + default='inner', + help= +""""""Type of merge to be performed (default: 'inner') +(choices: 'left', 'right', 'outer', 'inner', 'cross')."""""" + ) + parser.add_argument( + '--on', + metavar='TEXT', + nargs='+', + help= +""""""Column names to join on."""""" + ) + parser.add_argument( + '--lsep', + metavar='TEXT', + default='\t', + help= +""""""Delimiter to use for the left file (default: '\\t')."""""" + ) + parser.add_argument( + '--rsep', + metavar='TEXT', + default='\t', + help= +""""""Delimiter to use for the right file (default: '\\t')."""""" + ) + parser.add_argument( + '--osep', + metavar='TEXT', + default='\t', + help= +""""""Delimiter to use for the output file (default: '\\t')."""""" + ) + return parser + +def main(args): + df1 = pd.read_table(args.left, sep=args.lsep) + df2 = pd.read_table(args.right, sep=args.rsep) + df3 = df1.merge(df2, on=args.on, how=args.how) + sys.stdout.write(df3.to_csv(sep=args.osep, index=False)) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/vcf_rename.py",".py","2394","90","import sys + +from .. import api + +import pandas as pd + +description = """""" +Rename the samples in a VCF file. + +There are three different renaming modes using the 'names' file: + - 'MAP': Default mode. Requires two columns, old names in the first + and new names in the second. + - 'INDEX': Requires two columns, new names in the first and 0-based + indicies in the second. + - 'RANGE': Requires only one column of new names but '--range' must + be specified. +"""""" + +epilog = f"""""" +[Example] Using the default 'MAP' mode: + $ fuc {api.common._script_name()} in.vcf old_new.tsv > out.vcf + +[Example] Using the 'INDEX' mode: + $ fuc {api.common._script_name()} in.vcf new_idx.tsv --mode INDEX > out.vcf + +[Example] Using the 'RANGE' mode: + $ fuc {api.common._script_name()} in.vcf new_only.tsv --mode RANGE --range 2 5 > out.vcf +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Rename the samples in a VCF file."""""" + ) + parser.add_argument( + 'vcf', + help= +""""""VCF file (compressed or uncompressed)."""""" + ) + parser.add_argument( + 'names', + help= +""""""Text file containing information for renaming the samples."""""" + ) + parser.add_argument( + '--mode', + metavar='TEXT', + default='MAP', + choices=['MAP', 'INDEX', 'RANGE'], + help= +""""""Renaming mode (default: 'MAP') (choices: 'MAP', +'INDEX', 'RANGE')."""""" + ) + parser.add_argument( + '--range', + metavar='INT', + type=int, + nargs=2, + help= +""""""Index range to use when renaming the samples. +Applicable only with the 'RANGE' mode."""""" + ) + parser.add_argument( + '--sep', + metavar='TEXT', + default='\t', + help= +""""""Delimiter to use for reading the 'names' file +(default: '\\t')."""""" + ) + +def main(args): + vf = api.pyvcf.VcfFrame.from_file(args.vcf) + df = pd.read_table(args.names, sep=args.sep, header=None) + if args.mode == 'MAP': + names = dict(zip(df[0], df[1])) + indicies = None + elif args.mode == 'INDEX': + names = df[0].to_list() + indicies = df[1].to_list() + else: + names = df[0].to_list() + indicies = tuple(args.range) + vf = vf.rename(names, indicies=indicies) + sys.stdout.write(vf.to_string()) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/fq_sum.py",".py","1118","42","from .. import api + +description = """""" +Summarize a FASTQ file. + +This command will output a summary of the input FASTQ file. The summary +includes the total number of sequence reads, the distribution of read +lengths, and the numbers of unique and duplicate sequences. +"""""" + +epilog = f"""""" +[Example] Summarize a FASTQ file: + $ fuc {api.common._script_name()} in.fastq +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Summarize a FASTQ file."""""" + ) + parser.add_argument( + 'fastq', + help= +""""""Input FASTQ file (compressed or uncompressed)."""""" + ) + +def main(args): + qf = api.pyfq.FqFrame.from_file(args.fastq) + print(f'# Total: {qf.shape[0]:,}') + unique = qf.df.SEQ.nunique() + duplicate = qf.shape[0] - unique + print(f'# Unique: {unique:,}') + print(f'# Duplicate: {duplicate:,}') + lengths = qf.readlen() + print('# Read length and count:') + for length in sorted(lengths): + print(length, f'{lengths[length]:,}', sep='\t') +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/fuc_exist.py",".py","1156","49","import sys +from pathlib import Path + +from .. import api + +description = """""" +Check whether certain files exist. + +This command will check whether or not specified files including directories +exist, returning 'True' if they exist and 'False' otherwise. +"""""" + +epilog = f"""""" +[Example] Test a file: + $ fuc {api.common._script_name()} in.txt + +[Example] Test a directory: + $ fuc {api.common._script_name()} dir + +[Example] When the input is stdin: + $ cat test.list | fuc {api.common._script_name()} +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Check whether certain files exist."""""" + ) + parser.add_argument( + 'files', + nargs='*', + help= +""""""Files and directories to be tested (default: stdin)."""""" + ) + +def main(args): + if args.files: + paths = args.files + elif not sys.stdin.isatty(): + paths = sys.stdin.read().rstrip('\n').split('\n') + else: + raise ValueError('no input files detected') + for path in paths: + print(Path(path).exists(), path) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/maf_oncoplt.py",".py","2074","91","from .. import api + +import matplotlib.pyplot as plt + +description = """""" +Create an oncoplot with a MAF file. + +The format of output image (PDF/PNG/JPEG/SVG) will be automatically +determined by the output file's extension. +"""""" + +epilog = f"""""" +[Example] Output a PNG file: + $ fuc {api.common._script_name()} in.maf out.png + +[Example] Output a PDF file: + $ fuc {api.common._script_name()} in.maf out.pdf +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Create an oncoplot with a MAF file."""""" + ) + parser.add_argument( + 'maf', + help= +""""""Input MAF file."""""" + ) + parser.add_argument( + 'out', + help= +""""""Output image file."""""" + ) + parser.add_argument( + '--count', + metavar='INT', + type=int, + default=10, + help= +""""""Number of top mutated genes to display (default: 10)."""""" + ) + parser.add_argument( + '--figsize', + metavar='FLOAT', + type=float, + default=[15, 10], + nargs=2, + help= +""""""Width, height in inches (default: [15, 10])."""""" + ) + parser.add_argument( + '--label_fontsize', + metavar='FLOAT', + type=float, + default=15, + help= +""""""Font size of labels (default: 15)."""""" + ) + parser.add_argument( + '--ticklabels_fontsize', + metavar='FLOAT', + type=float, + default=15, + help= +""""""Font size of tick labels (default: 15)."""""" + ) + parser.add_argument( + '--legend_fontsize', + metavar='FLOAT', + type=float, + default=15, + help= +""""""Font size of legend texts (default: 15)."""""" + ) + +def main(args): + mf = api.pymaf.MafFrame.from_file(args.maf) + mf.plot_oncoplot( + count=args.count, + figsize=args.figsize, + label_fontsize=args.label_fontsize, + ticklabels_fontsize=args.ticklabels_fontsize, + legend_fontsize=args.legend_fontsize + ) + plt.savefig(args.out) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/tbl_sum.py",".py","3726","138","from .. import api + +import pandas as pd +from pandas.api.types import is_numeric_dtype + +description = """""" +Summarize a table file. +"""""" + +epilog = f"""""" +[Example] Summarize a table: + $ fuc {api.common._script_name()} table.tsv +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Summarize a table file."""""" + ) + parser.add_argument( + 'table_file', + help= +""""""Table file."""""" + ) + parser.add_argument( + '--sep', + metavar='TEXT', + default='\t', + help= +""""""Delimiter to use (default: '\\t')."""""" + ) + parser.add_argument( + '--skiprows', + metavar='TEXT', + help= +""""""Comma-separated line numbers to skip (0-indexed) or +number of lines to skip at the start of the file +(e.g. `--skiprows 1,` will skip the second line, +`--skiprows 2,4` will skip the third and fifth lines, +and `--skiprows 10` will skip the first 10 lines)."""""" + ) + parser.add_argument( + '--na_values', + metavar='TEXT', + nargs='+', + help= +""""""Additional strings to recognize as NA/NaN (by +default, the following values are interpreted +as NaN: '', '#N/A', '#N/A N/A', '#NA', '-1.#IND', +'-1.#QNAN', '-NaN', '-nan', '1.#IND', '1.#QNAN', +'', 'N/A', 'NA', 'NULL', 'NaN', 'n/a', 'nan', +'null')."""""" + ) + parser.add_argument( + '--keep_default_na', + action='store_false', + help= +""""""Whether or not to include the default NaN values when +parsing the data (see 'pandas.read_table' for details)."""""" + ) + parser.add_argument( + '--expr', + metavar='TEXT', + help= +""""""Query the columns of a pandas.DataFrame with a +boolean expression (e.g. `--query ""A == 'yes'""`)."""""" + ) + parser.add_argument( + '--columns', + metavar='TEXT', + nargs='+', + help= +""""""Columns to be summarized (by default, all columns +will be included)."""""" + ) + parser.add_argument( + '--dtypes', + metavar='PATH', + help= +""""""File of column names and their data types (either +'categorical' or 'numeric'); one tab-delimited pair of +column name and data type per line."""""" + ) + +def main(args): + if args.skiprows is None: + skiprows = None + elif ',' in args.skiprows: + skiprows = [int(x) for x in args.skiprows.split(',') if x] + else: + skiprows = int(args.skiprows) + + df = pd.read_table(args.table_file, + sep=args.sep, + skiprows=skiprows, + na_values=args.na_values, + keep_default_na=args.keep_default_na) + + if args.dtypes is not None: + with open(args.dtypes) as f: + for line in f: + fields = line.strip().split('\t') + col = fields[0] + dtype = fields[1] + if dtype == 'numeric': + dtype = float + elif dtype == 'categorical': + dtype = 'category' + else: + raise TypeError(""Data type must be either 'numeric' or "" + ""'categorical'."") + df[col] = df[col].astype(dtype) + + if args.expr: + df = df.query(args.expr) + + if args.columns: + headers = args.columns + else: + headers = df.columns + + print('='*70) + + for header in headers: + s = df[header] + print(f'Name: {header}') + print(f'Count: {len(s)}') + print('Summary:') + if is_numeric_dtype(s): + print(s.describe().to_string()) + else: + print(s.value_counts().sort_index().to_string()) + print('='*70) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/fa_filter.py",".py","1587","67","import sys +import subprocess +import os + +from .. import api + +from Bio import SeqIO + +description = """""" +Filter sequence records in a FASTA file. +"""""" + +epilog = f"""""" +[Example] Select certain contigs: + $ fuc {api.common._script_name()} in.fasta --contigs chr1 chr2 > out.fasta + +[Example] Select certain contigs: + $ fuc {api.common._script_name()} in.fasta --contigs contigs.list --exclude > out.fasta +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Filter sequence records in a FASTA file."""""" + ) + parser.add_argument( + 'fasta', + help= +""""""Input FASTA file (compressed or uncompressed)."""""" + ) + parser.add_argument( + '--contigs', + metavar='TEXT', + nargs='+', + help= +""""""One or more contigs to be selected. Alternatively, you can +provide a file containing one contig per line."""""" + ) + parser.add_argument( + '--exclude', + action='store_true', + help= +""""""Exclude specified contigs."""""" + ) + +def main(args): + if os.path.exists(args.contigs[0]): + contigs = api.common.convert_file2list(args.contigs[0]) + else: + contigs = args.contigs + + records = [] + + for record in SeqIO.parse(args.fasta, 'fasta'): + if args.exclude: + if record.id not in contigs: + records.append(record) + else: + if record.id in contigs: + records.append(record) + + SeqIO.write(records, sys.stdout, 'fasta') +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/cov_rename.py",".py","2429","89","import sys + +from .. import api + +import pandas as pd + +description = """""" +Rename the samples in a depth of coverage file. + +There are three different renaming modes using the names file: + - 'MAP': Default mode. Requires two columns, old names in the first + and new names in the second. + - 'INDEX': Requires two columns, new names in the first and 0-based + indicies in the second. + - 'RANGE': Requires only one column of new names but --range must + be specified. +"""""" + +epilog = f"""""" +[Example] Using the default 'MAP' mode: + $ fuc {api.common._script_name()} in.tsv old_new.tsv > out.tsv + +[Example] Using the 'INDEX' mode: + $ fuc {api.common._script_name()} in.tsv new_idx.tsv --mode INDEX > out.tsv + +[Example] Using the 'RANGE' mode: + $ fuc {api.common._script_name()} in.tsv new_only.tsv --mode RANGE --range 2 5 > out.tsv +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Rename the samples in a depth of coverage file."""""" + ) + parser.add_argument( + 'tsv', + help= +""""""TSV file (compressed or uncompressed)."""""" + ) + parser.add_argument( + 'names', + help= +""""""Text file containing information for renaming the samples."""""" + ) + parser.add_argument( + '--mode', + metavar='TEXT', + default='MAP', + choices=['MAP', 'INDEX', 'RANGE'], + help=""Renaming mode (default: 'MAP') (choices: 'MAP', \n"" + ""'INDEX', 'RANGE')."" + ) + parser.add_argument( + '--range', + metavar='INT', + type=int, + nargs=2, + help= +""""""Index range to use when renaming the samples. +Applicable only with the 'RANGE' mode."""""" + ) + parser.add_argument( + '--sep', + metavar='TEXT', + default='\t', + help= +""""""Delimiter to use when reading the names file +(default: '\\t')."""""" + ) + +def main(args): + cf = api.pycov.CovFrame.from_file(args.tsv) + df = pd.read_table(args.names, sep=args.sep, header=None) + if args.mode == 'MAP': + names = dict(zip(df[0], df[1])) + indicies = None + elif args.mode == 'INDEX': + names = df[0].to_list() + indicies = df[1].to_list() + else: + names = df[0].to_list() + indicies = tuple(args.range) + cf = cf.rename(names, indicies=indicies) + sys.stdout.write(cf.to_string()) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/__init__.py",".py","252","10","from importlib import import_module +from pathlib import Path + +commands = {} + +for f in sorted(Path(__file__).parent.glob('*.py')): + if '__' in f.stem: + continue + commands[f.stem.replace('_', '-')] = import_module(f'.{f.stem}', __package__) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/vcf_vcf2bed.py",".py","658","33","import sys + +from .. import api + +description = """""" +Convert a VCF file to a BED file. +"""""" + +epilog = f"""""" +[Example] Convert VCF to BED: + $ fuc {api.common._script_name()} in.vcf > out.bed +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Convert a VCF file to a BED file."""""" + ) + parser.add_argument( + 'vcf', + help= +""""""VCF file (compressed or uncompressed)."""""" + ) + +def main(args): + vf = api.pyvcf.VcfFrame.from_file(args.vcf) + bf = vf.to_bed() + sys.stdout.write(bf.to_string()) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/vcf_merge.py",".py","1791","70","import sys + +from .. import api + +description = """""" +Merge two or more VCF files. +"""""" + +epilog = f"""""" +[Example] Merge multiple VCF files: + $ fuc {api.common._script_name()} 1.vcf 2.vcf 3.vcf > merged.vcf + +[Example] Keep the GT, AD, DP fields: + $ fuc {api.common._script_name()} 1.vcf 2.vcf --format GT:AD:DP > merged.vcf +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help='Merge two or more VCF files.', + ) + parser.add_argument( + 'vcf_files', + nargs='+', + help= +""""""VCF files (compressed or uncompressed). Note that the 'chr' +prefix in contig names (e.g. 'chr1' vs. '1') will be +automatically added or removed as necessary to match the +contig names of the first VCF."""""" + ) + parser.add_argument( + '--how', + metavar='TEXT', + default='inner', + help= +""""""Type of merge as defined in pandas.DataFrame.merge +(default: 'inner')."""""" + ) + parser.add_argument( + '--format', + metavar='TEXT', + default='GT', + help= +""""""FORMAT subfields to be retained (e.g. 'GT:AD:DP') +(default: 'GT')."""""" + ) + parser.add_argument( + '--sort', + action='store_false', + help= +""""""Use this flag to turn off sorting of records +(default: True)."""""" + ) + parser.add_argument( + '--collapse', + action='store_true', + help= +""""""Use this flag to collapse duplicate records +(default: False)."""""" + ) + +def main(args): + vfs = [api.pyvcf.VcfFrame.from_file(x) for x in args.vcf_files] + merged_vf = api.pyvcf.merge(vfs, format=args.format, how=args.how, + sort=args.sort, collapse=args.collapse) + sys.stdout.write(merged_vf.to_string()) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/ngs_trim.py",".py","2971","132","import os +import sys +import shutil + +from .. import api + +import pandas as pd + +description = """""" +Pipeline for trimming adapters from FASTQ files. + +External dependencies: + - SGE: Required for job submission (i.e. qsub). + - cutadapt: Required for trimming adapters. + +Manifest columns: + - Name: Sample name. + - Read1: Path to forward FASTA file. + - Read2: Path to reverse FASTA file. +"""""" + +epilog = f"""""" +[Example] Specify queue: + $ fuc {api.common._script_name()} \\ + manifest.csv \\ + output_dir \\ + ""-q queue_name -pe pe_name 10"" \\ + --thread 10 +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Pipeline for trimming adapters from FASTQ files."""""" + ) + parser.add_argument( + 'manifest', + help= +""""""Sample manifest CSV file."""""" + ) + parser.add_argument( + 'output', + type=os.path.abspath, + help= +""""""Output directory."""""" + ) + parser.add_argument( + 'qsub', + type=str, + help= +""""""SGE resoruce to request for qsub."""""" + ) + parser.add_argument( + '--thread', + metavar='INT', + type=int, + default=1, + help= +""""""Number of threads to use (default: 1)."""""" + ) + parser.add_argument( + '--job', + metavar='TEXT', + type=str, + help= +""""""Job submission ID for SGE."""""" + ) + parser.add_argument( + '--force', + action='store_true', + help= +""""""Overwrite the output directory if it already exists."""""" + ) + +def main(args): + if os.path.exists(args.output) and args.force: + shutil.rmtree(args.output) + + os.mkdir(args.output) + os.mkdir(f'{args.output}/shell') + os.mkdir(f'{args.output}/log') + + with open(f'{args.output}/command.txt', 'w') as f: + f.write(' '.join(sys.argv) + '\n') + + df = pd.read_csv(args.manifest) + + for i, r in df.iterrows(): + with open(f'{args.output}/shell/S1-{r.Name}.sh', 'w') as f: + + command = 'cutadapt' + command += f' -a AGATCGGAAGAGCACACGTCTGAACTCCAGTCA' + command += f' -A AGATCGGAAGAGCGTCGTGTAGGGAAAGAGTGT' + command += f' -j {args.thread}' + command += f' -o {args.output}/{r.Name}_R1.fastq.gz' + command += f' -p {args.output}/{r.Name}_R2.fastq.gz' + command += f' {r.Read1}' + command += f' {r.Read2}' + + f.write( +f""""""#!/bin/bash + +# Activate conda environment. +source activate {api.common.conda_env()} + +# Trim adapters from FASTQ files. +{command} +"""""") + + if args.job is None: + jid = '' + else: + jid = args.job + '-' + + with open(f'{args.output}/shell/qsubme.sh', 'w') as f: + f.write( +f""""""#!/bin/bash + +p={args.output} + +samples=({"" "".join(df.Name)}) + +for sample in ${{samples[@]}} +do + qsub {args.qsub} -S /bin/bash -e $p/log -o $p/log -N {jid}S1-$sample $p/shell/S1-$sample.sh +done +"""""") +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/maf_maf2vcf.py",".py","2498","89","import sys + +from .. import api + +description = """""" +Convert a MAF file to a VCF file. + +In order to handle INDELs the command makes use of a reference assembly (i.e. +FASTA file). If SNVs are your only concern, then you do not need a FASTA file +and can just use --ignore_indels. + +If you are going to provide a FASTA file, please make sure to select the +appropriate one (e.g. one that matches the genome assembly). + +In addition to basic genotype calls (e.g. '0/1'), you can extract more +information from the MAF file by specifying the column(s) that contain +additional genotype data of interest with the '--cols' argument. If provided, +this argument will append the requested data to individual sample genotypes +(e.g. '0/1:0.23'). + +You can also control how these additional genotype information appear in the +FORMAT field (e.g. AF) with the '--names' argument. If this argument is not +provided, the original column name(s) will be displayed. +"""""" + +epilog = f"""""" +[Example] Convert both SNVs and indels: + $ fuc {api.common._script_name()} in.maf --fasta hs37d5.fa > out.vcf + +[Example] Convert SNVs only: + $ fuc {api.common._script_name()} in.maf --ignore_indels > out.vcf + +[Example] Extract AF field: + $ fuc {api.common._script_name()} \\ + in.maf \\ + --fasta hs37d5.fa \\ + --cols i_TumorVAF_WU \\ + --names AF > out.vcf +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Convert a MAF file to a VCF file."""""" + ) + parser.add_argument( + 'maf', + help= +""""""MAF file (compressed or uncompressed)."""""" + ) + parser.add_argument( + '--fasta', + metavar='PATH', + help= +""""""FASTA file (required to include INDELs in the output)."""""" + ) + parser.add_argument( + '--ignore_indels', + action='store_true', + help= +""""""Use this flag to exclude INDELs from the output."""""" + ) + parser.add_argument( + '--cols', + metavar='TEXT', + nargs='+', + help= +""""""Column(s) in the MAF file."""""" + ) + parser.add_argument( + '--names', + metavar='TEXT', + nargs='+', + help= +""""""Name(s) to be displayed in the FORMAT field."""""" + ) + +def main(args): + mf = api.pymaf.MafFrame.from_file(args.maf) + vf = mf.to_vcf( + fasta=args.fasta, ignore_indels=args.ignore_indels, + cols=args.cols, names=args.names + ) + sys.stdout.write(vf.to_string()) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/vcf_filter.py",".py","3206","117","import sys + +from .. import api + +import pandas as pd + +description = """""" +Filter a VCF file. +"""""" + +epilog = f"""""" +[Example] Mark genotypes with 0/0 as missing: + $ fuc {api.common._script_name()} in.vcf --expr 'GT == ""0/0""' > out.vcf + +[Example] Mark genotypes that are not 0/0 as missing: + $ fuc {api.common._script_name()} in.vcf --expr 'GT != ""0/0""' > out.vcf + +[Example] Mark genotypes whose DP is less than 30 as missing: + $ fuc {api.common._script_name()} in.vcf --expr 'DP < 30' > out.vcf + +[Example] Same as above, but also mark ambiguous genotypes as missing: + $ fuc {api.common._script_name()} in.vcf --expr 'DP < 30' --greedy > out.vcf + +[Example] Build a complex query to select genotypes to be marked missing: + $ fuc {api.common._script_name()} in.vcf --expr 'AD[1] < 10 or DP < 30' --opposite > out.vcf + +[Example] Compute summary statistics and subset samples: + $ fuc {api.common._script_name()} in.vcf \\ + --expr 'np.mean(AD) < 10' --greedy --samples sample.list > out.vcf + +[Example] Drop duplicate rows: + $ fuc {api.common._script_name()} in.vcf --drop_duplicates CHROM POS REF ALT > out.vcf + +[Example] Filter out rows without genotypes: + $ fuc {api.common._script_name()} in.vcf --filter_empty > out.vcf +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Filter a VCF file."""""" + ) + parser.add_argument( + 'vcf', + help= +""""""VCF file (compressed or uncompressed)."""""" + ) + parser.add_argument( + '--expr', + metavar='TEXT', + help= +""""""Expression to evaluate."""""" + ) + parser.add_argument( + '--samples', + metavar='PATH', + help= +""""""File of sample names to apply the marking (one +sample per line)."""""" + ) + parser.add_argument( + '--drop_duplicates', + metavar='TEXT', + nargs='*', + help= +""""""Only consider certain columns for identifying +duplicates, by default use all of the columns."""""" + ) + parser.add_argument( + '--greedy', + action='store_true', + help= +""""""Use this flag to mark even ambiguous genotypes +as missing."""""" + ) + parser.add_argument( + '--opposite', + action='store_true', + help= +""""""Use this flag to mark all genotypes that do not +satisfy the query expression as missing and leave +those that do intact."""""" + ) + parser.add_argument( + '--filter_empty', + action='store_true', + help= +""""""Use this flag to remove rows with no genotype +calls at all."""""" + ) + +def main(args): + vf = api.pyvcf.VcfFrame.from_file(args.vcf) + + if args.expr is not None: + if args.samples is None: + samples = None + else: + samples = pd.read_table(args.samples, header=None)[0].to_list() + + vf = vf.markmiss(args.expr, + greedy=args.greedy, + opposite=args.opposite, + samples=samples) + + if args.drop_duplicates is not None: + vf = vf.drop_duplicates(args.drop_duplicates) + + if args.filter_empty: + vf = vf.filter_empty() + + sys.stdout.write(vf.to_string()) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/tabix_index.py",".py","1461","63","import sys + +from .. import api + +import pysam + +description = """""" +Index a GFF/BED/SAM/VCF file with Tabix. + +The Tabix program is used to index a TAB-delimited genome position file +(GFF/BED/SAM/VCF) and create an index file (.tbi). The input data file must +be position sorted and compressed by bgzip. +"""""" + +epilog = f"""""" +[Example] Index a GFF file: + $ fuc {api.common._script_name()} in.gff.gz + +[Example] Index a BED file: + $ fuc {api.common._script_name()} in.bed.gz + +[Example] Index a SAM file: + $ fuc {api.common._script_name()} in.sam.gz + +[Example] Index a VCF file: + $ fuc {api.common._script_name()} in.vcf.gz +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Index a GFF/BED/SAM/VCF file with Tabix."""""" + ) + parser.add_argument( + 'file', + help= +""""""File to be indexed."""""" + ) + parser.add_argument( + '--force', + action='store_true', + help= +""""""Force to overwrite the index file if it is present."""""" + ) + +def main(args): + if '.vcf' in args.file: + preset = 'vcf' + elif '.sam' in args.file: + preset = 'sam' + elif '.gff' in args.file: + preset = 'gff' + elif '.bed' in args.file: + preset = 'bed' + else: + raise ValueError('Unsupported file format') + + pysam.tabix_index(args.file, preset=preset, force=args.force) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/vcf_index.py",".py","1067","45","import sys + +from .. import api + +import pysam + +description = """""" +Index a VCF file. + +This command will create an index file (.tbi) for the input VCF. +"""""" + +epilog = f"""""" +[Example] Index a compressed VCF file: + $ fuc {api.common._script_name()} in.vcf.gz + +[Example] Index an uncompressed VCF file (will create a compressed VCF first): + $ fuc {api.common._script_name()} in.vcf +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help='Index a VCF file.', + ) + parser.add_argument( + 'vcf', + help= +""""""Input VCF file to be indexed. When an uncompressed file is +given, the command will automatically create a BGZF +compressed copy of the file (.gz) before indexing."""""" + ) + parser.add_argument( + '--force', + action='store_true', + help= +""""""Force to overwrite the index file if it is already present."""""" + ) + +def main(args): + pysam.tabix_index(args.vcf, preset='vcf', force=args.force) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/ngs_bam2fq.py",".py","3878","152","import os +import sys +import shutil + +from .. import api + +import pandas as pd + +description = """""" +Pipeline for converting BAM files to FASTQ files. + +This pipeline assumes that input BAM files consist of paired-end reads, and +will output two zipped FASTQ files for each sample (forward and reverse +reads). That is, SAMPLE.bam will produce SAMPLE_R1.fastq.gz and +SAMPLE_R2.fastq.gz. + +By default, the pipeline will be run in a local environment. Use --qsub to +leverage a parallel environment, in which case SGE is required. + +External dependencies: + - [Required] SAMtools: Required for BAM to FASTQ conversion. + - [Optional] SGE: Required for job submission (i.e. qsub). + +Manifest columns: + - [Required] BAM: Input BAM file. +"""""" + +epilog = f"""""" +[Example] Run in local environment: + $ fuc {api.common._script_name()} \\ + manifest.csv \\ + output_dir \\ + --thread 10 + $ sh output_dir/shell/runme.sh + +[Example] Run in parallel environment with specific queue: + $ fuc {api.common._script_name()} \\ + manifest.csv \\ + output_dir \\ + --qsub ""-q queue_name -pe pe_name 10"" \\ + --thread 10 + $ sh output_dir/shell/runme.sh + +[Example] Run in parallel environment with specific nodes: + $ fuc {api.common._script_name()} \\ + manifest.csv \\ + output_dir \\ + --qsub ""-l h='node_A|node_B' -pe pe_name 10"" \\ + --thread 10 + $ sh output_dir/shell/runme.sh +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Pipeline for converting BAM files to FASTQ files."""""" + ) + parser.add_argument( + 'manifest', + help= +""""""Sample manifest CSV file."""""" + ) + parser.add_argument( + 'output', + type=os.path.abspath, + help= +""""""Output directory."""""" + ) + parser.add_argument( + '--thread', + metavar='INT', + type=int, + default=1, + help= +""""""Number of threads to use (default: 1)."""""" + ) + parser.add_argument( + '--qsub', + metavar='TEXT', + type=str, + help= +""""""SGE resoruce to request with qsub for BAM to FASTQ +conversion. Since this oppoeration supports multithreading, +it is recommended to speicfy a parallel environment (PE) +to speed up the process (also see --thread)."""""" + ) + parser.add_argument( + '--force', + action='store_true', + help= +""""""Overwrite the output directory if it already exists."""""" + ) + +def main(args): + if os.path.exists(args.output) and args.force: + shutil.rmtree(args.output) + + os.mkdir(args.output) + os.mkdir(f'{args.output}/shell') + os.mkdir(f'{args.output}/log') + + with open(f'{args.output}/command.txt', 'w') as f: + f.write(' '.join(sys.argv) + '\n') + + df = pd.read_csv(args.manifest) + + names = [] + + is_local = args.qsub is None + + if is_local: + conda_env = f'# source activate {api.common.conda_env()}' + else: + conda_env = f'source activate {api.common.conda_env()}' + + for i, r in df.iterrows(): + name = os.path.basename(r.BAM).replace('.bam', '') + names.append(name) + with open(f'{args.output}/shell/{name}.sh', 'w') as f: + f.write( +f""""""#!/bin/bash + +## Activate conda environment. +{conda_env} + +## Convert BAM to FASTQ. +samtools collate -O -@ {args.thread} {r.BAM} | samtools fastq -0 /dev/null -1 {args.output}/{name}_R1.fastq.gz -2 {args.output}/{name}_R2.fastq.gz -s /dev/null +"""""") + + with open(f'{args.output}/shell/runme.sh', 'w') as f: + if is_local: + command = f'sh $p/shell/$name.sh > $p/log/$name.o 2> $p/log/$name.e' + else: + command = f'qsub {args.qsub} -S /bin/bash -e $p/log -o $p/log -N S1-$name $p/shell/$name.sh' + + f.write( +f""""""#!/bin/bash + +p={args.output} + +names=({"" "".join(names)}) + +for name in ${{names[@]}} +do + {command} +done +"""""") +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/bam_head.py",".py","627","34","import sys + +from .. import api + +import pysam + +description = """""" +Print the header of a BAM file. +"""""" + +epilog = f"""""" +[Example] Print the header of a BAM file: + $ fuc {api.common._script_name()} in.bam +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Print the header of a BAM file."""""" + ) + parser.add_argument( + 'bam', + help= +""""""Input alignment file."""""" + ) + +def main(args): + header = pysam.view('-H', args.bam, '--no-PG') + sys.stdout.write(header) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/maf_vcf2maf.py",".py","617","32","import sys + +from .. import api + +description = """""" +Convert a VCF file to a MAF file. +"""""" + +epilog = f"""""" +[Example] Convert VCF to MAF: + $ fuc {api.common._script_name()} in.vcf > out.maf +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Convert a VCF file to a MAF file."""""" + ) + parser.add_argument( + 'vcf', + help= +""""""Annotated VCF file."""""" + ) + +def main(args): + mf = api.pymaf.MafFrame.from_vcf(args.vcf) + sys.stdout.write(mf.to_string()) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/fq_count.py",".py","1158","49","import sys +import subprocess + +from .. import api + +description = """""" +Count sequence reads in FASTQ files. +"""""" + +epilog = f"""""" +[Example] When the input is a FASTQ file: + $ fuc {api.common._script_name()} in1.fastq in2.fastq + +[Example] When the input is stdin: + $ cat fastq.list | fuc {api.common._script_name()} +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Count sequence reads in FASTQ files."""""" + ) + parser.add_argument( + 'fastq', + nargs='*', + help= +""""""Input FASTQ files (compressed or uncompressed) (default: stdin)."""""" + ) + +def main(args): + if args.fastq: + fastqs = args.fastq + elif not sys.stdin.isatty(): + fastqs = sys.stdin.read().rstrip('\n').split('\n') + else: + raise ValueError('No input files detected.') + + for fastq in fastqs: + if fastq.endswith('.gz'): + cat = 'zcat' + else: + cat = 'cat' + command = f'echo $({cat} < {fastq} | wc -l) / 4 | bc' + subprocess.run(command, shell=True) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/fuc_bgzip.py",".py","1349","53","import sys + +from .. import api + +from Bio import bgzf + +description = """""" +Write a BGZF compressed file. + +BGZF (Blocked GNU Zip Format) is a modified form of gzip compression which +can be applied to any file format to provide compression with efficient +random access. In addition to being required for random access to and writing +of BAM files, the BGZF format can also be used for most of the sequence data +formats (e.g. FASTA, FASTQ, GenBank, VCF, MAF). +"""""" + +epilog = f"""""" +[Example] When the input is a VCF file: + $ fuc {api.common._script_name()} in.vcf > out.vcf.gz + +[Example] When the input is stdin: + $ cat in.vcf | fuc {api.common._script_name()} > out.vcf.gz +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Write a BGZF compressed file."""""" + ) + parser.add_argument( + 'file', + nargs='*', + help= +""""""Input file to be compressed (default: stdin)."""""" + ) + +def main(args): + if args.file: + with open(args.file[0]) as f: + data = f.read() + elif not sys.stdin.isatty(): + data = sys.stdin.read() + else: + raise ValueError('No input data detected') + + w = bgzf.BgzfWriter(fileobj=sys.stdout.buffer) + w.write(data) + w.close() +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/vcf_call.py",".py","3672","125","import sys + +from .. import api + +description = """""" +Call SNVs and indels from BAM files. + +Under the hood, the command utilizes the bcftool program to call variants. +"""""" + +epilog = f"""""" +[Example] Specify regions manually: + $ fuc {api.common._script_name()} ref.fa 1.bam 2.bam \\ + -r chr1:100-200 chr2:400-500 > out.vcf + +[Example] Specify regions with a BED file: + $ fuc {api.common._script_name()} ref.fa bam.list \\ + -r in.bed > out.vcf +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Call SNVs and indels from BAM files."""""" + ) + parser.add_argument( + 'fasta', + help= +""""""Reference FASTA file."""""" + ) + parser.add_argument( + 'bams', + nargs='+', + help= +""""""One or more input BAM files. Alternatively, you can +provide a text file (.txt, .tsv, .csv, or .list) +containing one BAM file per line."""""" + ) + parser.add_argument( + '-r', + '--regions', + nargs='+', + metavar='TEXT', + help= +""""""By default, the command looks at each genomic +position with coverage in BAM files, which can be +excruciatingly slow for large files (e.g. whole +genome sequencing). Therefore, use this argument to +only call variants in given regions. Each region must +have the format chrom:start-end and be a half-open +interval with (start, end]. This means, for example, +chr1:100-103 will extract positions 101, 102, and +103. Alternatively, you can provide a BED file +(compressed or uncompressed) to specify regions. Note +that the 'chr' prefix in contig names (e.g. 'chr1' +vs. '1') will be automatically added or removed as +necessary to match the input BAM's contig names."""""" + ) + parser.add_argument( + '--min-mq', + metavar='INT', + type=int, + default=1, + help= +""""""Minimum mapping quality for an alignment to be used +(default: 1)."""""" + ) + parser.add_argument( + '--max-depth', + metavar='INT', + type=int, + default=250, + help= +""""""At a position, read maximally this number of reads +per input file (default: 250)."""""" + ) + parser.add_argument( + '--dir-path', + metavar='PATH', + help= +""""""By default, intermediate files (likelihoods.bcf, +calls.bcf, and calls.normalized.bcf) will be stored +in a temporary directory, which is automatically +deleted after creating final VCF. If you provide a +directory path, intermediate files will be stored +there."""""" + ) + parser.add_argument( + '--gap_frac', + metavar='FLOAT', + type=float, + default=0.002, + help= +""""""Minimum fraction of gapped reads for calling indels +(default: 0.002)."""""" + ) + parser.add_argument( + '--group-samples', + metavar='PATH', + help= +""""""By default, all samples are assumed to come from a +single population. This option allows to group +samples into populations and apply the HWE assumption +within but not across the populations. To use this +option, provide a tab-delimited text file with sample +names in the first column and group names in the +second column. If '--group-samples -' is given +instead, no HWE assumption is made at all and +single-sample calling is performed. Note that in low +coverage data this inflates the rate of false +positives. Therefore, make sure you know what you are +doing."""""" + ) + +def main(args): + api.pyvcf.call( + args.fasta, args.bams, regions=args.regions, path='-', + min_mq=args.min_mq, max_depth=args.max_depth, dir_path=args.dir_path, + gap_frac=args.gap_frac, group_samples=args.group_samples + ) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/vcf_slice.py",".py","1582","53","import sys + +from .. import api + +description = """""" +Slice a VCF file for specified regions. +"""""" + +epilog = f"""""" +[Example] Specify regions manually: + $ fuc {api.common._script_name()} in.vcf.gz 1:100-300 2:400-700 > out.vcf + +[Example] Speicfy regions with a BED file: + $ fuc {api.common._script_name()} in.vcf.gz regions.bed > out.vcf + +[Example] Output a compressed file: + $ fuc {api.common._script_name()} in.vcf.gz regions.bed | fuc fuc-bgzip > out.vcf.gz +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Slice a VCF file for specified regions."""""" + ) + parser.add_argument( + 'vcf', + help= +""""""Input VCF file must be already BGZF compressed (.gz) and +indexed (.tbi) to allow random access. A VCF file can be +compressed with the fuc-bgzip command and indexed with the +vcf-index command."""""" + ) + parser.add_argument( + 'regions', + nargs='+', + help= +""""""One or more regions to be sliced. Each region must have the +format chrom:start-end and be a half-open interval with +(start, end]. This means, for example, chr1:100-103 will +extract positions 101, 102, and 103. Alternatively, you can +provide a BED file (compressed or uncompressed) to specify +regions. Note that the 'chr' prefix in contig names (e.g. +'chr1' vs. '1') will be automatically added or removed as +necessary to match the input VCF's contig names."""""" + ) + +def main(args): + api.pyvcf.slice(args.vcf, args.regions, path='-') +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/ngs_pon.py",".py","5613","236","import os +import sys +import shutil + +from .. import api + +import pandas as pd + +description = """""" +Pipeline for constructing a panel of normals (PoN). + +Dependencies: + - GATK: Required for constructing PoN. + +Manifest columns: + - BAM: Path to recalibrated BAM file. +"""""" + +epilog = f"""""" +[Example] Specify queue: + $ fuc {api.common._script_name()} \\ + manifest.csv \\ + ref.fa \\ + output_dir \\ + ""-q queue_name"" \\ + ""-Xmx15g -Xms15g"" + +[Example] Specify nodes: + $ fuc {api.common._script_name()} \\ + manifest.csv \\ + ref.fa \\ + output_dir \\ + ""-l h='node_A|node_B'"" \\ + ""-Xmx15g -Xms15g"" +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Pipeline for constructing a panel of normals (PoN)."""""" + ) + parser.add_argument( + 'manifest', + help= +""""""Sample manifest CSV file."""""" + ) + parser.add_argument( + 'fasta', + help= +""""""Reference FASTA file."""""" + ) + parser.add_argument( + 'output', + type=os.path.abspath, + help= +""""""Output directory."""""" + ) + parser.add_argument( + 'qsub', + type=str, + help= +""""""SGE resoruce to request for qsub."""""" + ) + parser.add_argument( + 'java', + help= +""""""Java resoruce to request for GATK."""""" + ) + parser.add_argument( + '--bed', + metavar='PATH', + type=str, + help= +""""""BED file."""""" + ) + parser.add_argument( + '--force', + action='store_true', + help= +""""""Overwrite the output directory if it already exists."""""" + ) + parser.add_argument( + '--keep', + action='store_true', + help= +""""""Keep temporary files."""""" + ) + +def main(args): + if os.path.exists(args.output) and args.force: + shutil.rmtree(args.output) + + os.mkdir(args.output) + os.mkdir(f'{args.output}/shell') + os.mkdir(f'{args.output}/log') + os.mkdir(f'{args.output}/temp') + + with open(f'{args.output}/command.txt', 'w') as f: + f.write(' '.join(sys.argv) + '\n') + + df = pd.read_csv(args.manifest) + + if args.keep: + remove = '# rm' + else: + remove = 'rm' + + basenames = [] + + for i, r in df.iterrows(): + basename = os.path.basename(r.BAM) + basenames.append(basename) + + with open(f'{args.output}/shell/S1-{basename}.sh', 'w') as f: + + ########### + # Mutect2 # + ########### + + command = 'gatk Mutect2' + command += f' --QUIET' + command += f' --java-options ""{args.java}""' + command += f' -R {args.fasta}' + command += f' -I {r.BAM}' + command += f' -max-mnp-distance 0' + command += f' -O {args.output}/temp/{basename}.vcf' + + if args.bed is not None: + command += f' -L {args.bed}' + + f.write( +f""""""#!/bin/bash + +# Activate conda environment. +source activate {api.common.conda_env()} + +# Run Mutect2 in tumor-only mode for each normal sample. +{command} +"""""") + + chroms = [str(i) for i in range(1, 23)] + ['X', 'Y'] + + if api.pybam.has_chr_prefix(df.BAM[0]): + chroms = ['chr' + x for x in chroms] + + for chrom in chroms: + with open(f'{args.output}/shell/S2-{chrom}.sh', 'w') as f: + + #################### + # GenomicsDBImport # + #################### + + command1 = 'gatk GenomicsDBImport' + command1 += f' --QUIET' + command1 += f' --java-options ""{args.java}""' + command1 += f' -R {args.fasta}' + command1 += f' -L {chrom}' + command1 += f' --genomicsdb-workspace-path {args.output}/temp/db-{chrom}' + command1 += ' ' + ' '.join([f'-V {args.output}/temp/{x}.vcf' for x in basenames]) + + ############################### + # CreateSomaticPanelOfNormals # + ############################### + + command2 = 'gatk CreateSomaticPanelOfNormals' + command2 += f' --QUIET' + command2 += f' --java-options ""{args.java}""' + command2 += f' -R {args.fasta}' + command2 += f' -V gendb://{args.output}/temp/db-{chrom}' + command2 += f' -O {args.output}/temp/{chrom}.pon.vcf' + + f.write( +f""""""#!/bin/bash + +# Activate conda environment. +source activate {api.common.conda_env()} + +# Create a GenomicsDB from the normal Mutect2 calls. +{command1} + +# Combine the normal calls. +{command2} +"""""") + + with open(f'{args.output}/shell/S3.sh', 'w') as f: + + ############## + # GatherVcfs # + ############## + + command = 'gatk GatherVcfs' + command += f' --QUIET' + command += f' --java-options ""{args.java}""' + command += f' -O {args.output}/merged.pon.vcf' + command += ' ' + ' '.join([f'-I {args.output}/temp/{x}.pon.vcf' for x in chroms]) + + f.write( +f""""""#!/bin/bash + +# Activate conda environment. +source activate {api.common.conda_env()} + +# Merge VCF files. +{command} + +# Remove temporary files. +{remove} -r {args.output}/temp/* +"""""") + + with open(f'{args.output}/shell/qsubme.sh', 'w') as f: + f.write( +f""""""#!/bin/bash + +p={args.output} + +samples=({"" "".join(basenames)}) + +chroms=({"" "".join(chroms)}) + +for sample in ${{samples[@]}} +do + qsub {args.qsub} -S /bin/bash -e $p/log -o $p/log -N S1 $p/shell/S1-$sample.sh +done + +for chrom in ${{chroms[@]}} +do + qsub {args.qsub} -S /bin/bash -e $p/log -o $p/log -N S2 -hold_jid S1 $p/shell/S2-$chrom.sh +done + +qsub {args.qsub} -S /bin/bash -e $p/log -o $p/log -N S3 -hold_jid S2 $p/shell/S3.sh +"""""") +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/vcf_vep.py",".py","2157","72","import sys + +from .. import api + +description = """""" +Filter a VCF file by annotations from Ensembl VEP. +"""""" + +epilog = f"""""" +[Example] Select variants in the TP53 gene: + $ fuc {api.common._script_name()} in.vcf ""SYMBOL == 'TP53'"" > out.vcf + +[Example] Exclude variants from the TP53 gene: + $ fuc {api.common._script_name()} in.vcf ""SYMBOL != 'TP53'"" > out.vcf + +[Example] Same as above: + $ fuc {api.common._script_name()} in.vcf ""SYMBOL == 'TP53'"" --opposite > out.vcf + +[Example] Select splice donor or stop-gain variants: + $ fuc {api.common._script_name()} in.vcf \\ + ""Consequence in ['splice_donor_variant', 'stop_gained']"" > out.vcf + +[Example] Build a complex query to select specific variants: + $ fuc {api.common._script_name()} in.vcf \\ + ""(SYMBOL == 'TP53') and (Consequence.str.contains('stop_gained'))"" > out.vcf + +[Example] Select variants whose gnomAD AF is less than 0.001: + $ fuc {api.common._script_name()} in.vcf ""gnomAD_AF < 0.001"" > out.vcf + +[Example] Variants without AF data will be treated as having AF of 0: + $ fuc {api.common._script_name()} in.vcf ""gnomAD_AF < 0.001"" --as_zero > out.vcf +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Filter a VCF file by annotations from Ensembl VEP."""""" + ) + parser.add_argument( + 'vcf', + help= +""""""VCF file annotated by Ensembl VEP (compressed or uncompressed)."""""" + ) + parser.add_argument( + 'expr', + help= +""""""Query expression to evaluate."""""" + ) + parser.add_argument( + '--opposite', + action='store_true', + help= +""""""Use this flag to return only records that don't +meet the said criteria."""""" + ) + parser.add_argument( + '--as_zero', + action='store_true', + help= +""""""Use this flag to treat missing values as zero instead of NaN."""""" + ) + +def main(args): + vf = api.pyvcf.VcfFrame.from_file(args.vcf) + filtered_vf = api.pyvep.filter_query(vf, args.expr, + opposite=args.opposite, as_zero=args.as_zero) + sys.stdout.write(filtered_vf.to_string()) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/ngs_quant.py",".py","4185","181","import os +import sys +import shutil + +from .. import api + +import pandas as pd + +description = """""" +Pipeline for running RNAseq quantification from FASTQ files with Kallisto. + +External dependencies: + - SGE: Required for job submission (i.e. qsub). + - kallisto: Required for RNAseq quantification. + +Manifest columns: + - Name: Sample name. + - Read1: Path to forward FASTA file. + - Read2: Path to reverse FASTA file. +"""""" + +epilog = f"""""" +[Example] Specify queue: + $ fuc {api.common._script_name()} \\ + manifest.csv \\ + transcripts.idx \\ + output_dir \\ + ""-q queue_name -pe pe_name 10"" \\ + --thread 10 +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Pipeline for running RNAseq quantification from FASTQ files +with Kallisto."""""" + ) + parser.add_argument( + 'manifest', + help= +""""""Sample manifest CSV file."""""" + ) + parser.add_argument( + 'index', + help= +""""""Kallisto index file."""""" + ) + parser.add_argument( + 'output', + type=os.path.abspath, + help= +""""""Output directory."""""" + ) + parser.add_argument( + 'qsub', + type=str, + help= +""""""SGE resoruce to request for qsub."""""" + ) + parser.add_argument( + '--thread', + metavar='INT', + type=int, + default=1, + help= +""""""Number of threads to use (default: 1)."""""" + ) + parser.add_argument( + '--bootstrap', + metavar='INT', + type=int, + default=50, + help= +""""""Number of bootstrap samples (default: 50)."""""" + ) + parser.add_argument( + '--job', + metavar='TEXT', + type=str, + help= +""""""Job submission ID for SGE."""""" + ) + parser.add_argument( + '--force', + action='store_true', + help= +""""""Overwrite the output directory if it already exists."""""" + ) + parser.add_argument( + '--posix', + action='store_true', + help= +""""""Set the environment variable HDF5_USE_FILE_LOCKING=FALSE +before running Kallisto. This is required for shared Posix +Filesystems (e.g. NFS, Lustre)."""""" + ) + parser.add_argument( + '--stranded', + metavar='TEXT', + default='none', + choices=['none', 'forward', 'reverse'], + help= +""""""Strand specific reads (default: 'none') (choices: +'none', 'forward', 'reverse')."""""" + ) + +def main(args): + if os.path.exists(args.output) and args.force: + shutil.rmtree(args.output) + + os.mkdir(args.output) + os.mkdir(f'{args.output}/shell') + os.mkdir(f'{args.output}/log') + + with open(f'{args.output}/command.txt', 'w') as f: + f.write(' '.join(sys.argv) + '\n') + + #################### + # POSIX filesystem # + #################### + + if args.posix: + export = 'export HDF5_USE_FILE_LOCKING=FALSE' + else: + export = '# export HDF5_USE_FILE_LOCKING=FALSE' + + df = pd.read_csv(args.manifest) + + for i, r in df.iterrows(): + with open(f'{args.output}/shell/S1-{r.Name}.sh', 'w') as f: + + command = 'kallisto quant' + command += f' -i {args.index}' + command += f' -o {args.output}/{r.Name}' + command += f' -b {args.bootstrap}' + command += f' -t {args.thread}' + if args.stranded == 'forward': + command += ' --fr-stranded' + elif args.stranded == 'reverse': + command += ' --rf-stranded' + else: + pass + command += f' {r.Read1}' + command += f' {r.Read2}' + + f.write( +f""""""#!/bin/bash + +# Optimize for POSIX filesystem. +{export} + +# Activate conda environment. +source activate {api.common.conda_env()} + +# Run Kallisto for RNAseq quantification. +{command} +"""""") + + if args.job is None: + jid = '' + else: + jid = args.job + '-' + + with open(f'{args.output}/shell/qsubme.sh', 'w') as f: + f.write( +f""""""#!/bin/bash + +p={args.output} + +samples=({"" "".join(df.Name)}) + +for sample in ${{samples[@]}} +do + qsub {args.qsub} -S /bin/bash -e $p/log -o $p/log -N {jid}S1-$sample $p/shell/S1-$sample.sh +done +"""""") +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/ngs_hc.py",".py","8817","339","import os +import sys +import shutil + +from .. import api + +import pandas as pd + +description = """""" +Pipeline for germline short variant discovery. + +External dependencies: + - SGE: Required for job submission (i.e. qsub). + - GATK: Required for variant calling (i.e. HaplotypeCaller) and filtration. + +Manifest columns: + - BAM: Recalibrated BAM file. +"""""" + +epilog = f"""""" +[Example] Specify queue: + $ fuc {api.common._script_name()} \\ + manifest.csv \\ + ref.fa \\ + output_dir \\ + ""-q queue_name"" \\ + ""-Xmx15g -Xms15g"" \\ + ""-Xmx30g -Xms30g"" \\ + --dbsnp dbSNP.vcf + +[Example] Specify nodes: + $ fuc {api.common._script_name()} \\ + manifest.csv \\ + ref.fa \\ + output_dir \\ + ""-l h='node_A|node_B'"" \\ + ""-Xmx15g -Xms15g"" \\ + ""-Xmx30g -Xms30g"" \\ + --bed in.bed +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Pipeline for germline short variant discovery."""""" + ) + parser.add_argument( + 'manifest', + help= +""""""Sample manifest CSV file."""""" + ) + parser.add_argument( + 'fasta', + help= +""""""Reference FASTA file."""""" + ) + parser.add_argument( + 'output', + type=os.path.abspath, + help= +""""""Output directory."""""" + ) + parser.add_argument( + 'qsub', + type=str, + help= +""""""SGE resoruce to request for qsub."""""" + ) + parser.add_argument( + 'java1', + type=str, + help= +""""""Java resoruce to request for single-sample variant calling."""""" + ) + parser.add_argument( + 'java2', + type=str, + help= +""""""Java resoruce to request for joint variant calling."""""" + ) + parser.add_argument( + '--bed', + metavar='PATH', + type=str, + help= +""""""BED file."""""" + ) + parser.add_argument( + '--dbsnp', + metavar='PATH', + type=str, + help= +""""""VCF file from dbSNP."""""" + ) + parser.add_argument( + '--thread', + metavar='INT', + type=int, + default=1, + help= +""""""Number of threads to use (default: 1)."""""" + ) + parser.add_argument( + '--batch', + metavar='INT', + type=int, + default=0, + help= +""""""Batch size used for GenomicsDBImport (default: 0). This +controls the number of samples for which readers are +open at once and therefore provides a way to minimize +memory consumption. The size of 0 means no batching (i.e. +readers for all samples will be opened at once)."""""" + ) + parser.add_argument( + '--job', + metavar='TEXT', + type=str, + help= +""""""Job submission ID for SGE."""""" + ) + parser.add_argument( + '--force', + action='store_true', + help= +""""""Overwrite the output directory if it already exists."""""" + ) + parser.add_argument( + '--keep', + action='store_true', + help= +""""""Keep temporary files."""""" + ) + parser.add_argument( + '--posix', + action='store_true', + help= +""""""Set GenomicsDBImport to allow for optimizations to improve +the usability and performance for shared Posix Filesystems +(e.g. NFS, Lustre). If set, file level locking is disabled +and file system writes are minimized by keeping a higher +number of file descriptors open for longer periods of time. +Use with --batch if keeping a large number of file +descriptors open is an issue."""""" + ) + +def main(args): + if os.path.exists(args.output) and args.force: + shutil.rmtree(args.output) + + os.mkdir(args.output) + os.mkdir(f'{args.output}/shell') + os.mkdir(f'{args.output}/log') + os.mkdir(f'{args.output}/temp') + + with open(f'{args.output}/command.txt', 'w') as f: + f.write(' '.join(sys.argv) + '\n') + + df = pd.read_csv(args.manifest) + + if args.keep: + remove = '# rm' + else: + remove = 'rm' + + java_shared = f'-XX:ParallelGCThreads={args.thread} -XX:ConcGCThreads={args.thread}' + + basenames = [] + + for i, r in df.iterrows(): + basename = os.path.basename(r.BAM) + basenames.append(basename) + + with open(f'{args.output}/shell/S1-{basename}.sh', 'w') as f: + + ################### + # HaplotypeCaller # + ################### + + command = 'gatk HaplotypeCaller' + command += f' --QUIET' + command += f' --java-options ""{java_shared} {args.java1}""' + command += f' -R {args.fasta}' + command += f' --native-pair-hmm-threads {args.thread}' + command += f' --emit-ref-confidence GVCF' + command += f' -I {r.BAM}' + command += f' -O {args.output}/temp/{basename}.g.vcf' + + if args.bed is not None: + command += f' -L {args.bed}' + + if args.dbsnp is not None: + command += f' --dbsnp {args.dbsnp}' + + f.write( +f""""""#!/bin/bash + +# Activate conda environment. +source activate {api.common.conda_env()} + +# Call variants per-sample. +{command} +"""""") + + chroms = [str(i) for i in range(1, 23)] + ['X', 'Y'] + + if api.pybam.has_chr_prefix(df.BAM[0]): + chroms = ['chr' + x for x in chroms] + + for chrom in chroms: + with open(f'{args.output}/shell/S2-{chrom}.sh', 'w') as f: + + #################### + # POSIX filesystem # + #################### + + if args.posix: + export = 'export TILEDB_DISABLE_FILE_LOCKING=1' + else: + export = '# export TILEDB_DISABLE_FILE_LOCKING=1' + + #################### + # GenomicsDBImport # + #################### + + command1 = 'gatk GenomicsDBImport' + command1 += f' --QUIET' + command1 += f' --java-options ""{java_shared} {args.java2}""' + command1 += f' -L {chrom}' + command1 += f' --reader-threads {args.thread}' + if args.posix: + command1 += ' --genomicsdb-shared-posixfs-optimizations' + command1 += f' --batch-size {args.batch}' + command1 += f' --genomicsdb-workspace-path {args.output}/temp/db-{chrom}' + command1 += ' ' + ' '.join([f'-V {args.output}/temp/{x}.g.vcf' for x in basenames]) + + ################# + # GenotypeGVCFs # + ################# + + command2 = 'gatk GenotypeGVCFs' + command2 += f' --QUIET' + command2 += f' --java-options ""{java_shared} {args.java2}""' + command2 += f' -R {args.fasta}' + command2 += f' -V gendb://{args.output}/temp/db-{chrom}' + command2 += f' -O {args.output}/temp/{chrom}.joint.vcf' + + if args.dbsnp is not None: + command2 += f' --dbsnp {args.dbsnp}' + + ##################### + # VariantFiltration # + ##################### + + command3 = 'gatk VariantFiltration' + command3 += f' --QUIET' + command3 += f' --java-options ""{java_shared} {args.java2}""' + command3 += f' -R {args.fasta}' + command3 += f' -O {args.output}/temp/{chrom}.joint.filtered.vcf' + command3 += f' --variant {args.output}/temp/{chrom}.joint.vcf' + command3 += f' --filter-expression ""QUAL <= 50.0""' + command3 += f' --filter-name QUALFilter' + + f.write( +f""""""#!/bin/bash + +# Optimize for POSIX filesystem. +{export} + +# Activate conda environment. +source activate {api.common.conda_env()} + +# Consolidate GVCFs. +{command1} + +# Joint-call cohort. +{command2} + +# Filter variants. +{command3} +"""""") + + with open(f'{args.output}/shell/S3.sh', 'w') as f: + + ############## + # GatherVcfs # + ############## + + command = 'gatk GatherVcfs' + command += f' --QUIET' + command += f' --java-options ""{java_shared} {args.java2}""' + command += f' -O {args.output}/merged.joint.filtered.vcf' + command += ' ' + ' '.join([f'-I {args.output}/temp/{x}.joint.filtered.vcf' for x in chroms]) + + f.write( +f""""""#!/bin/bash + +# Activate conda environment. +source activate {api.common.conda_env()} + +# Merge VCF files. +{command} + +# Remove temporary files. +{remove} -r {args.output}/temp/* +"""""") + + if args.job is None: + jid = '' + else: + jid = '-' + args.job + + with open(f'{args.output}/shell/qsubme.sh', 'w') as f: + f.write( +f""""""#!/bin/bash + +p={args.output} + +samples=({"" "".join(basenames)}) + +chroms=({"" "".join(chroms)}) + +for sample in ${{samples[@]}} +do + qsub {args.qsub} -S /bin/bash -e $p/log -o $p/log -N S1{jid} $p/shell/S1-$sample.sh +done + +for chrom in ${{chroms[@]}} +do + qsub {args.qsub} -S /bin/bash -e $p/log -o $p/log -N S2{jid} -hold_jid S1{jid} $p/shell/S2-$chrom.sh +done + +qsub {args.qsub} -S /bin/bash -e $p/log -o $p/log -N S3{jid} -hold_jid S2{jid} $p/shell/S3.sh +"""""") +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/bam_index.py",".py","509","29","from .. import api + +description = """""" +Index a BAM file. +"""""" + +epilog = f"""""" +[Example] Index a BAM file: + $ fuc {api.common._script_name()} in.bam +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Index a BAM file."""""" + ) + parser.add_argument( + 'bam', + help= +""""""Input alignment file."""""" + ) + +def main(args): + api.pybam.index(args.bam) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/fuc_undetm.py",".py","1503","65","import gzip + +from .. import api + +description = """""" +Compute top unknown barcodes using undertermined FASTQ from bcl2fastq. + +This command will compute top unknown barcodes using undertermined FASTQ from +the bcl2fastq or bcl2fastq2 prograrm. +"""""" + +epilog = f"""""" +[Example] Compute top unknown barcodes: + $ fuc {api.common._script_name()} Undetermined_S0_R1_001.fastq.gz +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Compute top unknown barcodes using undertermined FASTQ from +bcl2fastq."""""" + ) + parser.add_argument( + 'fastq', + help= +""""""Undertermined FASTQ (compressed or uncompressed)."""""" + ) + parser.add_argument( + '--count', + metavar='INT', + type=int, + default=30, + help= +""""""Number of top unknown barcodes to return (default: 30)."""""" + ) + +def main(args): + if args.fastq.endswith('.gz'): + f = gzip.open(args.fastq, 'rt') + else: + f = open(args.fastq) + + data = {} + + for line in f: + if not line.startswith('@'): + continue + fields = line.strip().split(':') + name = fields[-1] + if name not in data: + data[name] = 0 + data[name] += 1 + + f.close() + + data = dict(sorted(data.items(), key=lambda x: x[1], reverse=True)) + + for i, name in enumerate(data): + if i < 30: + print(name, data[name]) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/ngs_m2.py",".py","7491","264","import os +import sys +import shutil + +from .. import api + +import pandas as pd + +description = """""" +Pipeline for somatic short variant discovery. + +External dependencies: + - SGE: Required for job submission (i.e. qsub). + - GATK: Required for variant calling (i.e. Mutect2) and filtration. + +Manifest columns: + - Tumor: Recalibrated BAM file for tumor. + - Normal: Recalibrated BAM file for matched normal. +"""""" + +epilog = f"""""" +[Example] Specify queue: + $ fuc {api.common._script_name()} \\ + manifest.csv \\ + ref.fa \\ + output_dir \\ + pon.vcf \\ + germline.vcf \\ + ""-q queue_name"" \\ + ""-Xmx15g -Xms15g"" + +[Example] Specify nodes: + $ fuc {api.common._script_name()} \\ + manifest.csv \\ + ref.fa \\ + output_dir \\ + pon.vcf \\ + germline.vcf \\ + ""-l h='node_A|node_B'"" \\ + ""-Xmx15g -Xms15g"" \\ + --bed in.bed +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + help='Pipeline for somatic short variant discovery.', + description=description, + ) + parser.add_argument( + 'manifest', + help= +""""""Sample manifest CSV file."""""" + ) + parser.add_argument( + 'fasta', + help= +""""""Reference FASTA file."""""" + ) + parser.add_argument( + 'output', + type=os.path.abspath, + help= +""""""Output directory."""""" + ) + parser.add_argument( + 'pon', + help= +""""""PoN VCF file."""""" + ) + parser.add_argument( + 'germline', + help= +""""""Germline VCF file."""""" + ) + parser.add_argument( + 'qsub', + type=str, + help= +""""""SGE resoruce to request for qsub."""""" + ) + parser.add_argument( + 'java', + type=str, + help= +""""""Java resoruce to request for GATK."""""" + ) + parser.add_argument( + '--bed', + metavar='PATH', + type=str, + help= +""""""BED file."""""" + ) + parser.add_argument( + '--force', + action='store_true', + help= +""""""Overwrite the output directory if it already exists."""""" + ) + parser.add_argument( + '--keep', + action='store_true', + help= +""""""Keep temporary files."""""" + ) + +def main(args): + if os.path.exists(args.output) and args.force: + shutil.rmtree(args.output) + + os.mkdir(args.output) + os.mkdir(f'{args.output}/shell') + os.mkdir(f'{args.output}/log') + os.mkdir(f'{args.output}/temp') + + with open(f'{args.output}/command.txt', 'w') as f: + f.write(' '.join(sys.argv) + '\n') + + df = pd.read_csv(args.manifest) + + if args.keep: + remove = '# rm' + else: + remove = 'rm' + + basenames = [] + + for i, r in df.iterrows(): + basename = api.pybam.tag_sm(r.Tumor)[0] + basenames.append(basename) + + with open(f'{args.output}/shell/S1-{basename}.sh', 'w') as f: + + ########### + # Mutect2 # + ########### + + command1 = 'gatk Mutect2' + command1 += f' --QUIET' + command1 += f' --java-options ""{args.java}""' + command1 += f' -R {args.fasta}' + command1 += f' -pon {args.pon}' + command1 += f' --germline-resource {args.germline}' + command1 += f' --f1r2-tar-gz {args.output}/temp/{basename}.f1r2.tar.gz' + command1 += f' -I {r.Tumor}' + command1 += f' -I {r.Normal}' + command1 += f' -normal {api.pybam.tag_sm(r.Normal)[0]}' + command1 += f' -O {args.output}/temp/{basename}.raw.vcf' + + if args.bed is not None: + command1 += f' -L {args.bed}' + + ###################### + # GetPileupSummaries # + ###################### + + command2 = 'gatk GetPileupSummaries' + command2 += f' --QUIET' + command2 += f' --java-options ""{args.java}""' + command2 += f' -I {r.Tumor}' + command2 += f' -V {args.germline}' + command2 += f' -L {args.output}/temp/{basename}.raw.vcf' + command2 += f' -O {args.output}/temp/{basename}.tumor-pileups.table' + + ###################### + # GetPileupSummaries # + ###################### + + command3 = 'gatk GetPileupSummaries' + command3 += f' --QUIET' + command3 += f' --java-options ""{args.java}""' + command3 += f' -I {r.Normal}' + command3 += f' -V {args.germline}' + command3 += f' -L {args.output}/temp/{basename}.raw.vcf' + command3 += f' -O {args.output}/temp/{basename}.normal-pileups.table' + + ########################## + # CalculateContamination # + ########################## + + command4 = 'gatk CalculateContamination' + command4 += f' --QUIET' + command4 += f' --java-options ""{args.java}""' + command4 += f' -I {args.output}/temp/{basename}.tumor-pileups.table' + command4 += f' -matched {args.output}/temp/{basename}.normal-pileups.table' + command4 += f' -O {args.output}/temp/{basename}.contamination.table' + command4 += f' -segments {args.output}/temp/{basename}.segments.tsv' + + ############################# + # LearnReadOrientationModel # + ############################# + + command5 = 'gatk LearnReadOrientationModel' + command5 += f' --QUIET' + command5 += f' --java-options ""{args.java}""' + command5 += f' -I {args.output}/temp/{basename}.f1r2.tar.gz' + command5 += f' -O {args.output}/temp/{basename}.artifact-prior.tar.gz' + + ##################### + # FilterMutectCalls # + ##################### + + command6 = 'gatk FilterMutectCalls' + command6 += f' --QUIET' + command6 += f' --java-options ""{args.java}""' + command6 += f' -R {args.fasta}' + command6 += f' -V {args.output}/temp/{basename}.raw.vcf' + command6 += f' --contamination-table {args.output}/temp/{basename}.contamination.table' + command6 += f' --tumor-segmentation {args.output}/temp/{basename}.segments.tsv' + command6 += f' -ob-priors {args.output}/temp/{basename}.artifact-prior.tar.gz' + command6 += f' -O {args.output}/{basename}.filtered.vcf' + command6 += f' --filtering-stats {args.output}/temp/{basename}.filtered.vcf.filteringStats.tsv' + + f.write( +f""""""#!/bin/bash + +## Activate conda environment. +source activate {api.common.conda_env()} + +## Call candidate variants. +{command1} + +## Get pileup summary for tumor. +{command2} + +## Get pileup summary for normal. +{command3} + +## Calculate contamination. +{command4} + +## Construct orientation bias model. +{command5} + +## Filter variants. +{command6} + +# Remove temporary files. +{remove} {args.output}/temp/{basename}.f1r2.tar.gz +{remove} {args.output}/temp/{basename}.normal-pileups.table +{remove} {args.output}/temp/{basename}.tumor-pileups.table +{remove} {args.output}/temp/{basename}.raw.vcf +{remove} {args.output}/temp/{basename}.contamination.table +{remove} {args.output}/temp/{basename}.segments.tsv +{remove} {args.output}/temp/{basename}.artifact-prior.tar.gz +{remove} {args.output}/temp/{basename}.filtered.vcf.filteringStats.tsv +"""""") + + with open(f'{args.output}/shell/qsubme.sh', 'w') as f: + f.write( +f""""""#!/bin/bash + +p={args.output} + +samples=({"" "".join(basenames)}) + +for sample in ${{samples[@]}} +do + qsub {args.qsub} -S /bin/bash -e $p/log -o $p/log -N S1 $p/shell/S1-$sample.sh +done +"""""") +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/vcf_split.py",".py","1363","61","import sys +import os +import shutil + +from .. import api + +description = """""" +Split a VCF file by individual. +"""""" + +epilog = f"""""" +[Example] Split a VCF file by individual: + $ fuc {api.common._script_name()} in.vcf output_dir +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Split a VCF file by individual."""""" + ) + parser.add_argument( + 'vcf', + help= +""""""VCF file to be split."""""" + ) + parser.add_argument( + 'output', + type=os.path.abspath, + help= +""""""Output directory."""""" + ) + parser.add_argument( + '--clean', + action='store_false', + help= +""""""By default, the command will only return variants present in +each individual. Use the tag to stop this behavior and make +sure that all individuals have the same number of variants."""""" + ) + parser.add_argument( + '--force', + action='store_true', + help= +""""""Overwrite the output directory if it already exists."""""" + ) + +def main(args): + if os.path.exists(args.output) and args.force: + shutil.rmtree(args.output) + + os.mkdir(args.output) + + vfs = api.pyvcf.split(args.vcf, clean=args.clean) + + for vf in vfs: + vf.to_file(f'{args.output}/{vf.samples[0]}.vcf') +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/fuc_compf.py",".py","786","39","import filecmp + +from .. import api + +description = """""" +Compare the contents of two files. + +This command will compare the contents of two files, returning 'True' if they +are identical and 'False' otherwise. +"""""" + +epilog = f"""""" +[Example] Compare two files: + $ fuc {api.common._script_name()} left.txt right.txt +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Compare the contents of two files."""""" + ) + parser.add_argument( + 'left', + help= +""""""Input left file."""""" + ) + parser.add_argument( + 'right', + help= +""""""Input right file."""""" + ) + +def main(args): + print(filecmp.cmp(args.left, args.right)) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/tabix_slice.py",".py","1534","63","import sys + +from .. import api + +import pysam +from fuc import common, pyvcf + +description = """""" +Slice a GFF/BED/SAM/VCF file with Tabix. + +After creating an index file (.tbi), the Tabix program is able to quickly +retrieve data lines overlapping regions specified in the format +'chr:start-end'. Coordinates specified in this region format are 1-based and +inclusive. +"""""" + +epilog = f"""""" +[Example] Slice a VCF file: + $ fuc {api.common._script_name()} in.vcf.gz chr1:100-200 > out.vcf +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Slice a GFF/BED/SAM/VCF file with Tabix."""""" + ) + parser.add_argument( + 'file', + help= +""""""File to be sliced."""""" + ) + parser.add_argument( + 'regions', + nargs='+', + help= +""""""One or more regions."""""" + ) + +def main(args): + if '.vcf' in args.file: + vf = pyvcf.VcfFrame.from_file(args.file, meta_only=True) + for line in vf.meta: + sys.stdout.write(line + '\n') + sys.stdout.write('#' + '\t'.join(vf.df.columns) + '\n') + elif '.sam' in args.file: + pass + elif '.gff' in args.file: + pass + elif '.bed' in args.file: + pass + else: + raise ValueError('Unsupported file format') + + tbx = pysam.TabixFile(args.file) + + for region in args.regions: + for row in tbx.fetch(*common.parse_region(region)): + sys.stdout.write(row + '\n') +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/bed_sum.py",".py","1816","68","from .. import api + +description = """""" +Summarize a BED file. + +This command will compute various summary statistics for a BED file. The +returned statistics include the total numbers of probes and covered base +pairs for each chromosome. + +By default, covered base pairs are displayed in bp, but if you prefer you +can, for example, use '--bases 1000' to display in kb. +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + help= +""""""Summarize a BED file."""""" + ) + parser.add_argument( + 'bed', + help= +""""""Input BED file."""""" + ) + parser.add_argument( + '--bases', + metavar='INT', + type=int, + default=1, + help= +""""""Number to divide covered base pairs (default: 1)."""""" + ) + parser.add_argument( + '--decimals', + metavar='INT', + type=int, + default=0, + help= +""""""Number of decimals (default: 0)."""""" + ) + +def main(args): + bf = api.pybed.BedFrame.from_file(args.bed) + chrom_dict = {} + total = [0, 0] + for i, r in bf.gr.df.iterrows(): + chrom = r['Chromosome'] + start = r['Start'] + end = r['End'] + bases = end - start + if chrom not in chrom_dict: + chrom_dict[chrom] = [0, 0] + chrom_dict[chrom][0] += 1 + chrom_dict[chrom][1] += bases + total[0] += 1 + total[1] += bases + print('Chrom', 'Probes', 'Bases', sep='\t') + for chrom in chrom_dict: + results = chrom_dict[chrom] + probes = results[0] + bases = f'{results[1]/args.bases:.{args.decimals}f}' + print(chrom, probes, bases, sep='\t') + probes = total[0] + bases = f'{total[1]/args.bases:.{args.decimals}f}' + print('Total', probes, bases, sep='\t') +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/cov_concat.py",".py","1059","48","import sys + +from .. import api + +import pysam + +description = """""" +Concatenate depth of coverage files. +"""""" + +epilog = f"""""" +[Example] Concatenate vertically: + $ fuc {api.common._script_name()} in1.tsv in2.tsv > out.tsv + +[Example] Concatenate horizontally: + $ fuc {api.common._script_name()} in1.tsv in2.tsv --axis 1 > out.tsv +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Concatenate depth of coverage files."""""" + ) + parser.add_argument( + 'tsv', + nargs='+', + help= +""""""Input TSV files."""""" + ) + parser.add_argument( + '--axis', + metavar='INT', + default=0, + type=int, + help= +""""""The axis to concatenate along (default: 0) (choices: +0, 1 where 0 is index and 1 is columns)."""""" + ) + +def main(args): + cfs = [api.pycov.CovFrame.from_file(x) for x in args.tsv] + cf = api.pycov.concat(cfs, axis=args.axis) + sys.stdout.write(cf.to_string()) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/bam_depth.py",".py","1995","73","import sys + +from .. import api + +import pysam + +description = """""" +Compute per-base read depth from BAM files. + +Under the hood, the command computes read depth using the 'samtools depth' +command. +"""""" + +epilog = f"""""" +[Example] Specify regions manually: + $ fuc {api.common._script_name()} 1.bam 2.bam \\ + -r chr1:100-200 chr2:400-500 > out.tsv + +[Example] Specify regions with a BED file: + $ fuc {api.common._script_name()} bam.list \\ + -r in.bed > out.tsv +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Compute per-base read depth from BAM files."""""" + ) + parser.add_argument( + 'bams', + nargs='+', + help= +""""""One or more input BAM files. Alternatively, you can +provide a text file (.txt, .tsv, .csv, or .list) +containing one BAM file per line."""""" + ) + parser.add_argument( + '-r', + '--regions', + nargs='+', + metavar='TEXT', + help= +""""""By default, the command counts all reads in BAM +files, which can be excruciatingly slow for large +files (e.g. whole genome sequencing). Therefore, use +this argument to only output positions in given +regions. Each region must have the format +chrom:start-end and be a half-open interval with +(start, end]. This means, for example, chr1:100-103 +will extract positions 101, 102, and 103. +Alternatively, you can provide a BED file (compressed +or uncompressed) to specify regions. Note that the +'chr' prefix in contig names (e.g. 'chr1' vs. '1') +will be automatically added or removed as necessary +to match the input BAM's contig names."""""" + ) + parser.add_argument( + '--zero', + action='store_true', + help= +""""""Output all positions including those with zero depth."""""" + ) + +def main(args): + cf = api.pycov.CovFrame.from_bam( + args.bams, regions=args.regions, zero=args.zero + ) + sys.stdout.write(cf.to_string()) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/bam_aldepth.py",".py","1704","59","import sys + +from .. import api + +description = """""" +Count allelic depth from a BAM file. +"""""" + +epilog = f"""""" +[Example] Provide sites with a TSV file: + $ fuc {api.common._script_name()} in.bam sites.tsv > out.tsv + +[Example] Provide sites with a VCF file: + $ fuc {api.common._script_name()} in.bam sites.vcf > out.tsv +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Compute allelic depth from a BAM file."""""" + ) + parser.add_argument( + 'bam', + help= +""""""Input alignment file."""""" + ) + parser.add_argument( + 'sites', + help= +""""""TSV file containing two columns, chromosome and position. This +can also be a BED or VCF file (compressed or uncompressed). +Input type will be detected automatically."""""" + ) + +def main(args): + if '.vcf' in args.sites: + vf = api.pyvcf.VcfFrame.from_file(args.sites) + def one_row(r): + if api.pyvcf.row_hasindel(r): + return f'{r.CHROM}-{r.POS+1}' + else: + return f'{r.CHROM}-{r.POS}' + sites = vf.df.apply(one_row, axis=1).to_list() + elif '.bed' in args.sites: + bf = api.pybed.BedFrame.from_file(args.sites) + sites = bf.gr.df.apply(lambda r: f'{r.Chromosome}-{r.Start}', axis=1).to_list() + else: + with open(args.sites) as f: + sites = [] + for line in f: + fields = line.strip().split('\t') + sites.append(fields[0] + '-' + fields[1]) + df = api.pybam.count_allelic_depth(args.bam, sites) + sys.stdout.write(df.to_csv(sep='\t', index=False)) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/maf_sumplt.py",".py","1876","82","from .. import api + +import matplotlib.pyplot as plt + +description = """""" +Create a summary plot with a MAF file. + +The format of output image (PDF/PNG/JPEG/SVG) will be automatically +determined by the output file's extension. +"""""" + +epilog = f"""""" +[Example] Output a PNG file: + $ fuc {api.common._script_name()} in.maf out.png + +[Example] Output a PNG file: + $ fuc {api.common._script_name()} in.maf out.pdf +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + epilog=epilog, + help= +""""""Create a summary plot with a MAF file."""""" + ) + parser.add_argument( + 'maf', + help= +""""""Input MAF file."""""" + ) + parser.add_argument( + 'out', + help= +""""""Output image file."""""" + ) + parser.add_argument( + '--figsize', + metavar='FLOAT', + type=float, + default=[15, 10], + nargs=2, + help= +""""""Width, height in inches (default: [15, 10])."""""" + ) + parser.add_argument( + '--title_fontsize', + metavar='FLOAT', + type=float, + default=16, + help= +""""""Font size of subplot titles (default: 16)."""""" + ) + parser.add_argument( + '--ticklabels_fontsize', + metavar='FLOAT', + type=float, + default=12, + help= +""""""Font size of tick labels (default: 12)."""""" + ) + parser.add_argument( + '--legend_fontsize', + metavar='FLOAT', + type=float, + default=12, + help= +""""""Font size of legend texts (default: 12)."""""" + ) + +def main(args): + mf = api.pymaf.MafFrame.from_file(args.maf) + mf.plot_summary( + figsize=args.figsize, + title_fontsize=args.title_fontsize, + ticklabels_fontsize=args.ticklabels_fontsize, + legend_fontsize=args.legend_fontsize + ) + plt.savefig(args.out) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/cli/fuc_demux.py",".py","3629","121","import os +from pathlib import Path + +from .. import api + +import pandas as pd +import seaborn as sns +import matplotlib.pyplot as plt + +description = """""" +Parse the Reports directory from bcl2fastq. + +This command will parse, and extract various statistics from, HTML files in +the Reports directory created by the bcl2fastq or bcl2fastq2 prograrm. After +creating an output directory, the command will write the following files: + - flowcell-summary.csv + - lane-summary.csv + - top-unknown-barcodes.csv + - reports.pdf + +Use --sheet to sort samples in the lane-summary.csv file in the same order +as your SampleSheet.csv file. You can also provide a modified version of your +SampleSheet.csv file to subset samples for the lane-summary.csv and +reports.pdf files. +"""""" + +epilog = f"""""" +[Example] Parse a Reports directory: + $ fuc {api.common._script_name()} Reports output + +[Example] Sort and/or subset samples: + $ fuc {api.common._script_name()} Reports output --sheet SampleSheet.csv +"""""" + +def create_parser(subparsers): + parser = api.common._add_parser( + subparsers, + api.common._script_name(), + description=description, + help= +""""""Parse the Reports directory from bcl2fastq."""""" + ) + parser.add_argument( + 'reports', + help= +""""""Input Reports directory."""""" + ) + parser.add_argument( + 'output', + help= +""""""Output directory (will be created)."""""" + ) + parser.add_argument( + '--sheet', + metavar='PATH', + help= +""""""SampleSheet.csv file. Used for sorting and/or subsetting +samples."""""" + ) + +def main(args): + for path in Path(args.reports).rglob('all/all/all/laneBarcode.html'): + html_file = path.absolute() + + dfs = pd.read_html(html_file) + + d = { + '% of thelane': '% of the lane', + '% Perfectbarcode': '% Perfect barcode', + '% One mismatchbarcode': '% One mismatch barcode', + '% PFClusters': '% PF Clusters', + '% >= Q30bases': '% >= Q30 bases', + 'Mean QualityScore': 'Mean Quality Score', + } + + df1 = dfs[1] + df2 = dfs[2].rename(columns=d) + df2.Sample = df2.Sample.astype(str) + df3 = dfs[3].dropna() + + if args.sheet is None: + df4 = pd.DataFrame() + else: + with open(args.sheet) as f: + for i, line in enumerate(f): + if line.startswith('[Data]'): + n = i + 1 + df4 = pd.read_csv(args.sheet, skiprows=n) + df4.Sample_Name = df4.Sample_Name.astype(str) + sample_order = df4.Sample_Name.to_list() + ['Undetermined'] + df2.index = df2.Sample + df2 = df2.loc[sample_order] + df2 = df2.reset_index(drop=True) + + fig, axes = plt.subplots(3, 2, figsize=(14, 17)) + + kwargs = dict(data=df2[:-1], kde=True) + + sns.histplot(ax=axes[0][0], x='PF Clusters', **kwargs) + sns.histplot(ax=axes[0][1], x='% of the lane', **kwargs) + sns.histplot(ax=axes[1][0], x='Yield (Mbases)', **kwargs) + sns.histplot(ax=axes[1][1], x='% PF Clusters', **kwargs) + sns.histplot(ax=axes[2][0], x='% >= Q30 bases', **kwargs) + sns.histplot(ax=axes[2][1], x='Mean Quality Score', **kwargs) + + os.mkdir(args.output) + + plt.tight_layout() + plt.savefig(f'{args.output}/reports.pdf') + + df1_string = df1.to_csv(index=False) + df2_string = df2.to_csv(index=False, na_rep='NaN') + df3_string = df3.to_csv(index=False) + + with open(f'{args.output}/flowcell-summary.csv', 'w') as f: + f.write(df1_string) + with open(f'{args.output}/lane-summary.csv', 'w') as f: + f.write(df2_string) + with open(f'{args.output}/top-unknown-barcodes.csv', 'w') as f: + f.write(df3_string) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/api/pybam.py",".py","7687","271",""""""" +The pybam submodule is designed for working with sequence alignment files +(SAM/BAM/CRAM). It essentially wraps the `pysam +`_ package to allow fast +computation and easy manipulation. If you are mainly interested in working +with depth of coverage data, please check out the pycov submodule which is +specifically designed for the task. +"""""" + +import sys + +from . import common, pybed + +import pysam +import pandas as pd + +def slice(bam, regions, format='BAM', path=None, fasta=None): + """""" + Slice a BAM file for specified regions. + + Parameters + ---------- + bam : str + Input BAM file. It must be already indexed to allow random access. + You can index a BAM file with the :meth:`pybam.index` method. + regions : str, list, or pybed.BedFrame + One or more regions to be sliced. Each region must have the format + chrom:start-end and be a half-open interval with (start, end]. This + means, for example, chr1:100-103 will extract positions 101, 102, and + 103. Alternatively, you can provide a BED file (compressed or + uncompressed) to specify regions. Note that the 'chr' prefix in + contig names (e.g. 'chr1' vs. '1') will be automatically added or + removed as necessary to match the input BED's contig names. + path : str, optional + Output BAM file. Writes to stdout when ``path='-'``. If None is + provided the result is returned as a string. + format : {'BAM', 'SAM', 'CRAM'}, default: 'BAM' + Output file format. + fasta + FASTA file. Required when ``format`` is 'CRAM'. + + Returns + ------- + None or str + If ``path`` is None, returns the resulting BAM format as a string. + Otherwise returns None. + """""" + formats = ['BAM', 'SAM', 'CRAM'] + + if format not in formats: + raise ValueError( + f""Output format must be BAM, SAM, or CRAM, not {format}"" + ) + + options = ['-h', '--no-PG'] + + # Determine the output format. + if format == 'BAM': + options += ['-b'] + elif format == 'CRAM': + if fasta is None: + raise ValueError( + ""A FASTA file must be specified with '--fasta' "" + ""when '--format' is 'CRAM'."" + ) + options += ['-C', '-T', fasta] + else: + pass + + # Parse the regions. + if isinstance(regions, pybed.BedFrame): + regions = regions.to_regions() + elif isinstance(regions, list): + if '.bed' in regions[0]: + regions = pybed.BedFrame.from_file(regions[0]).to_regions() + else: + regions = common.sort_regions(regions) + else: + raise TypeError('Incorrect regions type') + + # Handle the 'chr' prefix. + if has_chr_prefix(bam): + regions = common.update_chr_prefix(regions, mode='add') + else: + regions = common.update_chr_prefix(regions, mode='remove') + + if path is None: + data = pysam.view(bam, *regions, *options) + else: + data = None + if path == '-': + pysam.view(bam, *regions, *options, catch_stdout=False) + else: + pysam.view(bam, *regions, *options, '-o', path, catch_stdout=False) + + return data + +def index(fn): + """""" + Index a BAM file. + + This simply wraps the :meth:`pysam.index` method. + + Parameters + ---------- + fn : str + BAM file. + """""" + pysam.index(fn) + +def tag_sm(fn): + """""" + Extract SM tags (sample names) from a BAM file. + + Parameters + ---------- + fn : str + BAM file. + + Returns + ------- + list + List of SM tags. + + Examples + -------- + + >>> from fuc import pybam + >>> pybam.tag_sm('NA19920.bam') + ['NA19920'] + """""" + lines = pysam.view('-H', fn, '--no-PG').strip().split('\n') + tags = [] + for line in lines: + fields = line.split('\t') + if fields[0] == '@RG': + for field in fields: + if 'SM:' in field: + tags.append(field.replace('SM:', '')) + return list(set(tags)) + +def tag_sn(fn): + """""" + Extract SN tags (contig names) from a BAM file. + + Parameters + ---------- + fn : str + BAM file. + + Returns + ------- + list + List of SN tags. + + Examples + -------- + + >>> from fuc import pybam + >>> pybam.tag_sn('NA19920.bam') + ['chr3', 'chr15', 'chrY', 'chr19', 'chr22', 'chr5', 'chr18', 'chr14', 'chr11', 'chr20', 'chr21', 'chr16', 'chr10', 'chr13', 'chr9', 'chr2', 'chr17', 'chr12', 'chr6', 'chrM', 'chrX', 'chr4', 'chr8', 'chr1', 'chr7'] + """""" + lines = pysam.view('-H', fn, '--no-PG').strip().split('\n') + tags = [] + for line in lines: + fields = line.split('\t') + if fields[0] == '@SQ': + for field in fields: + if 'SN:' in field: + tags.append(field.replace('SN:', '')) + return list(set(tags)) + +def has_chr_prefix(fn): + """""" + Return True if contigs have the (annoying) 'chr' string. + + Parameters + ---------- + fn : str + BAM file. + + Returns + ------- + bool + Whether the 'chr' string is found. + """""" + contigs = tag_sn(fn) + for contig in contigs: + if 'chr' in contig: + return True + return False + +def count_allelic_depth(bam, sites): + """""" + Count allelic depth for specified sites. + + Parameters + ---------- + bam : str + BAM file. + sites : str or list + Genomic site or list of sites. Each site should consist of chromosome + and 1-based position in the format that can be recognized by + :meth:`common.parse_variant` (e.g. '22-42127941'). + + Returns + ------- + pandas.DataFrame + DataFrame containing allelic depth. + + Examples + -------- + + >>> from fuc import pybam + >>> pybam.count_allelic_depth('in.bam', ['19-41510048', '19-41510053', '19-41510062']) + Chromosome Position Total A C G T N DEL INS + 0 19 41510048 119 106 7 4 0 0 2 0 + 1 19 41510053 120 1 2 0 116 0 0 1 + 2 19 41510062 115 0 0 115 0 0 0 0 + """""" + if isinstance(sites, str): + sites = [sites] + + has_prefix = has_chr_prefix(bam) + + f = pysam.AlignmentFile(bam, 'rb') + + rows = [] + + for site in sites: + chrom, pos, _, _ = common.parse_variant(site) + + if has_prefix: + if 'chr' not in chrom: + formatted_chrom = 'chr' + chrom + else: + formatted_chrom = chrom + else: + if 'chr' in chrom: + formatted_chrom = chrom.replace('chr', '') + else: + formatted_chrom = chrom + row = {'A': 0, 'C': 0, 'G': 0, 'T': 0, 'N': 0 , 'DEL': 0, 'INS': 0} + kwargs = dict( + min_base_quality=0, + ignore_overlaps=False, + ignore_orphans=False, + truncate=True + ) + for i, col in enumerate(f.pileup(formatted_chrom, pos-2, pos, **kwargs)): + for read in col.pileups: + if i == 0: + if read.indel < 0: + row['DEL'] += 1 + elif read.indel > 0: + row['INS'] += 1 + else: + continue + else: + if read.is_del: + continue + allele = read.alignment.query_sequence[read.query_position] + row[allele] += 1 + + data = list(row.values()) + rows.append([chrom, pos, sum(data)] + data) + + f.close() + + return pd.DataFrame(rows, columns=['Chromosome', 'Position', 'Total']+list(row)) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/api/pymaf.py",".py","139474","3942",""""""" +The pymaf submodule is designed for working with MAF files. It implements +``pymaf.MafFrame`` which stores MAF data as ``pandas.DataFrame`` to allow +fast computation and easy manipulation. The ``pymaf.MafFrame`` class also +contains many useful plotting methods such as ``MafFrame.plot_oncoplot`` and +``MafFrame.plot_summary``. The submodule strictly adheres to the +standard `MAF specification +`_. + +A typical MAF file contains many columns ranging from gene symbol to +protein change. However, most of the analysis in pymaf uses the +following columns: + ++-----+------------------------+----------------------+-------------------------------+ +| No. | Name | Description | Examples | ++=====+========================+======================+===============================+ +| 1 | Hugo_Symbol | HUGO gene symbol | 'TP53', 'Unknown' | ++-----+------------------------+----------------------+-------------------------------+ +| 2 | Chromosome | Chromosome name | 'chr1', '1', 'X' | ++-----+------------------------+----------------------+-------------------------------+ +| 3 | Start_Position | Start coordinate | 119031351 | ++-----+------------------------+----------------------+-------------------------------+ +| 4 | End_Position | End coordinate | 44079555 | ++-----+------------------------+----------------------+-------------------------------+ +| 5 | Variant_Classification | Translational effect | 'Missense_Mutation', 'Silent' | ++-----+------------------------+----------------------+-------------------------------+ +| 6 | Variant_Type | Mutation type | 'SNP', 'INS', 'DEL' | ++-----+------------------------+----------------------+-------------------------------+ +| 7 | Reference_Allele | Reference allele | 'T', '-', 'ACAA' | ++-----+------------------------+----------------------+-------------------------------+ +| 8 | Tumor_Seq_Allele1 | First tumor allele | 'A', '-', 'TCA' | ++-----+------------------------+----------------------+-------------------------------+ +| 9 | Tumor_Seq_Allele2 | Second tumor allele | 'A', '-', 'TCA' | ++-----+------------------------+----------------------+-------------------------------+ +| 10 | Tumor_Sample_Barcode | Sample ID | 'TCGA-AB-3002' | ++-----+------------------------+----------------------+-------------------------------+ +| 11 | Protein_Change | Protein change | 'p.L558Q' | ++-----+------------------------+----------------------+-------------------------------+ + +It is also recommended to include additional custom columns such as variant +allele frequecy (VAF) and transcript name. + +If sample annotation data are available for a given MAF file, use +the :class:`common.AnnFrame` class to import the data. + +There are nine nonsynonymous variant classifcations that pymaf primarily +uses: Missense_Mutation, Frame_Shift_Del, Frame_Shift_Ins, In_Frame_Del, +In_Frame_Ins, Nonsense_Mutation, Nonstop_Mutation, Splice_Site, and +Translation_Start_Site. +"""""" + +import re +import copy +import warnings +import itertools + +from . import pyvcf, common + +import numpy as np +import pandas as pd +import statsmodels.formula.api as smf +from matplotlib_venn import venn2, venn3 +from scipy.stats import fisher_exact +import seaborn as sns +import matplotlib.pyplot as plt +import matplotlib.patches as mpatches +import matplotlib.gridspec as gridspec + + +CHROM_LENGTHS = { + 'hg18': [ + 247249719, 242951149, 199501827, 191273063, 180857866, 170899992, + 158821424, 146274826, 140273252, 135374737, 134452384, 132349534, + 114142980, 106368585, 100338915, 88827254, 78774742, 76117153, + 63811651, 62435964, 46944323, 49691432, 154913754, 57772954 + ], + 'hg19': [ + 249250621, 243199373, 198022430, 191154276, 180915260, 171115067, + 159138663, 146364022, 141213431, 135534747, 135006516, 133851895, + 115169878, 107349540, 102531392, 90354753, 81195210, 78077248, + 59128983, 63025520, 48129895, 51304566, 155270560, 59373566 + ], + 'hg38': [ + 248956422, 242193529, 198295559, 190214555, 181538259, 170805979, + 159345973, 145138636, 138394717, 133797422, 135086622, 133275309, + 114364328, 107043718, 101991189, 90338345, 83257441, 80373285, + 58617616, 64444167, 46709983, 50818468, 156040895, 57227415 + ], +} + +COMMON_COLUMNS = [ + 'Hugo_Symbol', 'Entrez_Gene_Id', 'Center', 'NCBI_Build', 'Chromosome', + 'Start_Position', 'End_Position', 'Strand', 'Variant_Classification', + 'Variant_Type', 'Reference_Allele', 'Tumor_Seq_Allele1', + 'Tumor_Seq_Allele2', 'Tumor_Sample_Barcode', 'Protein_Change' +] + +# Below is the list of calculated variant consequences from Ensembl VEP: +# https://m.ensembl.org/info/genome/variation/prediction/predicted_data.html +# (accessed on 2023-09-03) +# +# Note that both frameshift_variant and protein_altering_variant require +# additional information to find their correct Variant_Classification. + +VEP_CONSEQUENCES = { + 'transcript_ablation': 'Splice_Site', + 'splice_acceptor_variant': 'Splice_Site', + 'splice_donor_variant': 'Splice_Site', + 'stop_gained': 'Nonsense_Mutation', + 'frameshift_variant': 'AMBIGUOUS', + 'stop_lost': 'Nonstop_Mutation', + 'start_lost': 'Translation_Start_Site', + 'transcript_amplification': 'Intron', + 'inframe_insertion': 'In_Frame_Ins', + 'inframe_deletion': 'In_Frame_Del', + 'missense_variant': 'Missense_Mutation', + 'protein_altering_variant': 'AMBIGUOUS', + 'splice_region_variant': 'Splice_Region', + 'incomplete_terminal_codon_variant': 'Silent', + 'start_retained_variant': 'Silent', + 'stop_retained_variant': 'Silent', + 'synonymous_variant': 'Silent', + 'coding_sequence_variant': 'Missense_Mutation', + 'mature_miRNA_variant': 'RNA', + '5_prime_UTR_variant': ""5'UTR"", + '3_prime_UTR_variant': ""3'UTR"", + 'non_coding_transcript_exon_variant': 'RNA', + 'intron_variant': 'Intron', + 'NMD_transcript_variant': 'Silent', + 'non_coding_transcript_variant': 'RNA', + 'upstream_gene_variant': ""5'Flank"", + 'downstream_gene_variant': ""3'Flank"", + 'TFBS_ablation': 'Targeted_Region', + 'TFBS_amplification': 'Targeted_Region', + 'TF_binding_site_variant': 'IGR', + 'regulatory_region_ablation': 'Targeted_Region', + 'regulatory_region_amplification': 'Targeted_Region', + 'feature_elongation': 'Targeted_Region', + 'regulatory_region_variant': 'IGR', + 'feature_truncation': 'Targeted_Region', + 'intergenic_variant': 'IGR', + 'splice_donor_5th_base_variant': 'AMBIGUOUS', + 'splice_donor_region_variant': 'AMBIGUOUS', + 'splice_polypyrimidine_tract_variant': 'AMBIGUOUS', + 'coding_transcript_variant': 'AMBIGUOUS', + 'sequence_variant': 'AMBIGUOUS', +} + +VARCLS_LIST = [ + ""3'Flank"", + ""3'UTR"", + ""5'Flank"", + ""5'UTR"", + 'De_novo_Start_InFrame', + 'De_novo_Start_OutOfFrame', + 'Frame_Shift_Del', + 'Frame_Shift_Ins', + 'IGR', + 'In_Frame_Del', + 'In_Frame_Ins', + 'Intron', + 'Missense_Mutation', + 'Nonsense_Mutation', + 'Nonstop_Mutation', + 'RNA', + 'Silent', + 'Splice_Region', + 'Splice_Site', + 'Start_Codon_Ins', + 'Start_Codon_SNP', + 'Stop_Codon_Del', + 'Targeted_Region', + 'Translation_Start_Site', + 'lincRNA', +] + +NONSYN_NAMES = [ + 'Missense_Mutation', 'Frame_Shift_Del', 'Frame_Shift_Ins', + 'In_Frame_Del', 'In_Frame_Ins', 'Nonsense_Mutation', + 'Nonstop_Mutation', 'Splice_Site', 'Translation_Start_Site' +] + +NONSYN_COLORS = [ + 'tab:green', 'tab:blue', 'tab:purple', 'tab:olive', 'tab:red', + 'tab:cyan', 'tab:pink', 'tab:orange', 'tab:brown' +] + +SNV_CLASSES = { + 'A>C': {'class': 'T>G', 'type': 'Tv'}, + 'A>G': {'class': 'T>C', 'type': 'Ti'}, + 'A>T': {'class': 'T>A', 'type': 'Tv'}, + 'C>A': {'class': 'C>A', 'type': 'Tv'}, + 'C>G': {'class': 'C>G', 'type': 'Tv'}, + 'C>T': {'class': 'C>T', 'type': 'Ti'}, + 'G>A': {'class': 'C>T', 'type': 'Ti'}, + 'G>C': {'class': 'C>G', 'type': 'Tv'}, + 'G>T': {'class': 'C>A', 'type': 'Tv'}, + 'T>A': {'class': 'T>A', 'type': 'Tv'}, + 'T>C': {'class': 'T>C', 'type': 'Ti'}, + 'T>G': {'class': 'T>G', 'type': 'Tv'}, +} + +SNV_CLASS_ORDER = ['C>A', 'C>G', 'C>T', 'T>A', 'T>C', 'T>G'] + +class MafFrame: + """""" + Class for storing MAF data. + + Parameters + ---------- + df : pandas.DataFrame + DataFrame containing MAF data. + + See Also + -------- + MafFrame.from_file + Construct MafFrame from a MAF file. + """""" + def __init__(self, df): + self.df = df.reset_index(drop=True) + + @property + def shape(self): + """"""tuple : Dimensionality of MafFrame (variants, samples)."""""" + return (self.df.shape[0], len(self.samples)) + + @property + def samples(self): + """"""list : List of the sample names."""""" + return list(self.df.Tumor_Sample_Barcode.unique()) + + @property + def genes(self): + """"""list : List of the genes."""""" + return list(self.df.Hugo_Symbol.unique()) + + def copy(self): + """"""Return a copy of the MafFrame."""""" + return self.__class__(self.df.copy()) + + def compute_clonality(self, vaf_col, threshold=0.25): + """""" + Compute the clonality of variants based on + :ref:`VAF `. + + A mutation will be defined as ""Subclonal"" if the VAF is less than the + threshold percentage (e.g. 25%) of the highest VAF in the sample and + is defined as ""Clonal"" if it is equal to or above this threshold. + + Parameters + ---------- + vaf_col : str + MafFrame column containing VAF data. + threshold : float + Minimum VAF to be considered as ""Clonal"". + + Returns + ------- + panda.Series + Clonality for each variant. + + Examples + -------- + + >>> import matplotlib.pyplot as plt + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> mf.df['Clonality'] = mf.compute_clonality('i_TumorVAF_WU') + >>> mf.df['Clonality'][:10] + 0 Clonal + 1 Clonal + 2 Clonal + 3 Clonal + 4 Clonal + 5 Clonal + 6 Clonal + 7 Clonal + 8 Clonal + 9 Clonal + Name: Clonality, dtype: object + """""" + d = self.df.groupby('Tumor_Sample_Barcode')[vaf_col].max().to_dict() + def one_row(r): + m = d[r.Tumor_Sample_Barcode] + if r[vaf_col] < m * threshold: + result = 'Subclonal' + else: + result = 'Clonal' + return result + s = self.df.copy().apply(one_row, axis=1) + return s + + @classmethod + def from_file(cls, fn): + """""" + Construct MafFrame from a MAF file. + + Parameters + ---------- + fn : str + MAF file (compressed or uncompressed). + + Returns + ------- + MafFrame + MafFrame object. + + See Also + -------- + MafFrame + MafFrame object creation using constructor. + + Examples + -------- + + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> mf = pymaf.MafFrame.from_file(maf_file) + """""" + # Read the input MAF file. + df = pd.read_table(fn) + + # Check the letter case of column names. This will help distinguish + # missing columns from columns with incorrect letter case (e.g. + # 'End_Position' vs. 'End_position'). + lower_names = [x.lower() for x in COMMON_COLUMNS] + for col in df.columns: + if col.lower() in lower_names: + i = lower_names.index(col.lower()) + if col != COMMON_COLUMNS[i]: + message = ( + f""Input column '{col}' will be renamed "" + f""as '{COMMON_COLUMNS[i]}'."" + ) + warnings.warn(message) + df = df.rename(columns={col: COMMON_COLUMNS[i]}) + + # Set the data type of chromosomes as string (e.g. 'chr1' vs. '1'). + if 'Chromosome' in df.columns: + df.Chromosome = df.Chromosome.astype(str) + + return cls(df) + + @classmethod + def from_vcf(cls, vcf, keys=None, names=None): + """""" + Construct MafFrame from a VCF file or VcfFrame. + + It is recommended that the input VCF data be functionally annotated + by an annotation tool such as Ensembl VEP, SnpEff, and ANNOVAR; + however, the method can handle unannotated VCF data as well. + + The preferred tool for functional annotation is Ensembl VEP with + ""RefSeq transcripts"" as the transcript database and the filtering + option ""Show one selected consequence per variant"". + + Parameters + ---------- + vcf : str or VcfFrame + VCF file or VcfFrame. + keys : str or list + Genotype key (e.g. 'AD', 'AF') or list of genotype keys to be + added to the MafFrame. + names : str or list + Column name or list of column names for ``keys`` (must be the + same length). By default, the genotype keys will be used as + column names. + + Examples + -------- + Below is a simple example: + + >>> from fuc import pyvcf, pymaf + >>> data = { + ... 'CHROM': ['chr1', 'chr2'], + ... 'POS': [100, 101], + ... 'ID': ['.', '.'], + ... 'REF': ['G', 'T'], + ... 'ALT': ['A', 'C'], + ... 'QUAL': ['.', '.'], + ... 'FILTER': ['.', '.'], + ... 'INFO': ['CSQ=T|missense_variant|MODERATE|MTOR|2475|Transcript|NM_001386500.1|protein_coding|47/58||||6792|6644|2215|S/Y|tCt/tAt|rs587777894&COSV63868278&COSV63868313||-1||EntrezGene||||||||G|G||deleterious(0)|possibly_damaging(0.876)||||||||||||||||||likely_pathogenic&pathogenic|0&1&1|1&1&1|26619011&27159400&24631838&26018084&27830187|||||', 'CSQ=C|splice_donor_variant|HIGH|MTOR|2475|Transcript|NM_001386500.1|protein_coding||46/57||||||||||-1||EntrezGene||||||||A|A|||||||||||||||||||||||||||||'], + ... 'FORMAT': ['GT:AD:DP:AF', 'GT:AD:DP:AF'], + ... 'A': ['0/1:176,37:213:0.174', '0/1:966,98:1064:0.092'] + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A + 0 chr1 100 . G A . . CSQ=T|missense_variant|MODERATE|MTOR|2475|Tran... GT:AD:DP:AF 0/1:176,37:213:0.174 + 1 chr2 101 . T C . . CSQ=C|splice_donor_variant|HIGH|MTOR|2475|Tran... GT:AD:DP:AF 0/1:966,98:1064:0.092 + >>> mf = pymaf.MafFrame.from_vcf(vf) + >>> mf.df + Hugo_Symbol Entrez_Gene_Id Center NCBI_Build Chromosome Start_Position End_Position Strand Variant_Classification Variant_Type Reference_Allele Tumor_Seq_Allele1 Tumor_Seq_Allele2 Protein_Change Tumor_Sample_Barcode + 0 MTOR 2475 . . chr1 100 100 - Missense_Mutation SNP G A A p.S2215Y A + 1 MTOR 2475 . . chr2 101 101 - Splice_Site SNP T C C . A + + We can add genotype keys such as AD and AF: + + >>> mf = pymaf.MafFrame.from_vcf(vf, keys=['AD', 'AF']) + >>> mf.df + Hugo_Symbol Entrez_Gene_Id Center NCBI_Build Chromosome Start_Position End_Position Strand Variant_Classification Variant_Type Reference_Allele Tumor_Seq_Allele1 Tumor_Seq_Allele2 Protein_Change Tumor_Sample_Barcode AD AF + 0 MTOR 2475 . . chr1 100 100 - Missense_Mutation SNP G A A p.S2215Y A 176,37 0.174 + 1 MTOR 2475 . . chr2 101 101 - Splice_Site SNP T C C . A 966,98 0.092 + + The method can accept a VCF file as input instead of VcfFrame: + + >>> mf = pymaf.MafFrame.from_vcf('annotated.vcf') + + The method can also handle unannotated VCF data: + + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1'], + ... 'POS': [100, 200, 300], + ... 'ID': ['.', '.', '.'], + ... 'REF': ['G', 'C', 'TTC'], + ... 'ALT': ['A', 'CAG', 'T'], + ... 'QUAL': ['.', '.', '.'], + ... 'FILTER': ['.', '.', '.'], + ... 'INFO': ['.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT'], + ... 'A': ['0/1', '0/1', '0/1'] + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A + 0 chr1 100 . G A . . . GT 0/1 + 1 chr1 200 . C CAG . . . GT 0/1 + 2 chr1 300 . TTC T . . . GT 0/1 + >>> mf = pymaf.MafFrame.from_vcf(vf) + >>> mf.df + Hugo_Symbol Entrez_Gene_Id Center NCBI_Build Chromosome Start_Position End_Position Strand Variant_Classification Variant_Type Reference_Allele Tumor_Seq_Allele1 Tumor_Seq_Allele2 Protein_Change Tumor_Sample_Barcode + 0 . . . . chr1 100 100 . . SNP G A A . A + 1 . . . . chr1 200 201 . . INS - AG AG . A + 2 . . . . chr1 301 302 . . DEL TC - - . A + """""" + # Parse the input VCF. + if isinstance(vcf, str): + vf = pyvcf.VcfFrame.from_file(vcf) + else: + vf = vcf + + # Set some default values in case the VCF is not annotated. + ncbi_build = '.' + + # Get the NCBI_Build data. + for line in vf.meta: + if line.startswith('##VEP'): + ncbi_build = re.search(r'assembly=""(.*?)""', line).group(1) + break + + # Define the conversion algorithm. + def one_row(r): + has_annot = 'CSQ=' in r.INFO + + # Set some default values in case the VCF is not annotated. + strand = '.' + variant_classification = '.' + protein_change = '.' + hugo_symbol = '.' + entrez_gene_id = '.' + + # Get the sequence data. + inframe = abs(len(r.REF) - len(r.ALT)) / 3 == 0 + if len(r.REF) == len(r.ALT) == 1: + variant_type = 'SNP' + start_position = r.POS + end_position = r.POS + reference_allele = r.REF + tumor_seq_allele1 = r.ALT + tumor_seq_allele2 = r.ALT + elif len(r.REF) > len(r.ALT): + variant_type = 'DEL' + start_position = r.POS + 1 + end_position = r.POS + len(r.REF) - len(r.ALT) + reference_allele = r.REF[1:] + tumor_seq_allele1 = '-' + tumor_seq_allele2 = '-' + else: + variant_type = 'INS' + start_position = r.POS + end_position = r.POS + 1 + reference_allele = '-' + tumor_seq_allele1 = r.ALT[1:] + tumor_seq_allele2 = r.ALT[1:] + + # Extract annotation fields. + if has_annot: + csq = [x for x in r.INFO.split(';') if x.startswith('CSQ=')][0] + fields = csq.replace('CSQ=', '').split('|') + + # Get the Strand data. + if has_annot: + strand = '+' if fields[19] == '1' else '-' + + # Get the Variant_Classification data. + if has_annot: + consequence = fields[1].split('&')[0] + if consequence == 'frameshift_variant': + if variant_type == 'DEL': + variant_classification = 'Frame_Shift_Del' + else: + variant_classification = 'Frame_Shift_Ins' + elif consequence == 'protein_altering_variant': + if inframe: + if variant_type == 'DEL': + variant_classification = 'In_Frame_Del' + else: + variant_classification = 'In_Frame_Ins' + else: + if variant_type == 'DEL': + variant_classification = 'Frame_Shift_Del' + else: + variant_classification = 'Frame_Shift_Ins' + elif consequence in VEP_CONSEQUENCES: + variant_classification = VEP_CONSEQUENCES[consequence] + else: + m = f'Found unknown Ensembl VEP consequence: {consequence}' + raise ValueError(m) + + # Get the Tumor_Sample_Barcode data. + s = r[9:].apply(pyvcf.gt_hasvar) + tumor_sample_barcode = ','.join(s[s].index.to_list()) + + # Get the Protein_Change data. + if has_annot: + pos = fields[14] + aa = fields[15].split('/') + if len(aa) > 1: + protein_change = f'p.{aa[0]}{pos}{aa[1]}' + + # Get other data. + if has_annot: + hugo_symbol = fields[3] + entrez_gene_id = fields[4] + + d = dict( + Hugo_Symbol = hugo_symbol, + Entrez_Gene_Id = entrez_gene_id, + Center = '.', + NCBI_Build = ncbi_build, + Chromosome = r.CHROM, + Start_Position = start_position, + End_Position = end_position, + Strand = strand, + Variant_Classification = variant_classification, + Variant_Type = variant_type, + Reference_Allele = reference_allele, + Tumor_Seq_Allele1 = tumor_seq_allele1, + Tumor_Seq_Allele2 = tumor_seq_allele2, + Tumor_Sample_Barcode = tumor_sample_barcode, + Protein_Change = protein_change, + CHROM = r.CHROM, # will be dropped + POS = r.POS, # will be dropped + REF = r.REF, # will be dropped + ALT = r.ALT, # will be dropped + ) + + return pd.Series(d) + + # Apply the conversion algorithm. + df = vf.df.apply(one_row, axis=1) + + # Expand the Tumor_Sample_Barcode column to multiple rows. + s = df['Tumor_Sample_Barcode'].str.split(',').apply( + pd.Series, 1).stack() + s.index = s.index.droplevel(-1) + s.name = 'Tumor_Sample_Barcode' + del df['Tumor_Sample_Barcode'] + df = df.join(s) + + # Append extra genotype keys, if necessary. + if keys is not None: + if names is None: + names = keys + if isinstance(keys, str): + keys = [keys] + if isinstance(names, str): + names = [names] + for i, key in enumerate(keys): + temp_df = vf.extract_format(key) + temp_df = pd.concat([vf.df.iloc[:, :9], temp_df], axis=1) + temp_df = temp_df.drop( + columns=['ID', 'QUAL', 'FILTER', 'INFO', 'FORMAT']) + temp_df = pd.melt( + temp_df, + id_vars=['CHROM', 'POS', 'REF', 'ALT'], + var_name='Tumor_Sample_Barcode', + ) + temp_df = temp_df[temp_df.value != '.'] + df = df.merge(temp_df, + on=['CHROM', 'POS', 'REF', 'ALT', 'Tumor_Sample_Barcode']) + df = df.rename(columns={'value': names[i]}) + + # Drop the extra columns. + df = df.drop(columns=['CHROM', 'POS', 'REF', 'ALT']) + + return cls(df) + + def matrix_prevalence(self): + """""" + Compute a matrix of variant counts with a shape of (genes, samples). + + Returns + ------- + pandas.DataFrame + The said matrix. + """""" + s = self.df.groupby( + 'Hugo_Symbol')['Tumor_Sample_Barcode'].value_counts() + s.name = 'Count' + df = s.to_frame().reset_index() + df = df.pivot(index='Hugo_Symbol', + columns='Tumor_Sample_Barcode', values='Count') + df.columns.name = '' + df = df.fillna(0) + return df + + def matrix_genes(self, mode='variants', count=10): + """""" + Compute a matrix of counts with a shape of (genes, variant + classifications). + + This method only considers the nine nonsynonymous variant + classifications. + + Parameters + ---------- + mode : {'variants', 'samples'}, default: 'variants' + Determines how to identify top mutated genes: + + * 'variants': Count the number of observed variants. + * 'samples': Count the number of affected samples. Using this + option will create an additional variant classification called + 'Multi_Hit'. + + count : int, default: 10 + Number of top mutated genes to include. + + Returns + ------- + pandas.DataFrame + The said matrix. + """""" + if mode == 'variants': + df = self.df[self.df.Variant_Classification.isin(NONSYN_NAMES)] + df = df.groupby('Hugo_Symbol')[ + 'Variant_Classification'].value_counts().to_frame() + df.columns = ['Count'] + df = df.reset_index() + df = df.pivot(index='Hugo_Symbol', columns='Variant_Classification', + values='Count') + df = df.fillna(0) + for varcls in NONSYN_NAMES: + if varcls not in df.columns: + df[varcls] = 0 + i = df.sum(axis=1).sort_values(ascending=False).index + df = df.reindex(index=i) + df = df[NONSYN_NAMES] + df = df[:count] + df = df.rename_axis(None, axis=1) + elif mode == 'samples': + df = self.matrix_waterfall(count) + df = df.apply(lambda r: r.value_counts(), axis=1) + for varcls in NONSYN_NAMES + ['Multi_Hit']: + if varcls not in df.columns: + df[varcls] = np.nan + df = df[NONSYN_NAMES + ['Multi_Hit']] + df = df.fillna(0) + else: + raise ValueError(f'Found incorrect mode: {mode}') + return df + + def matrix_tmb(self): + """""" + Compute a matrix of variant counts with a shape of (samples, variant + classifications). + + Returns + ------- + pandas.DataFrame + The said matrix. + """""" + df = self.df[self.df.Variant_Classification.isin(NONSYN_NAMES)] + df = df.groupby('Tumor_Sample_Barcode')[ + 'Variant_Classification'].value_counts().to_frame() + df.columns = ['Count'] + df = df.reset_index() + df = df.pivot(index='Tumor_Sample_Barcode', + columns='Variant_Classification', values='Count') + df = df.fillna(0) + for varcls in NONSYN_NAMES: + if varcls not in df.columns: + df[varcls] = 0 + i = df.sum(axis=1).sort_values(ascending=False).index + df = df.reindex(index=i) + df = df[NONSYN_NAMES] + df = df.rename_axis(None, axis=1) + return df + + def matrix_waterfall(self, count=10, keep_empty=False): + """""" + Compute a matrix of variant classifications with a shape of + (genes, samples). + + If there are multiple variant classifications available for a given + cell, they will be replaced as 'Multi_Hit'. + + Parameters + ---------- + count : int, default: 10 + Number of top mutated genes to include. + keep_empty : bool, default: False + If True, keep samples with all ``NaN``'s. + + Returns + ------- + pandas.DataFrame + The said matrix. + """""" + df = self.df[self.df.Variant_Classification.isin(NONSYN_NAMES)] + + f = lambda x: ''.join(x) if len(x) == 1 else 'Multi_Hit' + df = df.groupby(['Hugo_Symbol', 'Tumor_Sample_Barcode'])[ + 'Variant_Classification'].apply(f).to_frame() + df = df.reset_index() + df = df.pivot(index='Hugo_Symbol', columns='Tumor_Sample_Barcode', + values='Variant_Classification') + + # Sort the rows (genes). + i = df.isnull().sum(axis=1).sort_values(ascending=True).index + df = df.reindex(index=i) + + # Select the top mutated genes. + df = df[:count] + + # Drop samples with all NaN's. + if not keep_empty: + df = df.dropna(axis=1, how='all') + + # Sort the columns (samples). + c = df.applymap(lambda x: 0 if pd.isnull(x) else 1).sort_values( + df.index.to_list(), axis=1, ascending=False).columns + df = df[c] + df = df.fillna('None') + df = df.rename_axis(None, axis=1) + + return df + + def plot_genes( + self, mode='variants', count=10, flip=False, ax=None, figsize=None, + **kwargs + ): + """""" + Create a bar plot showing variant distirbution for top mutated genes. + + Parameters + ---------- + mode : {'variants', 'samples'}, default: 'variants' + Determines how to identify top mutated genes: + + * 'variants': Count the number of observed variants. + * 'samples': Count the number of affected samples. Using this + option will create an additional variant classification called + 'Multi_Hit'. + count : int, default: 10 + Number of top mutated genes to display. + flip : bool, default: False + If True, flip the x and y axes. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`pandas.DataFrame.plot.bar` or + :meth:`pandas.DataFrame.plot.barh`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + Examples + -------- + By default (``mode='variants'``), the method identifies top mutated + genes by counting the number of observed variants: + + .. plot:: + :context: close-figs + + >>> import matplotlib.pyplot as plt + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> mf.plot_genes() + >>> plt.tight_layout() + + We can also identify top mutated genes by counting the number of + affected samples: + + .. plot:: + :context: close-figs + + >>> mf.plot_genes(mode='samples') + >>> plt.tight_layout() + """""" + if mode == 'variants': + colors = NONSYN_COLORS + elif mode == 'samples': + colors = NONSYN_COLORS + ['k'] + else: + raise ValueError(f'Found incorrect mode: {mode}') + df = self.matrix_genes(count=count, mode=mode) + df = df.iloc[::-1] + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + if flip: + df = df.iloc[::-1] + kind = 'bar' + xlabel, ylabel = '', 'Count' + else: + kind = 'barh' + xlabel, ylabel = 'Count', '' + + df.plot( + kind=kind, ax=ax, stacked=True, legend=False, + color=colors, **kwargs + ) + + ax.set_xlabel(xlabel) + ax.set_ylabel(ylabel) + + return ax + + def plot_oncoplot( + self, count=10, keep_empty=False, figsize=(15, 10), label_fontsize=15, + ticklabels_fontsize=15, legend_fontsize=15 + ): + """""" + Create an oncoplot. + + See this :ref:`tutorial ` to + learn how to create customized oncoplots. + + Parameters + ---------- + count : int, default: 10 + Number of top mutated genes to display. + keep_empty : bool, default: False + If True, display samples that do not have any mutations. + figsize : tuple, default: (15, 10) + Width, height in inches. Format: (float, float). + label_fontsize : float, default: 15 + Font size of labels. + ticklabels_fontsize : float, default: 15 + Font size of tick labels. + legend_fontsize : float, default: 15 + Font size of legend texts. + + Examples + -------- + + .. plot:: + + >>> import matplotlib.pyplot as plt + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> mf.plot_oncoplot() + """""" + g = {'height_ratios': [1, 10, 1], 'width_ratios': [10, 1]} + fig, axes = plt.subplots(3, 2, figsize=figsize, gridspec_kw=g) + [[ax1, ax2], [ax3, ax4], [ax5, ax6]] = axes + + # Create the TMB plot. + samples = list(self.matrix_waterfall(count=count, + keep_empty=keep_empty).columns) + self.plot_tmb(ax=ax1, samples=samples, width=0.95) + ax1.set_xlabel('') + ax1.spines['right'].set_visible(False) + ax1.spines['top'].set_visible(False) + ax1.spines['bottom'].set_visible(False) + ax1.set_xlim(-0.5, len(samples)-0.5) + ax1.set_ylabel('TMB', fontsize=label_fontsize) + ax1.set_yticks([0, self.matrix_tmb().sum(axis=1).max()]) + ax1.tick_params(axis='y', which='major', + labelsize=ticklabels_fontsize) + + # Remove the top right plot. + ax2.remove() + + # Create the waterfall plot. + self.plot_waterfall(count=count, ax=ax3, linewidths=1, keep_empty=keep_empty) + ax3.set_xlabel('') + ax3.tick_params(axis='y', which='major', labelrotation=0, + labelsize=ticklabels_fontsize) + + # Create the genes plot. + self.plot_genes(count=count, ax=ax4, mode='samples', width=0.95) + ax4.spines['right'].set_visible(False) + ax4.spines['left'].set_visible(False) + ax4.spines['top'].set_visible(False) + ax4.set_yticks([]) + ax4.set_xlabel('Samples', fontsize=label_fontsize) + ax4.set_xticks([0, self.matrix_genes( + count=10, mode='samples').sum(axis=1).max()]) + ax4.set_ylim(-0.5, count-0.5) + ax4.tick_params(axis='x', which='major', + labelsize=ticklabels_fontsize) + + # Create the legend. + handles = common.legend_handles(NONSYN_NAMES+['Multi_Hit'], + colors=NONSYN_COLORS+['k']) + ax5.legend( + handles=handles, + title='Variant_Classification', + loc='upper center', + ncol=4, + fontsize=legend_fontsize, + title_fontsize=legend_fontsize + ) + ax5.axis('off') + + # Remove the bottom right plot. + ax6.remove() + + plt.tight_layout() + plt.subplots_adjust(wspace=0.01, hspace=0.01) + + def plot_oncoplot_matched( + self, af, patient_col, group_col, group_order, colors='Set2', + figsize=(15, 10), label_fontsize=12, ticklabels_fontsize=12, + legend_fontsize=12 + ): + """""" + Create an oncoplot for mached samples. + + Parameters + ---------- + af : AnnFrame + AnnFrame containing sample annotation data. + patient_col : str + AnnFrame column containing patient information. + group_col : str + AnnFrame column containing sample group information. + group_order : list, optional + List of sample group names. + colors : str + Colormap name for the sample groups. + figsize : tuple, default: (15, 10) + Width, height in inches. Format: (float, float). + label_fontsize : float, default: 12 + Font size of labels. + ticklabels_fontsize : float, default: 12 + Font size of tick labels. + legend_fontsize : float, default: 12 + Font size of legend texts. + """""" + fig, axes = plt.subplots(3, 2, figsize=figsize, + gridspec_kw={'height_ratios': [1, 10, 1.5], 'width_ratios': [10, 1]} + ) + + [[ax1, ax2], [ax3, ax4], [ax5, ax6]] = axes + + patients = self.matrix_waterfall_matched(af, patient_col, group_col, group_order).columns + + self.plot_tmb_matched( + af, patient_col, group_col, group_order=group_order, ax=ax1, + legend=False, patients=patients, width=0.90, + color=sns.color_palette(colors)[:3] + ) + ax1.set_xticks([]) + ax1.set_xlim(-0.5, 53-0.5) + ax1.spines['right'].set_visible(False) + ax1.spines['top'].set_visible(False) + ax1.spines['bottom'].set_visible(False) + ax1.set_ylabel('TMB', fontsize=label_fontsize) + ax1.tick_params(axis='y', which='major', + labelsize=ticklabels_fontsize) + + ax2.remove() + + self.plot_waterfall_matched(af, patient_col, group_col, group_order=group_order, ax=ax3) + ax3.set_xticks([]) + ax3.tick_params(axis='y', which='major', labelrotation=0, + labelsize=ticklabels_fontsize) + + self.plot_mutated_matched( + af, patient_col, group_col, group_order=group_order, ax=ax4, palette=colors + ) + ax4.set_yticks([]) + ax4.legend().remove() + ax4.spines['right'].set_visible(False) + ax4.spines['left'].set_visible(False) + ax4.spines['top'].set_visible(False) + ax4.tick_params(axis='x', which='major', + labelsize=ticklabels_fontsize) + ax4.set_xlabel('Patients', fontsize=label_fontsize) + + # Create the legends. + handles1 = common.legend_handles(NONSYN_NAMES+['Multi_Hit'], + colors=NONSYN_COLORS+['k']) + handles2 = common.legend_handles(group_order, colors=colors) + leg1 = ax5.legend(handles=handles1, loc=(0, 0), title='Variant_Classification', ncol=4, fontsize=legend_fontsize, title_fontsize=legend_fontsize) + leg2 = ax5.legend(handles=handles2, loc=(0.8, 0), title=group_col, fontsize=legend_fontsize, title_fontsize=legend_fontsize) + ax5.add_artist(leg1) + ax5.add_artist(leg2) + ax5.axis('off') + + # Remove the bottom right plot. + ax6.remove() + + plt.tight_layout() + plt.subplots_adjust(wspace=0.01, hspace=0.01) + + def plot_clonality( + self, vaf_col, af=None, group_col=None, group_order=None, count=10, + threshold=0.25, subclonal=False, ax=None, figsize=None + ): + """""" + Create a bar plot summarizing the clonality of variants in top + mutated genes. + + Clonality will be calculated based on VAF using + :meth:`MafFrame.compute_clonality`. + + Parameters + ---------- + vaf_col : str + MafFrame column containing VAF data. + af : AnnFrame, optional + AnnFrame containing sample annotation data. + group_col : str, optional + AnnFrame column containing sample group information. + group_order : list, optional + List of sample group names. + count : int, defualt: 10 + Number of top mutated genes to display. + threshold : float, default: 0.25 + VAF threshold percentage. + subclonal : bool, default: False + If True, display subclonality (1 - clonality). + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`seaborn.barplot`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + See Also + -------- + MafFrame.compute_clonality + Compute the clonality of variants based on VAF. + + Examples + -------- + + Below is a simple example: + + .. plot:: + :context: close-figs + + >>> import matplotlib.pyplot as plt + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> mf.plot_clonality('i_TumorVAF_WU') + >>> plt.tight_layout() + + We can create a grouped bar plot based on FAB classification: + + .. plot:: + :context: close-figs + + >>> annot_file = '~/fuc-data/tcga-laml/tcga_laml_annot.tsv' + >>> af = common.AnnFrame.from_file(annot_file, sample_col=0) + >>> mf.plot_clonality('i_TumorVAF_WU', + ... af=af, + ... group_col='FAB_classification', + ... group_order=['M0', 'M1', 'M2']) + >>> plt.tight_layout() + """""" + df = self.df.copy() + df['Clonality'] = self.compute_clonality(vaf_col, threshold=threshold) + + if group_col is None: + s = df.groupby('Hugo_Symbol')['Clonality'].value_counts() + s.name = 'Count' + df = s.to_frame().reset_index() + df = df.pivot(index='Hugo_Symbol', columns='Clonality', values='Count') + else: + df = df.merge(af.df[group_col], left_on='Tumor_Sample_Barcode', right_index=True) + s = df.groupby(['Hugo_Symbol', group_col])['Clonality'].value_counts() + s.name = 'Count' + df = s.to_frame().reset_index() + df = df.pivot(index=['Hugo_Symbol', group_col], columns='Clonality', values='Count') + + df = df.reset_index() + df = df.fillna(0) + l = ['Clonal', 'Subclonal'] + df[l] = df[l].div(df[l].sum(axis=1), axis=0) + genes = self.matrix_genes(count=count).index + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + if subclonal: + y = 'Subclonal' + else: + y = 'Clonal' + + sns.barplot( + x='Hugo_Symbol', y=y, data=df, order=genes, hue=group_col, + hue_order=group_order, ax=ax + ) + + ax.set_xlabel('') + + return ax + + def plot_evolution( + self, samples, vaf_col, anchor=None, normalize=True, count=5, + ax=None, figsize=None, **kwargs + ): + """""" + Create a line plot visualizing changes in VAF between specified + samples. + + Parameters + ---------- + samples : list + List of samples to display. + vaf_col : str + MafFrame column containing VAF data. + anchor : str, optional + Sample to use as the anchor. If absent, use the first sample in + the list. + normalize : bool, default: True + If False, do not normalize VAF by the maximum value. + count : int, default: 5 + Number of top variants to display. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`seaborn.lineplot`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + """""" + df = self.df[self.df.Tumor_Sample_Barcode.isin(samples)] + + if df.empty: + message = f'No variants to display for the samples: {samples}.' + raise ValueError(message) + + df = df[df.Variant_Classification.isin(NONSYN_NAMES)] + + def one_row(r): + if r.Protein_Change == '.': + variant_name = f'{r.Hugo_Symbol} ({r.Variant_Classification})' + else: + variant_name = f'{r.Hugo_Symbol} ({r.Protein_Change})' + return variant_name + + df['Variant_Name'] = df.apply(one_row, axis=1) + df = df.pivot(index=['Variant_Name'], + columns=['Tumor_Sample_Barcode'], values=[vaf_col]) + df.columns = df.columns.get_level_values(1) + df.columns.name = '' + df = df.fillna(0) + + for sample in samples: + if sample not in df.columns: + df[sample] = 0 + + df = df[samples] + + if anchor is None: + anchor = samples[0] + + df = df.sort_values(by=anchor, ascending=False) + if normalize: + df = df / df.max() + df = df.fillna(0) + df = df.iloc[:count, :].T + df = df.loc[samples] + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + sns.lineplot(data=df, ax=ax, **kwargs) + + ax.set_ylabel('Fraction') + + return ax + + def plot_genepair( + self, x, y, vaf_col, af=None, group_col=None, group_order=None, + ax=None, figsize=None, **kwargs + ): + """""" + Create a scatter plot of VAF between Gene X and Gene Y. + + Parameters + ---------- + x, y : str + Gene names. + vaf_col : str + MafFrame column containing VAF data. + af : AnnFrame, optional + AnnFrame containing sample annotation data. + group_col : str, optional + AnnFrame column containing sample group information. + group_order : list, optional + List of sample group names. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`seaborn.scatterplot`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + Examples + -------- + Below is a simple example: + + .. plot:: + :context: close-figs + + >>> import matplotlib.pyplot as plt + >>> import seaborn as sns + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> mf.plot_genepair('DNMT3A', 'FLT3', 'i_TumorVAF_WU') + >>> plt.tight_layout() + + We can create a grouped bar plot based on FAB classification: + + .. plot:: + :context: close-figs + + >>> annot_file = '~/fuc-data/tcga-laml/tcga_laml_annot.tsv' + >>> af = common.AnnFrame.from_file(annot_file, sample_col=0) + >>> mf.plot_genepair('DNMT3A', 'FLT3', 'i_TumorVAF_WU', + ... af=af, + ... group_col='FAB_classification') + >>> plt.tight_layout() + """""" + df = self.df[self.df.Hugo_Symbol.isin([x, y])] + df = df[['Tumor_Sample_Barcode', 'Hugo_Symbol', vaf_col]] + df = df.sort_values(vaf_col, ascending=False) + df = df.drop_duplicates(subset=['Tumor_Sample_Barcode', 'Hugo_Symbol']) + df = df.pivot(index='Tumor_Sample_Barcode', + columns='Hugo_Symbol', values=vaf_col) + df = df.fillna(0) + + if group_col is not None: + df = df.merge(af.df[group_col], left_index=True, right_index=True) + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + sns.scatterplot( + x=x, y=y, data=df, ax=ax, hue=group_col, hue_order=group_order, + **kwargs + ) + + # Print summary statistics including R-squared and p-value. + results = smf.ols(f'{y} ~ {x}', data=df).fit() + print(f'Results for {y} ~ {x}:') + print(f'R^2 = {results.rsquared:.2f}') + print(f' P = {results.f_pvalue:.2e}') + + return ax + + def plot_regplot_gene( + self, af, group_col, a, b, a_size=None, b_size=None, genes=None, + count=10, to_csv=None, ax=None, figsize=None, **kwargs + ): + """""" + Create a scatter plot with a linear regression model fit visualizing + correlation between gene mutation frequencies in two sample groups + A and B. + + Each point in the plot represents a gene. + + The method will automatically calculate and print summary statistics + including R-squared and p-value. + + Parameters + ---------- + af : AnnFrame + AnnFrame containing sample annotation data. + group_col : str + AnnFrame column containing sample group information. + a, b : str + Sample group names. + a_size, b_size : int, optional + Sample group sizes to use as denominator. By default, these are + inferred from the MafFrame and AnnFrame objects. + genes : list, optional + Genes to display. When absent, top mutated genes (``count``) will + be used. + count : int, defualt: 10 + Number of top mutated genes to display. Ignored if ``genes`` is + specified. + to_csv : str, optional + Write the plot's data to a CSV file. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`seaborn.regplot`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + Examples + -------- + + .. plot:: + + >>> import matplotlib.pyplot as plt + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> annot_file = '~/fuc-data/tcga-laml/tcga_laml_annot.tsv' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> af = common.AnnFrame.from_file(annot_file, sample_col=0) + >>> mf.plot_regplot_gene(af, 'FAB_classification', 'M1', 'M2') + Results for M2 ~ M1: + R^2 = 0.43 + P = 3.96e-02 + >>> plt.tight_layout() + """""" + df1 = self.matrix_prevalence() + df2 = af.df[af.df.index.isin(df1.columns)] + i_a = df2[df2[group_col] == a].index + i_b = df2[df2[group_col] == b].index + + # Determine which genes to display. + if genes is None: + genes = self.matrix_genes(count=count).index.to_list() + + # Determine each group's sample size. + if a_size is None: + a_size = len(i_a) + if b_size is None: + b_size = len(i_b) + + f = lambda x: 0 if x == 0 else 1 + s_a = df1.T.loc[i_a].applymap(f).sum().loc[genes] / a_size + s_b = df1.T.loc[i_b].applymap(f).sum().loc[genes] / b_size + df3 = pd.concat([s_a, s_b], axis=1) + df3.columns = [a, b] + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + # Draw the main plot. + sns.regplot(x=a, y=b, data=df3, ax=ax, **kwargs) + + # Write the DataFrame to a CSV file. + if to_csv is not None: + df3.to_csv(to_csv) + + # Print summary statistics including R-squared and p-value. + results = smf.ols(f'{b} ~ {a}', data=df3).fit() + print(f'Results for {b} ~ {a}:') + print(f'R^2 = {results.rsquared:.2f}') + print(f' P = {results.f_pvalue:.2e}') + + return ax + + def plot_regplot_tmb( + self, af, subject_col, group_col, a, b, ax=None, figsize=None, + to_csv=None, **kwargs + ): + """""" + Create a scatter plot with a linear regression model fit visualizing + correlation between TMB in two sample groups. + + The method will automatically calculate and print summary statistics + including R-squared and p-value. + + Parameters + ---------- + af : AnnFrame + AnnFrame containing sample annotation data. + subject_col : str + AnnFrame column containing sample subject information. + group_col : str + AnnFrame column containing sample group information. + a, b : str + Sample group names. + to_csv : str, optional + Write the plot's data to a CSV file. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`seaborn.regplot`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + See Also + -------- + fuc.api.pyvcf.VcfFrame.plot_regplot_tmb + Similar method for the :meth:`fuc.api.pyvcf.VcfFrame` class. + + Examples + -------- + + .. plot:: + + >>> import matplotlib.pyplot as plt + >>> from fuc import common, pymaf, pyvcf + >>> common.load_dataset('pyvcf') + >>> vcf_file = '~/fuc-data/pyvcf/normal-tumor.vcf' + >>> annot_file = '~/fuc-data/pyvcf/normal-tumor-annot.tsv' + >>> vf = pyvcf.VcfFrame.from_file(vcf_file) + >>> af = common.AnnFrame.from_file(annot_file, sample_col='Sample') + >>> mf = pymaf.MafFrame.from_vcf(vf) + >>> mf.plot_regplot_tmb(af, 'Patient', 'Tissue', 'Normal', 'Tumor') + Results for Tumor ~ Normal: + R^2 = 0.01 + P = 7.17e-01 + >>> plt.tight_layout() + """""" + d = self.df.value_counts('Tumor_Sample_Barcode').to_dict() + + df = af.df[af.df[group_col].isin([a, b])][[group_col, subject_col]] + df = df.reset_index().pivot(index=subject_col, columns=group_col, + values=af.df.index.name) + + def one_row(r): + for col in [a, b]: + if r[col] in d: + r[col] = d[r[col]] + else: + r[col] = 0 + return r + + df = df.apply(one_row, axis=1) + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + sns.regplot(x=a, y=b, data=df, ax=ax, **kwargs) + + # Print summary statistics including R-squared and p-value. + results = smf.ols(f'{b} ~ {a}', data=df).fit() + print(f""Results for {b} ~ {a}:"") + print(f'R^2 = {results.rsquared:.2f}') + print(f' P = {results.f_pvalue:.2e}') + + # Write the DataFrame to a CSV file. + if to_csv is not None: + df.to_csv(to_csv) + + return ax + + def plot_interactions( + self, count=10, cmap=None, ax=None, figsize=None, **kwargs + ): + """""" + Create a heatmap representing mutually exclusive or co-occurring set + of genes. + + This method performs pair-wise Fisher’s Exact test to detect such + significant pair of genes. + + Parameters + ---------- + count : int, defualt: 10 + Number of top mutated genes to display. + cmap : str, optional + Color map. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`seaborn.heatmap`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + Examples + -------- + + .. plot:: + + >>> import matplotlib.pyplot as plt + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> mf.plot_interactions(count=25, cmap='BrBG') + >>> plt.tight_layout() + """""" + df = self.matrix_prevalence() + genes = self.matrix_genes(count=count, mode='samples').index.to_list() + df = df.loc[genes] + df = df.applymap(lambda x: True if x else False) + df = df.T + pairs = list(itertools.combinations(genes, 2)) + data = [] + + def one_pair(a, b): + s_a = df[a].to_list() + s_b = df[b].to_list() + ab = 0 + AB = 0 + aB = 0 + Ab = 0 + for i in range(len(s_a)): + if s_a[i] and s_b[i]: + AB += 1 + elif s_a[i] and not s_b[i]: + Ab += 1 + elif not s_a[i] and s_b[i]: + aB += 1 + else: + ab += 1 + return (ab, AB, aB, Ab) + + for pair in pairs: + a = pair[0] + b = pair[1] + ab, AB, aB, Ab = one_pair(a, b) + event = 'Co_Occurence' if AB else 'Mutually_Exclusive' + data.append([a, b, ab, AB, aB, Ab, event]) + + df = pd.DataFrame(data, + columns=['A', 'B', 'ab', 'AB', 'aB', 'Ab', 'Event']) + + def one_row(r): + oddsr, p = fisher_exact([[r.AB, r.aB], [r.Ab, r.ab]], + alternative='two-sided') + return pd.Series([oddsr, p], index=['Odds_Ratio', 'P_Value']) + + df = pd.concat([df.apply(one_row, axis=1), df], axis=1) + df = df.sort_values('P_Value') + + def one_row(r): + r['Log_P_Value'] = -np.log10(r.P_Value) + if r.P_Value < 0.05: + r['Label'] = '*' + elif r.P_Value < 0.1: + r['Label'] = '.' + else: + r['Label'] = '' + if r.Event == 'Mutually_Exclusive': + r.Log_P_Value *= -1 + return r + + df = df.apply(one_row, axis=1) + + annot = df.pivot(index='A', columns='B', values='Label') + annot = annot.fillna('') + + df = df.pivot(index='A', columns='B', values='Log_P_Value') + df = df.fillna(0) + + for gene in genes: + if gene not in df.columns: + df[gene] = 0 + if gene not in annot.columns: + annot[gene] = '' + + df = df.T + annot = annot.T + + for gene in genes: + if gene not in df.columns: + df[gene] = 0 + if gene not in annot.columns: + annot[gene] = '' + + annot = annot[genes] + annot = annot.loc[genes] + + df = df[genes] + df = df.loc[genes] + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + # Create a mask for the heatmap. + corr = np.corrcoef(np.random.randn(count, 200)) + mask = np.zeros_like(corr) + mask[np.triu_indices_from(mask)] = True + + sns.heatmap( + df, annot=annot, fmt='', cmap=cmap, mask=mask, vmax=3, vmin=-3, + center=0, ax=ax, **kwargs + ) + + ax.set_xlabel('') + ax.set_ylabel('') + + return ax + + def plot_lollipop( + self, gene, alpha=0.7, ax=None, figsize=None, legend=True + ): + """""" + Create a lollipop or stem plot showing amino acid changes of a gene. + + Parameters + ---------- + gene : str + Name of the gene. + alpha : float, default: 0.7 + Set the color transparency. Must be within the 0-1 range, + inclusive. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + Examples + -------- + + .. plot:: + + >>> import matplotlib.pyplot as plt + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> mf.plot_lollipop('DNMT3A') + >>> plt.tight_layout() + """""" + # Only select variants from the gene. + df1 = self.df[self.df.Hugo_Symbol == gene] + + # Raise an error if there are no SNVs to plot. + if df1.empty: + raise ValueError(f""No variants to plot for the gene: '{gene}'."") + + # Count each amino acid change. + df2 = df1.Protein_Change.value_counts().to_frame().reset_index() + df2.columns = ['Protein_Change', 'Count'] + + # Identify variant classification for each amino acid change. + df3 = df1[['Protein_Change', 'Variant_Classification'] + ].drop_duplicates(subset=['Protein_Change']) + df4 = pd.merge(df2, df3, on='Protein_Change') + + # Extract amino acid positions. Sort the counts by position. + def one_row(r): + digits = [x for x in r.Protein_Change if x.isdigit()] + if not digits: + return np.nan + return int(''.join(digits)) + df4['Protein_Position'] = df4.apply(one_row, axis=1) + df4 = df4.dropna(subset=['Protein_Position']) + df4 = df4.sort_values(['Protein_Position']) + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + for i, nonsyn_name in enumerate(NONSYN_NAMES): + temp = df4[df4.Variant_Classification == nonsyn_name] + color = NONSYN_COLORS[i] + ax.vlines(temp.Protein_Position, ymin=0, ymax=temp.Count, + alpha=alpha, color=color) + ax.plot(temp.Protein_Position, temp.Count, 'o', alpha=alpha, + color=color, label=nonsyn_name) + + ax.set_xlabel('Position') + ax.set_ylabel('Count') + + if legend: + ax.legend() + + return ax + + def plot_mutated( + self, af=None, group_col=None, group_order=None, genes=None, + count=10, ax=None, figsize=None + ): + """""" + Create a bar plot visualizing the mutation prevalence of top + mutated genes. + + Parameters + ---------- + af : AnnFrame, optional + AnnFrame containing sample annotation data. + group_col : str, optional + AnnFrame column containing sample group information. + group_order : list, optional + List of sample group names. + genes : list, optional + Genes to display. When absent, top mutated genes (``count``) will + be used. + count : int, defualt: 10 + Number of top mutated genes to display. Ignored if ``genes`` is + specified. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`seaborn.barplot`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + Examples + -------- + Below is a simple example: + + .. plot:: + :context: close-figs + + >>> import matplotlib.pyplot as plt + >>> import seaborn as sns + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> mf.plot_mutated() + >>> plt.tight_layout() + + We can create a grouped bar plot based on FAB classification: + + .. plot:: + :context: close-figs + + >>> annot_file = '~/fuc-data/tcga-laml/tcga_laml_annot.tsv' + >>> af = common.AnnFrame.from_file(annot_file, sample_col=0) + >>> mf.plot_mutated(af=af, + ... group_col='FAB_classification', + ... group_order=['M0', 'M1', 'M2']) + >>> plt.tight_layout() + """""" + df = self.matrix_prevalence() + + # Determine which genes to display. + if genes is None: + genes = self.matrix_genes(count=count).index.to_list() + + df = df.loc[genes] + df = df.applymap(lambda x: True if x else False) + if group_col is None: + df = (df.sum(axis=1) / df.shape[1]).to_frame().reset_index() + df.columns.values[1] = 'Prevalence' + else: + df = df.T + df = pd.merge(df, af.df[group_col], left_index=True, right_index=True) + df = df.groupby([group_col]).mean().reset_index() + df = df.melt(id_vars=[group_col]) + df.columns = [group_col, 'Hugo_Symbol', 'Prevalence'] + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + sns.barplot( + x='Hugo_Symbol', y='Prevalence', data=df, hue=group_col, + hue_order=group_order, ax=ax + ) + + ax.set_xlabel('') + + return ax + + def plot_mutated_matched( + self, af, patient_col, group_col, group_order, count=10, ax=None, + figsize=None, **kwargs + ): + """""" + Create a bar plot visualizing the mutation prevalence of top + mutated genes. + + Parameters + ---------- + af : AnnFrame + AnnFrame containing sample annotation data. + patient_col : str + AnnFrame column containing patient information. + group_col : str + AnnFrame column containing sample group information. + group_order : list + List of sample group names. + count : int, defualt: 10 + Number of top mutated genes to display. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`seaborn.barplot`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + """""" + df = self.matrix_waterfall_matched(af, patient_col, group_col, group_order, count=count) + df = df.applymap(lambda x: 0 if x == 'None' else 1) + s = df.sum(axis=1) / len(df.columns) * 100 + s.name = 'Count' + df = s.to_frame().reset_index() + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + sns.barplot( + x='Count', y='Gene', hue='Group', data=df, hue_order=group_order, + orient='h', ax=ax, **kwargs + ) + + ax.set_xlabel('Patients (%)') + ax.set_ylabel('') + + return ax + + def plot_rainfall( + self, sample, palette=None, legend='auto', ax=None, figsize=None, + **kwargs + ): + """""" + Create a rainfall plot visualizing inter-variant distance on a linear + genomic scale for single sample. + + Parameters + ---------- + sample : str + Name of the sample. + palette : str, optional + Name of the seaborn palette. See the :ref:`tutorials:Control plot + colors` tutorial for details. + legend : {'auto', 'brief', 'full', False}, default: 'auto' + Display setting of the legend according to + :meth:`seaborn.scatterplot`. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`seaborn.scatterplot`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + Examples + -------- + + .. plot:: + + >>> import matplotlib.pyplot as plt + >>> import seaborn as sns + >>> from fuc import common, pymaf + >>> common.load_dataset('brca') + >>> maf_file = '~/fuc-data/brca/brca.maf.gz' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> mf.plot_rainfall('TCGA-A8-A08B', + ... figsize=(14, 7), + ... palette=sns.color_palette('Set2')[:6]) + >>> plt.tight_layout() + """""" + # Select variants from the sample. + df = self.df[self.df.Tumor_Sample_Barcode == sample] + + # Remove indels. + df = df[df.Variant_Type == 'SNP'] + + # Raise an error if there are no SNVs to plot. + if df.empty: + message = ( + 'There are no SNVs to be drawn ' + f""for the sample: '{sample}'."" + ) + raise ValueError(message) + + # Get SNV class for each variant. + def one_row(r): + change = r.Reference_Allele + '>' + r.Tumor_Seq_Allele2 + return SNV_CLASSES[change]['class'] + df['SNV_Class'] = df.apply(one_row, axis=1) + + # Convert string chromosomes to integers for ordering. + def one_row(r): + r.Chromosome = int(r.Chromosome.replace( + 'chr', '').replace('X', '23').replace('Y', '24')) + return r + df = df.apply(one_row, axis=1) + df = df[['Chromosome', 'Start_Position', 'SNV_Class']] + df = df.sort_values(['Chromosome', 'Start_Position']) + + # Update positions as if all chromosomes are one long molecule. + def one_row(r): + if r.Chromosome == 1: + return r + r.Start_Position += sum(CHROM_LENGTHS['hg19'][:r.Chromosome-1]) + return r + df = df.apply(one_row, axis=1) + s = np.diff(df.Start_Position) + s = np.insert(s, 0, 0) + s = np.log10(s + 1) + df['Interevent_Distance'] = s + df = df.reset_index(drop=True) + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + bounds = [0] + df.drop_duplicates(subset=['Chromosome'], + keep='last').index.to_list() + + xticks = [] + for i, bound in enumerate(bounds): + if i == 0: + continue + elif i == 1: + xticks.append(bound / 2) + else: + xticks.append(bounds[i-1] + (bound - bounds[i-1]) / 2) + + for bound in bounds: + ax.axvline(x=bound, color='lightgray', zorder=1) + + sns.scatterplot( + x=df.index, y='Interevent_Distance', data=df, hue='SNV_Class', + hue_order=SNV_CLASS_ORDER, palette=palette, ax=ax, legend=legend, + zorder=2, **kwargs + ) + + ax.set_xlabel('Chromosomes') + ax.set_ylabel('Interevent distance') + ax.set_xticks(xticks) + ax.set_xticklabels(['X' if x == 23 else 'Y' if x == 24 else x + for x in df.Chromosome.unique()]) + + return ax + + def plot_snvclsc( + self, af=None, group_col=None, group_order=None, palette=None, + flip=False, ax=None, figsize=None, **kwargs + ): + """""" + Create a bar plot summarizing the count distrubtions of the six + :ref:`glossary:SNV classes` for all samples. + + A grouped bar plot can be created with ``group_col`` (requires an AnnFrame). + + Parameters + ---------- + af : AnnFrame, optional + AnnFrame containing sample annotation data. + group_col : str, optional + AnnFrame column containing sample group information. + group_order : list, optional + List of sample group names. + palette : str, optional + Name of the seaborn palette. See the :ref:`tutorials:Control plot + colors` tutorial for details. + flip : bool, default: False + If True, flip the x and y axes. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`seaborn.barplot`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + See Also + -------- + MafFrame.plot_snvclsp + Create a box plot summarizing the proportion distrubtions of + the six :ref:`glossary:SNV classes` for all sample. + MafFrame.plot_snvclss + Create a bar plot showing the proportions of the six + :ref:`glossary:SNV classes` for individual samples. + + Examples + -------- + Below is a simple example: + + .. plot:: + :context: close-figs + + >>> import matplotlib.pyplot as plt + >>> import seaborn as sns + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> mf.plot_snvclsc(palette=sns.color_palette('Dark2')) + >>> plt.tight_layout() + + We can create a grouped bar plot based on FAB classification: + + .. plot:: + :context: close-figs + + >>> annot_file = '~/fuc-data/tcga-laml/tcga_laml_annot.tsv' + >>> af = common.AnnFrame.from_file(annot_file, sample_col=0) + >>> mf.plot_snvclsc(af=af, + ... group_col='FAB_classification', + ... group_order=['M0', 'M1', 'M2']) + >>> plt.tight_layout() + """""" + # Add the SNV_Class column. + df = self.df[self.df.Variant_Type == 'SNP'] + def one_row(r): + change = r.Reference_Allele + '>' + r.Tumor_Seq_Allele2 + return SNV_CLASSES[change]['class'] + s = df.apply(one_row, axis=1) + s.name = 'SNV_Class' + df = pd.concat([df, s], axis=1) + + # Count the occurance of each SNV class. + if group_col is not None: + df = pd.merge(df, af.df[group_col], left_on='Tumor_Sample_Barcode', + right_index=True) + s = df.groupby([group_col]).SNV_Class.value_counts() + df = s.to_frame().rename(columns={'SNV_Class': 'Count'} + ).reset_index() + else: + s = df.SNV_Class.value_counts() + df = s.to_frame().reset_index() + df.columns = ['SNV_Class', 'Count'] + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + if flip: + x, y = 'Count', 'SNV_Class' + xlabel, ylabel = 'Count', '' + else: + x, y = 'SNV_Class', 'Count' + xlabel, ylabel = '', 'Count' + + sns.barplot( + x=x, y=y, data=df, ax=ax, hue=group_col, hue_order=group_order, + palette=palette, order=SNV_CLASS_ORDER, **kwargs + ) + + ax.set_xlabel(xlabel) + ax.set_ylabel(ylabel) + + return ax + + def plot_snvclsp( + self, af=None, group_col=None, group_order=None, palette=None, flip=False, + ax=None, figsize=None, **kwargs + ): + """""" + Create a box plot summarizing the proportion distrubtions of the six + :ref:`glossary:SNV classes` for all sample. + + Parameters + ---------- + af : AnnFrame, optional + AnnFrame containing sample annotation data. + group_col : str, optional + AnnFrame column containing sample group information. + group_order : list, optional + List of sample group names. + palette : str, optional + Name of the seaborn palette. See the :ref:`tutorials:Control plot + colors` tutorial for details. + flip : bool, default: False + If True, flip the x and y axes. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`seaborn.boxplot`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + See Also + -------- + MafFrame.plot_snvclsc + Create a bar plot summarizing the count distrubtions of the six + :ref:`glossary:SNV classes` for all samples. + MafFrame.plot_snvclss + Create a bar plot showing the proportions of the six + :ref:`glossary:SNV classes` for individual samples. + + Examples + -------- + Below is a simple example: + + .. plot:: + :context: close-figs + + >>> import matplotlib.pyplot as plt + >>> import seaborn as sns + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> mf.plot_snvclsp(palette=sns.color_palette('Set2')) + >>> plt.tight_layout() + + We can create a grouped bar plot based on FAB classification: + + .. plot:: + :context: close-figs + + >>> annot_file = '~/fuc-data/tcga-laml/tcga_laml_annot.tsv' + >>> af = common.AnnFrame.from_file(annot_file, sample_col=0) + >>> mf.plot_snvclsp(af=af, + ... group_col='FAB_classification', + ... group_order=['M0', 'M1', 'M2']) + >>> plt.tight_layout() + """""" + # Add the SNV_Class column. + df = self.df[self.df.Variant_Type == 'SNP'] + def one_row(r): + change = r.Reference_Allele + '>' + r.Tumor_Seq_Allele2 + return SNV_CLASSES[change]['class'] + s = df.apply(one_row, axis=1) + s.name = 'SNV_Class' + df = pd.concat([df, s], axis=1) + + # Compute the proportions of SNV classes in each sample. + s = df.groupby('Tumor_Sample_Barcode')['SNV_Class'].value_counts() + s.name = 'Count' + df = s.to_frame().reset_index() + df = df.pivot(index='Tumor_Sample_Barcode', columns='SNV_Class') + df = df.fillna(0) + df = df.apply(lambda r: r/r.sum(), axis=1) + df.columns = df.columns.get_level_values(1) + df.columns.name = '' + + if group_col is None: + df = pd.melt(df, var_name='SNV_Class', value_name='Proportion') + else: + df = pd.merge(df, af.df[group_col], left_index=True, right_index=True) + df = pd.melt(df, id_vars=[group_col], var_name='SNV_Class', + value_name='Proportion') + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + if flip: + x, y = 'Proportion', 'SNV_Class' + xlabel, ylabel = 'Proportion', '' + else: + x, y = 'SNV_Class', 'Proportion' + xlabel, ylabel = '', 'Proportion' + + sns.boxplot( + x=x, y=y, data=df, hue=group_col, hue_order=group_order, + palette=palette, ax=ax, **kwargs + ) + + ax.set_xlabel(xlabel) + ax.set_ylabel(ylabel) + + return ax + + def plot_snvclss( + self, samples=None, color=None, colormap=None, width=0.8, + legend=True, flip=False, to_csv=None, ax=None, figsize=None, **kwargs + ): + """""" + Create a bar plot showing the proportions of the six + :ref:`glossary:SNV classes` for individual samples. + + Parameters + ---------- + samples : list, optional + List of samples to display (in that order too). If samples that + are absent in the MafFrame are provided, the method will give a + warning but still draw an empty bar for those samples. + color : list, optional + List of color tuples. See the :ref:`tutorials:Control plot + colors` tutorial for details. + colormap : str or matplotlib colormap object, optional + Colormap to select colors from. See the :ref:`tutorials:Control + plot colors` tutorial for details. + width : float, default: 0.8 + The width of the bars. + legend : bool, default: True + Place legend on axis subplots. + flip : bool, default: False + If True, flip the x and y axes. + to_csv : str, optional + Write the plot's data to a CSV file. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`pandas.DataFrame.plot.bar` or + :meth:`pandas.DataFrame.plot.barh`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + See Also + -------- + MafFrame.plot_snvclsc + Create a bar plot summarizing the count distrubtions of the six + :ref:`glossary:SNV classes` for all samples. + MafFrame.plot_snvclsp + Create a box plot summarizing the proportion distrubtions of + the six :ref:`glossary:SNV classes` for all sample. + + Examples + -------- + + .. plot:: + + >>> import matplotlib.pyplot as plt + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> ax = mf.plot_snvclss(width=1, color=plt.get_cmap('Set2').colors) + >>> ax.legend(loc='upper right') + >>> plt.tight_layout() + """""" + # Add the SNV_Class column. + df = self.df[self.df.Variant_Type == 'SNP'] + def one_row(r): + change = r.Reference_Allele + '>' + r.Tumor_Seq_Allele2 + return SNV_CLASSES[change]['class'] + s = df.apply(one_row, axis=1) + s.name = 'SNV_Class' + df = pd.concat([df, s], axis=1) + + # Compute the proportions of SNV classes in each sample. + s = df.groupby('Tumor_Sample_Barcode')['SNV_Class'].value_counts() + s.name = 'Count' + df = s.to_frame().reset_index() + df = df.pivot(index='Tumor_Sample_Barcode', columns='SNV_Class') + df = df.fillna(0) + df = df.apply(lambda r: r/r.sum(), axis=1) + df.columns = df.columns.get_level_values(1) + df.columns.name = '' + for x in SNV_CLASS_ORDER: + if x not in df.columns: + df[x] = 0 + df = df[SNV_CLASS_ORDER] + + # Determine which samples should be displayed. + if samples is not None: + missing_samples = [] + missing_data = [] + for sample in samples: + if sample not in df.index: + missing_samples.append(sample) + missing_data.append([0] * 6) + if missing_samples: + message = ( + 'Although the following samples are absent in the ' + 'MafFrame, they will still be displayed as empty bar: ' + f'{missing_samples}.' + ) + warnings.warn(message) + temp = pd.DataFrame(missing_data) + temp.index = missing_samples + temp.columns = SNV_CLASS_ORDER + df = pd.concat([df, temp]).loc[samples] + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + if flip: + kind = 'barh' + xlabel, ylabel = 'Proportion', 'Samples' + else: + kind = 'bar' + xlabel, ylabel = 'Samples', 'Proportion' + + df.plot( + kind=kind, ax=ax, stacked=True, legend=legend, width=width, + color=color, colormap=colormap, **kwargs + ) + + ax.set_xlabel(xlabel) + ax.set_ylabel(ylabel) + + if flip: + ax.set_yticks([]) + else: + ax.set_xticks([]) + + # Write the DataFrame to a CSV file. + if to_csv is not None: + df.to_csv(to_csv) + + return ax + + def plot_titv( + self, af=None, group_col=None, group_order=None, flip=False, ax=None, + figsize=None, **kwargs + ): + """""" + Create a box plot showing the :ref:`Ti/Tv ` proportions of samples. + + Parameters + ---------- + af : AnnFrame, optional + AnnFrame containing sample annotation data. + group_col : str, optional + AnnFrame column containing sample group information. + group_order : list, optional + List of sample group names. + flip : bool, default: False + If True, flip the x and y axes. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`seaborn.boxplot`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + See Also + -------- + fuc.api.pyvcf.VcfFrame.plot_titv + Similar method for the :class:`fuc.api.pyvcf.VcfFrame` class. + + Examples + -------- + Below is a simple example: + + .. plot:: + :context: close-figs + + >>> import matplotlib.pyplot as plt + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> mf.plot_titv() + >>> plt.tight_layout() + + We can create a grouped bar plot based on FAB classification: + + .. plot:: + :context: close-figs + + >>> annot_file = '~/fuc-data/tcga-laml/tcga_laml_annot.tsv' + >>> af = common.AnnFrame.from_file(annot_file, sample_col=0) + >>> mf.plot_titv(af=af, + ... group_col='FAB_classification', + ... group_order=['M0', 'M1', 'M2']) + >>> plt.tight_layout() + """""" + df = self.df[self.df.Variant_Type == 'SNP'] + def one_row(r): + change = r.Reference_Allele + '>' + r.Tumor_Seq_Allele2 + return SNV_CLASSES[change]['type'] + s = df.apply(one_row, axis=1) + s.name = 'SNV_Type' + df = pd.concat([df, s], axis=1) + s = df.groupby('Tumor_Sample_Barcode')['SNV_Type'].value_counts() + s.name = 'Count' + df = s.to_frame().reset_index() + df = df.pivot(index='Tumor_Sample_Barcode', columns='SNV_Type') + + df = df.fillna(0) + df = df.apply(lambda r: r/r.sum(), axis=1) + df.columns = df.columns.get_level_values(1) + df.columns.name = '' + + if group_col is not None: + df = pd.merge(df, af.df[group_col], left_index=True, right_index=True) + df = df.reset_index(drop=True) + df = df.set_index(group_col) + df = pd.melt(df, var_name='SNV_Type', value_name='Proportion', + ignore_index=False) + df = df.reset_index() + else: + df = pd.melt(df, var_name='SNV_Type', value_name='Proportion') + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + if flip: + x, y = 'Proportion', 'SNV_Type' + xlabel, ylabel = 'Proportion', '' + else: + x, y = 'SNV_Type', 'Proportion' + xlabel, ylabel = '', 'Proportion' + + sns.boxplot( + x=x, y=y, data=df, hue=group_col, hue_order=group_order, ax=ax, + **kwargs + ) + + ax.set_xlabel(xlabel) + ax.set_ylabel(ylabel) + + return ax + + def plot_summary( + self, figsize=(15, 10), title_fontsize=16, ticklabels_fontsize=12, + legend_fontsize=12 + + ): + """""" + Create a summary figure for MafFrame. + + Parameters + ---------- + figsize : tuple, default: (15, 10) + Width, height in inches. Format: (float, float). + title_fontsize : float, default: 16 + Font size of subplot titles. + ticklabels_fontsize : float, default: 12 + Font size of tick labels. + legend_fontsize : float, default: 12 + Font size of legend texts. + + Examples + -------- + + .. plot:: + + >>> import matplotlib.pyplot as plt + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> mf.plot_summary() + """""" + g = {'height_ratios': [10, 10, 1]} + fig, axes = plt.subplots(3, 3, figsize=figsize, gridspec_kw=g) + [[ax1, ax2, ax3], [ax4, ax5, ax6], [ax7, ax8, ax9]] = axes + gs = axes[2, 0].get_gridspec() + for ax in axes[2, :]: + ax.remove() + axbig = fig.add_subplot(gs[2, :]) + + # Create the 'Variant classification (variants)' figure. + self.plot_varcls(ax=ax1) + ax1.set_yticks([]) + ax1.set_title('Variant classification (variants)', + fontsize=title_fontsize) + ax1.set_xlabel('') + ax1.tick_params(axis='x', which='major', + labelsize=ticklabels_fontsize) + + # Create the 'Variant type' figure. + self.plot_vartype(ax=ax2, palette='Pastel1', flip=True) + ax2.set_title('Variant type', fontsize=title_fontsize) + ax2.set_xlabel('') + ax2.tick_params(axis='both', which='major', + labelsize=ticklabels_fontsize) + + # Create the 'SNV class' figure. + self.plot_snvclsc(ax=ax3, flip=True, + palette=sns.color_palette('Set2')) + ax3.set_title('SNV class', fontsize=title_fontsize) + ax3.set_xlabel('') + ax3.tick_params(axis='both', which='major', + labelsize=ticklabels_fontsize) + + # Create the 'Variants per sample' figure. + median = self.matrix_tmb().sum(axis=1).median() + self.plot_tmb(ax=ax4, width=1) + ax4.set_title(f'Variants per sample (median={median:.1f})', + fontsize=title_fontsize) + ax4.set_xlabel('') + ax4.set_ylabel('') + ax4.tick_params(axis='y', which='major', + labelsize=ticklabels_fontsize) + + ax4.axhline(y=median, color='red', linestyle='dashed') + + # Create the 'Variant classification (samples)' figure. + self.plot_varsum(ax=ax5) + ax5.set_title('Variant classification (samples)', + fontsize=title_fontsize) + ax5.set_yticks([]) + ax5.set_xlabel('') + ax5.tick_params(axis='x', which='major', + labelsize=ticklabels_fontsize) + + # Create the 'Top 10 mutated genes' figure. + self.plot_genes(ax=ax6) + ax6.set_title('Top 10 mutated genes', fontsize=title_fontsize) + ax6.set_xlabel('') + ax6.tick_params(axis='both', which='major', + labelsize=ticklabels_fontsize) + + # Add the legend. + axbig.legend( + handles=common.legend_handles(NONSYN_NAMES, colors=NONSYN_COLORS), + title='Variant_Classification', + loc='upper center', + ncol=3, + fontsize=legend_fontsize, + title_fontsize=legend_fontsize + ) + axbig.axis('off') + + plt.tight_layout() + + def plot_tmb( + self, samples=None, width=0.8, ax=None, figsize=None, **kwargs + ): + """""" + Create a bar plot showing the :ref:`TMB ` distributions of samples. + + Parameters + ---------- + samples : list, optional + List of samples to display (in that order too). If samples that + are absent in the MafFrame are provided, the method will give a + warning but still draw an empty bar for those samples. + width : float, default: 0.8 + The width of the bars. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`pandas.DataFrame.plot.bar`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + Examples + -------- + Below is a simple example: + + .. plot:: + + >>> import matplotlib.pyplot as plt + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> mf.plot_tmb(width=1) + >>> plt.tight_layout() + """""" + df = self.matrix_tmb() + + if samples is not None: + df = df.T + missing_samples = [] + for sample in samples: + if sample not in df.columns: + missing_samples.append(sample) + if missing_samples: + message = ( + 'Although the following samples are absent in the ' + 'MafFrame, they will still be displayed as empty bar: ' + f'{missing_samples}.' + ) + warnings.warn(message) + for missing_sample in missing_samples: + df[missing_sample] = 0 + df = df[samples] + df = df.T + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + df.plot.bar(stacked=True, ax=ax, width=width, legend=False, + color=NONSYN_COLORS, **kwargs) + + ax.set_xlabel('Samples') + ax.set_ylabel('Count') + ax.set_xticks([]) + + return ax + + def plot_tmb_matched( + self, af, patient_col, group_col, group_order=None, patients=None, + legend=True, ax=None, figsize=None, **kwargs + ): + """""" + Create a grouped bar plot showing TMB distributions for different + group levels in each patient. + + Parameters + ---------- + af : AnnFrame + AnnFrame containing sample annotation data. + patient_col : str + AnnFrame column containing patient information. + group_col : str + AnnFrame column containing sample group information. + group_order : list, optional + List of sample group names. + patients : list, optional + List of patient names. + legend : bool, default: True + Place legend on axis subplots. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`pandas.DataFrame.plot.bar` + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + """""" + df = self.matrix_tmb().T + + for sample in af.samples: + if sample not in df.columns: + df[sample] = 0 + + s = df.sum() + s.name = 'TMB' + df = pd.concat([s, af.df[[patient_col, group_col]]], axis=1) + + df = df.pivot(index=patient_col, columns=group_col, values='TMB') + + if group_order is not None: + df = df[group_order] + + i = df.sum(axis=1).sort_values(ascending=False).index + df = df.loc[i] + + if patients is not None: + df = df.loc[patients] + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + df.plot(ax=ax, kind='bar', stacked=True, legend=legend, **kwargs) + + ax.set_xlabel('') + ax.set_ylabel('TMB') + + return ax + + def plot_vaf( + self, vaf_col, count=10, af=None, group_col=None, group_order=None, + flip=False, sort=True, ax=None, figsize=None, **kwargs + ): + """""" + Create a box plot showing the :ref:`VAF ` distributions of top mutated genes. + + A grouped box plot can be created with ``group_col`` (requires an + AnnFrame). + + Parameters + ---------- + vaf_col : str + MafFrame column containing VAF data. + count : int, default: 10 + Number of top mutated genes to display. + af : AnnFrame, optional + AnnFrame containing sample annotation data. + group_col : str, optional + AnnFrame column containing sample group information. + group_order : list, optional + List of sample group names. + flip : bool, default: False + If True, flip the x and y axes. + sort : bool, default: True + If False, do not sort the genes by median value. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`seaborn.boxplot`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + Examples + -------- + + Below is a simple example: + + .. plot:: + :context: close-figs + + >>> import matplotlib.pyplot as plt + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> mf.plot_vaf('i_TumorVAF_WU') + >>> plt.tight_layout() + + We can create a grouped bar plot based on FAB classification: + + .. plot:: + :context: close-figs + + >>> annot_file = '~/fuc-data/tcga-laml/tcga_laml_annot.tsv' + >>> af = common.AnnFrame.from_file(annot_file, sample_col=0) + >>> mf.plot_vaf('i_TumorVAF_WU', + ... af=af, + ... group_col='FAB_classification', + ... group_order=['M1', 'M2', 'M3'], + ... count=5) + >>> plt.tight_layout() + """""" + genes = self.matrix_genes(count=count).index.to_list() + + if sort: + medians = self.df.groupby('Hugo_Symbol')[vaf_col].median() + genes = medians[genes].sort_values( + ascending=False).index.to_list() + + df = self.df[self.df.Hugo_Symbol.isin(genes)] + + if group_col is not None: + df = pd.merge(df, af.df, left_on='Tumor_Sample_Barcode', + right_index=True) + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + if flip: + x, y = vaf_col, 'Hugo_Symbol' + xlabel, ylabel = 'VAF', '' + else: + x, y = 'Hugo_Symbol', vaf_col + xlabel, ylabel = '', 'VAF' + + sns.boxplot( + x=x, y=y, data=df, ax=ax, order=genes, hue=group_col, + hue_order=group_order, **kwargs + ) + + ax.set_xlabel(xlabel) + ax.set_ylabel(ylabel) + + return ax + + def plot_varcls(self, ax=None, figsize=None, **kwargs): + """""" + Create a bar plot for the nonsynonymous variant classes. + + Parameters + ---------- + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`matplotlib.axes.Axes.bar` and :meth:`seaborn.barplot`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + Examples + -------- + + .. plot:: + + >>> import matplotlib.pyplot as plt + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> mf.plot_varcls() + >>> plt.tight_layout() + """""" + d = self.df.Variant_Classification.value_counts().to_dict() + counts = {} + for varcls in NONSYN_NAMES: + if varcls in d: + counts[varcls] = d[varcls] + else: + counts[varcls] = 0 + s = pd.Series(counts).reindex(index=NONSYN_NAMES) + df = s.to_frame().reset_index() + df.columns = ['Variant_Classification', 'Count'] + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + sns.barplot(x='Count', y='Variant_Classification', data=df, + ax=ax, palette=NONSYN_COLORS, **kwargs) + + ax.set_ylabel('') + + return ax + + def plot_matrixg( + self, gene, af, group_col, group_order=None, cbar=True, ax=None, + figsize=None, **kwargs + ): + """""" + Create a heatmap of count matrix with a shape of (sample groups, + protein changes). + + Parameters + ---------- + gene : str + Name of the gene. + af : AnnFrame + AnnFrame containing sample annotation data. + group_col : str + AnnFrame column containing sample group information. + group_order : list, optional + List of sample group names. + cbar : bool, default: True + Whether to draw a colorbar. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`seaborn.heatmap`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + Examples + -------- + + .. plot:: + + >>> import matplotlib.pyplot as plt + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> annot_file = '~/fuc-data/tcga-laml/tcga_laml_annot.tsv' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> af = common.AnnFrame.from_file(annot_file, sample_col=0) + >>> mf.plot_matrixg('IDH1', af, 'FAB_classification', linewidth=0.5, square=True, annot=True) + >>> plt.tight_layout() + """""" + df = self.df[self.df.Hugo_Symbol == gene] + + if df.empty: + raise ValueError(f'No protein changes were found: {gene}') + + df = df[['Tumor_Sample_Barcode', 'Protein_Change']] + df = df[df.Protein_Change != '.'] + df = df.merge(af.df[group_col], left_on='Tumor_Sample_Barcode', right_index=True) + s = df.groupby(group_col)['Protein_Change'].value_counts() + s.name = 'Count' + df = s.to_frame().reset_index() + df = df.pivot(index=group_col, + columns='Protein_Change', + values='Count') + df = df.fillna(0) + + if group_order is not None: + missing_groups = [] + for group in group_order: + if group not in df.index: + missing_groups.append(group) + if missing_groups: + message = ( + 'Although the following sample groups are absent in the ' + 'MafFrame, they will still be displayed as empty bar: ' + f'{missing_groups}.' + ) + warnings.warn(message) + df = df.T + for missing_group in missing_groups: + df[missing_group] = 0 + df = df[groups] + df = df.T + + # Sort protein changes by position. + f = lambda s: int(''.join([x for x in list(s) if x.isdigit()])) + l = df.columns + s = pd.Series([f(x) for x in l], index=l).sort_values() + df = df[s.index] + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + sns.heatmap( + df, ax=ax, cbar=cbar, **kwargs + ) + + ax.set_xlabel('') + ax.set_ylabel('') + + return ax + + def plot_matrixs( + self, gene, samples=None, c0='lightgray', c1='red', l0='0', l1='1', + cbar=True, square=False, ax=None, figsize=None, **kwargs + ): + """""" + Create a heatmap of presence/absence matrix with a shape of (samples, + protein changes). + + Parameters + ---------- + gene : str + Name of the gene. + samples : list, optional + List of samples to display (in that order too). If samples that + are absent in the MafFrame are provided, the method will give a + warning but still draw an empty bar for those samples. + c0 : str, default: 'lightgray' + Color for absence. + c1 : str, default: 'red' + Color for presence. + l0 : str, default: '0' + Label for absence. + l1 : str, default: '1' + Label for presence. + cbar : bool, default: True + Whether to draw a colorbar. + square : bool, default: False + If True, set the Axes aspect to ""equal"" so each cell will be + square-shaped. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`seaborn.heatmap`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + Examples + -------- + + .. plot:: + + >>> import matplotlib.pyplot as plt + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> mf.plot_matrixs('KRAS', linewidth=0.5, square=True) + >>> plt.tight_layout() + """""" + df = self.df[self.df.Hugo_Symbol == gene] + + if df.empty: + raise ValueError(f'No protein changes were found: {gene}') + + df = df[['Tumor_Sample_Barcode', 'Protein_Change']] + df = df[df.Protein_Change != '.'] + df['Presence'] = 1 + df = df.pivot(index='Tumor_Sample_Barcode', + columns='Protein_Change', + values='Presence') + df = df.fillna(0) + + if samples is not None: + missing_samples = [] + for sample in samples: + if sample not in df.index: + missing_samples.append(sample) + if missing_samples: + message = ( + 'Although the following samples are absent in the ' + 'MafFrame, they will still be displayed as empty bar: ' + f'{missing_samples}.' + ) + warnings.warn(message) + df = df.T + for missing_sample in missing_samples: + df[missing_sample] = 0 + df = df[samples] + df = df.T + + # Sort protein changes by position. + f = lambda s: int(''.join([x for x in list(s) if x.isdigit()])) + l = df.columns + s = pd.Series([f(x) for x in l], index=l).sort_values() + df = df[s.index] + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + if len(np.unique(df.values)) == 1: + cmap = [c1] + cbar_ticklabels = [l1] + else: + cmap = [c0, c1] + cbar_ticklabels = [l0, l1] + + sns.heatmap( + df, cbar=cbar, cmap=cmap, square=square, ax=ax, **kwargs + ) + + if cbar: + colorbar = ax.collections[0].colorbar + n=len(cmap) + r = colorbar.vmax - colorbar.vmin + colorbar.set_ticks([colorbar.vmin + r/n * (0.5+i) for i in range(n)]) + colorbar.set_ticklabels(cbar_ticklabels) + + ax.set_xlabel('') + ax.set_ylabel('') + + return ax + + def plot_varsum(self, flip=False, ax=None, figsize=None): + """""" + Create a summary box plot for variant classifications. + + Parameters + ---------- + flip : bool, default: False + If True, flip the x and y axes. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + Examples + -------- + + .. plot:: + + >>> import matplotlib.pyplot as plt + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> mf.plot_varsum() + >>> plt.tight_layout() + """""" + df = self.matrix_tmb() + df = pd.melt(df, value_vars=df.columns) + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + if flip: + x, y = 'variable', 'value' + xlabel, ylabel = '', 'Samples' + else: + x, y = 'value', 'variable' + xlabel, ylabel = 'Samples', '' + + sns.boxplot(x=x, y=y, data=df, ax=ax, showfliers=False, + palette=NONSYN_COLORS) + + ax.set_xlabel(xlabel) + ax.set_ylabel(ylabel) + return ax + + def plot_vartype(self, palette=None, flip=False, ax=None, figsize=None, **kwargs): + """""" + Create a bar plot summarizing the count distrubtions of viaration + types for all samples. + + Parameters + ---------- + palette : str, optional + Name of the seaborn palette. See the :ref:`tutorials:Control plot + colors` tutorial for details. + flip : bool, default: False + If True, flip the x and y axes. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`seaborn.barplot`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + Examples + -------- + + .. plot:: + + >>> import matplotlib.pyplot as plt + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> mf.plot_vartype() + >>> plt.tight_layout() + """""" + s = self.df.Variant_Type.value_counts() + df = s.to_frame().reset_index() + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + if flip: + x, y = 'Variant_Type', 'index' + xlabel, ylabel = 'Count', '' + else: + x, y = 'index', 'Variant_Type' + xlabel, ylabel = '', 'Count' + + sns.barplot(x=x, y=y, data=df, ax=ax, palette=palette, **kwargs) + + ax.set_xlabel(xlabel) + ax.set_ylabel(ylabel) + + return ax + + def plot_waterfall( + self, count=10, keep_empty=False, samples=None, ax=None, + figsize=None, **kwargs + ): + """""" + Create a waterfall plot (oncoplot). + + See this :ref:`tutorial ` to + learn how to create customized oncoplots. + + Parameters + ---------- + count : int, default: 10 + Number of top mutated genes to display. + keep_empty : bool, default: False + If True, display samples that do not have any mutations. + samples : list, optional + List of samples to display (in that order too). If samples that + are absent in the MafFrame are provided, the method will give a + warning but still draw an empty bar for those samples. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`seaborn.heatmap`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + Examples + -------- + + .. plot:: + + >>> import matplotlib.pyplot as plt + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> mf.plot_waterfall(linewidths=0.5) + >>> plt.tight_layout() + """""" + df = self.matrix_waterfall(count=count, keep_empty=keep_empty) + + if samples is not None: + missing_samples = [] + for sample in samples: + if sample not in df.columns: + missing_samples.append(sample) + if missing_samples: + message = ( + 'Although the following samples are absent in the ' + 'MafFrame, they will still be displayed as empty bar: ' + f'{missing_samples}.' + ) + warnings.warn(message) + for missing_sample in missing_samples: + df[missing_sample] = 'None' + df = df[samples] + + # Apply the mapping between items and integers. + l = reversed(NONSYN_NAMES + ['Multi_Hit', 'None']) + d = {k: v for v, k in enumerate(l)} + df = df.applymap(lambda x: d[x]) + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + colors = list(reversed(NONSYN_COLORS + ['k', 'lightgray'])) + + sns.heatmap(df, cmap=colors, ax=ax, xticklabels=False, + cbar=False, vmin=0, vmax=len(colors), **kwargs) + + ax.set_xlabel('Samples') + ax.set_ylabel('') + + return ax + + def plot_waterfall_matched( + self, af, patient_col, group_col, group_order, count=10, ax=None, + figsize=None + ): + """""" + Create a waterfall plot using matched samples from each patient. + + Parameters + ---------- + af : AnnFrame + AnnFrame containing sample annotation data. + patient_col : str + AnnFrame column containing patient information. + group_col : str + AnnFrame column containing sample group information. + group_order : list + List of sample group names. + count : int, default: 10 + Number of top mutated genes to include. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + """""" + df = self.matrix_waterfall_matched(af, patient_col, + group_col, group_order, count=count) + genes = df.index.get_level_values(0).unique().to_list() + + l = reversed(NONSYN_NAMES + ['Multi_Hit', 'None']) + d = {k: v for v, k in enumerate(l)} + df = df.applymap(lambda x: d[x]) + + colors = list(reversed(NONSYN_COLORS + ['k', 'lightgray'])) + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + sns.heatmap(df, cmap=colors, xticklabels=True, cbar=False, ax=ax) + + n = len(group_order) + i = n / 2 + yticks = [] + for gene in genes: + yticks.append(i) + i += n + + ax.set_xlabel('') + ax.set_ylabel('') + ax.set_yticks(yticks) + ax.set_yticklabels(genes) + + # Add horizontal lines. + for i, gene in enumerate(genes, start=1): + ax.axhline(i*n, color='white') + + # Add vertical lines. + for i, sample in enumerate(af.samples, start=1): + ax.axvline(i, color='white') + + return ax + + def matrix_waterfall_matched( + self, af, patient_col, group_col, group_order, count=10 + ): + """""" + Compute a matrix of variant classifications with a shape of + (gene-group pairs, patients). + + Parameters + ---------- + af : AnnFrame + AnnFrame containing sample annotation data. + patient_col : str + AnnFrame column containing patient information. + group_col : str + AnnFrame column containing sample group information. + group_order : list + List of sample group names. + count : int, default: 10 + Number of top mutated genes to include. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + """""" + df = self.matrix_waterfall(count=count) + + genes = df.index + + missing_samples = {} + + for sample in af.samples: + if sample not in df.columns: + missing_samples[sample] = ['None'] * len(genes) + + df = pd.concat( + [df, pd.DataFrame(missing_samples, index=genes)], axis=1) + + df = df[af.samples].T + df = df.merge(af.df[[patient_col, group_col]], + left_index=True, right_index=True) + df = df.reset_index(drop=True) + + temps = [] + + for group in group_order: + temp = df[df[group_col] == group].set_index(patient_col)[genes] + tuples = [(x, group) for x in genes] + mi = pd.MultiIndex.from_tuples(tuples, names=['Gene', 'Group']) + temp.columns = mi + temps.append(temp) + + df = pd.concat(temps, axis=1) + + tuples = [] + + for gene in genes: + for group in group_order: + tuples.append((gene, group)) + + df = df[tuples] + df = df.T + + c = df.applymap(lambda x: 0 if x == 'None' else 1).sort_values( + df.index.to_list(), axis=1, ascending=False).columns + df = df[c] + + return df + + + def to_vcf( + self, fasta=None, ignore_indels=False, cols=None, names=None + ): + """""" + Write the MafFrame to a sorted VcfFrame. + + Converting from MAF to VCF is pretty straightforward for SNVs, but it + can be challenging for INDELs and complex events involving multiple + nucleotides (e.g. 'AAGG' → 'CCCG'). This is because, for the latter + case we need to identify the ""anchor"" nucleotide for each event, + which is crucial for constructing a properly formatted VCF. For + example, a deletion event 'AGT' → '-' in MAF would have to be + converted to 'CAGT' → 'C' in the VCF where 'C' is our anchor + nucleotide. The position should be shifted by one as well. + + In order to tackle this issue, the method makes use of a reference + assembly (i.e. FASTA file). If SNVs are your only concern, then you + do not need a FASTA file and can just set ``ignore_indels`` as True. + If you are going to provide a FASTA file, please make sure to select + the appropriate one (e.g. one that matches the genome assembly). For + example, if your MAF is in hg19/GRCh37, use the 'hs37d5.fa' file + which can be freely downloaded from the 1000 Genomes Project. + + Parameters + ---------- + fasta : str, optional + FASTA file. Required if ``ignore_indels`` is False. + ignore_indels : bool, default: False + If True, do not include INDELs in the VcfFrame. Useful when + a FASTA file is not available. + cols : str or list, optional + Column(s) in the MafFrame which contain additional genotype + data of interest. If provided, these data will be added to + individual sample genotypes (e.g. '0/1:0.23'). + names : str or list, optional + Name(s) to be displayed in the FORMAT field (e.g. AD, AF, DP). + If not provided, the original column name(s) will be displayed. + + Returns + ------- + VcfFrame + VcfFrame object. + + Examples + -------- + + >>> from fuc import pymaf + >>> mf = pymaf.MafFrame.from_file('in.maf') + >>> vf = mf.to_vcf(fasta='hs37d5.fa') + >>> vf = mf.to_vcf(ignore_indels=True) + >>> vf = mf.to_vcf(fasta='hs37d5.fa', cols='i_TumorVAF_WU', names='AF') + """""" + if not ignore_indels and fasta is None: + raise ValueError(""A FASTA file is required when 'ignore_indels' "" + ""argument is False."") + + if cols is None: + cols = [] + if names is None: + names = [] + + if isinstance(cols, str): + cols = [cols] + if isinstance(names, str): + names = [names] + + if cols and not names: + names = cols + if len(cols) != len(names): + raise ValueError(""Arguments 'cols' and 'names' "" + ""have different lengths."") + + # Create the minimal VCF. + index_cols = ['Chromosome', 'Start_Position', + 'Reference_Allele', 'Tumor_Seq_Allele2'] + df = self.df.pivot(index=index_cols, + columns='Tumor_Sample_Barcode', + values='Tumor_Seq_Allele2') + f = lambda x: '0/0' if pd.isnull(x) else '0/1' + df = df.applymap(f) + df.columns.name = None + df = df.reset_index() + df = df.rename(columns={'Chromosome': 'CHROM', + 'Start_Position': 'POS', + 'Reference_Allele': 'REF', + 'Tumor_Seq_Allele2': 'ALT'}) + df['ID'] = '.' + df['QUAL'] = '.' + df['FILTER'] = '.' + df['INFO'] = '.' + df['FORMAT'] = 'GT' + df = df[pyvcf.HEADERS + self.samples] + + # Add requested genotype information. + f = lambda x: '.' if pd.isnull(x) else str(x) + for i, col in enumerate(cols): + _ = self.df.pivot(index=index_cols, + columns='Tumor_Sample_Barcode', + values='i_TumorVAF_WU') + _ = _.reset_index() + _ = _.drop(index_cols, axis=1) + _ = _[self.samples] + _ = _.applymap(f) + df.iloc[:, 9:] = df.iloc[:, 9:] + ':' + _ + df.FORMAT = df.FORMAT + ':' + names[i] + + # Handle INDELs. + l = ['A', 'C', 'G', 'T'] + if ignore_indels: + i = (df.REF.isin(l)) & (df.ALT.isin(l)) + df = df[i] + else: + def one_row(r): + if r.REF in l and r.ALT in l: + return r + region = f'{r.CHROM}:{r.POS-1}-{r.POS-1}' + anchor = common.extract_sequence(fasta, region) + if not anchor: + return r + r.POS = r.POS - 1 + if r.ALT == '-': + r.REF = anchor + r.REF + r.ALT = anchor + elif r.REF == '-': + r.REF = anchor + r.ALT = anchor + r.ALT + else: + r.REF = anchor + r.REF + r.ALT = anchor + r.ALT + return r + df = df.apply(one_row, axis=1) + + # Create the metadata. + meta = [ + '##fileformat=VCFv4.3', + '##source=fuc.api.pymaf.MafFrame.to_vcf', + ] + + # Create the VcfFrame. + vf = pyvcf.VcfFrame(meta, df) + vf = vf.sort() + + return vf + + def to_file(self, fn): + """""" + Write MafFrame to a MAF file. + + Parameters + ---------- + fn : str + MAF file path. + """""" + with open(fn, 'w') as f: + f.write(self.to_string()) + + def to_string(self): + """""" + Render MafFrame to a console-friendly tabular output. + + Returns + ------- + str + String representation of MafFrame. + """""" + return self.df.to_csv(index=False, sep='\t') + + def filter_annot(self, af, expr): + """""" + Filter the MafFrame using sample annotation data. + + Samples are selected by querying the columns of an AnnFrame with a + boolean expression. Samples not present in the MafFrame will be + excluded automatically. + + Parameters + ---------- + af : AnnFrame + AnnFrame containing sample annotation data. + expr : str + Query expression to evaluate. + + Returns + ------- + MafFrame + Filtered MafFrame. + + Examples + -------- + + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> mf = pymaf.MafFrame.from_file('~/fuc-data/tcga-laml/tcga_laml.maf.gz') + >>> af = common.AnnFrame.from_file('~/fuc-data/tcga-laml/tcga_laml_annot.tsv', sample_col=0) + >>> filtered_mf = mf.filter_annot(af, ""FAB_classification == 'M4'"") + """""" + samples = af.df.query(expr).index + i = self.df.Tumor_Sample_Barcode.isin(samples) + df = self.df[i] + mf = self.__class__(df) + return mf + + def filter_indel(self, opposite=False, as_index=False): + """""" + Remove rows with an indel. + + Parameters + ---------- + opposite : bool, default: False + If True, return rows that don't meet the said criteria. + as_index : bool, default: False + If True, return boolean index array instead of MafFrame. + + Returns + ------- + MafFrame or pandas.Series + Filtered MafFrame or boolean index array. + + Examples + -------- + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> mf.filter_indel().df.Variant_Type.unique() + array(['SNP'], dtype=object) + >>> mf.filter_indel(opposite=True).df.Variant_Type.unique() + array(['DEL', 'INS'], dtype=object) + """""" + def one_row(r): + if (len(r.Reference_Allele) == 1 and + len(r.Tumor_Seq_Allele1) == 1 and + len(r.Tumor_Seq_Allele2) == 1 and + '-' not in r.Reference_Allele and + '-' not in r.Tumor_Seq_Allele1 and + '-' not in r.Tumor_Seq_Allele2): + return False + else: + return True + i = ~self.df.apply(one_row, axis=1) + if opposite: + i = ~i + if as_index: + return i + return self.__class__(self.df[i]) + + def variants(self): + """""" + List unique variants in MafFrame. + + Returns + ------- + list + List of unique variants. + + Examples + -------- + + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> mf.variants()[:5] + ['1:1571791:1571791:G:A', '1:1747228:1747228:T:G', '1:2418350:2418350:C:T', '1:3328523:3328523:G:A', '1:3638739:3638739:C:T'] + """""" + if self.df.empty: + return [] + cols = ['Chromosome', 'Start_Position', 'End_Position', 'Reference_Allele', 'Tumor_Seq_Allele2'] + df = self.df.drop_duplicates(cols) + df = df[cols] + df = df.sort_values(cols) + df = df.applymap(str) + s = df.apply(lambda r: r.str.cat(sep=':'), axis=1) + return s.to_list() + + def subset(self, samples, exclude=False): + """""" + Subset MafFrame for specified samples. + + Parameters + ---------- + samples : str, list, or pandas.Series + Sample name or list of names (the order does not matters). + exclude : bool, default: False + If True, exclude specified samples. + + Returns + ------- + MafFrame + Subsetted MafFrame. + + Examples + -------- + + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> mf.shape + (2207, 193) + >>> mf.subset(['TCGA-AB-2988', 'TCGA-AB-2869']).shape + (27, 2) + >>> mf.subset(['TCGA-AB-2988', 'TCGA-AB-2869'], exclude=True).shape + (2180, 191) + """""" + if isinstance(samples, str): + samples = [samples] + elif isinstance(samples, pd.Series): + samples = samples.to_list() + elif isinstance(samples, list): + pass + else: + raise TypeError(f'Incorrect input type: {type(samples)}') + + if exclude: + samples = [x for x in self.samples if x not in samples] + + df = self.df[self.df.Tumor_Sample_Barcode.isin(samples)] + + return self.__class__(df) + + def calculate_concordance(self, a, b, c=None, mode='all'): + """""" + Calculate genotype concordance between two (A, B) or three (A, B, C) + samples. + + This method will return (Ab, aB, AB, ab) for comparison between two + samples and (Abc, aBc, ABc, abC, AbC, aBC, ABC, abc) for three + samples. Note that the former is equivalent to (FP, FN, TP, TN) if + we assume A is the test sample and B is the truth sample. + + Parameters + ---------- + a, b : str or int + Name or index of Samples A and B. + c : str or int, optional + Name or index of Sample C. + mode : {'all', 'snv', 'indel'}, default: 'all' + Determines which variant types should be analyzed: + + - 'all': Include both SNVs and INDELs. + - 'snv': Include SNVs only. + - 'indel': Include INDELs only. + + Returns + ------- + tuple + Four- or eight-element tuple depending on the number of samples. + + See Also + -------- + fuc.api.common.sumstat + Return various summary statistics from (FP, FN, TP, TN). + + Examples + -------- + + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> mf.calculate_concordance('TCGA-AB-2988', 'TCGA-AB-2869') + (15, 12, 0, 2064) + >>> mf.calculate_concordance('TCGA-AB-2988', 'TCGA-AB-2869', 'TCGA-AB-3009') + (15, 12, 0, 42, 0, 0, 0, 2022) + """""" + if mode == 'all': + mf = self.copy() + elif mode == 'snv': + mf = self.filter_indel() + elif mode == 'indel': + mf = self.filter_indel(opposite=True) + else: + raise ValueError(f'Incorrect mode: {mode}.') + + if c is None: + result = self._compare_two(mf, a, b) + else: + result = self._compare_three(mf, a, b, c) + + return result + + def _compare_two(self, mf, a, b): + l = mf.variants() + A = mf.subset(a).variants() + B = mf.subset(b).variants() + + Ab = aB = AB = ab = 0 + + for x in l: + if x in A and x in B: + AB += 1 + elif x in A and x not in B: + Ab += 1 + elif x not in A and x in B: + aB += 1 + else: + ab += 1 + + return (Ab, aB, AB, ab) + + def _compare_three(self, mf, a, b, c): + l = mf.variants() + A = mf.subset(a).variants() + B = mf.subset(b).variants() + C = mf.subset(c).variants() + + Abc = aBc = ABc = abC = AbC = aBC = ABC = abc = 0 + + for x in l: + if (x in A) and (x not in B) and (x not in C): + Abc += 1 + elif (x not in A) and (x in B) and (x not in C): + aBc += 1 + elif (x in A) and (x in B) and (x not in C): + ABc += 1 + elif (x not in A) and (x not in B) and (x in C): + abC += 1 + elif (x in A) and (x not in B) and (x in C): + AbC += 1 + elif (x not in A) and (x in B) and (x in C): + aBC += 1 + elif (x in A) and (x in B) and (x in C): + ABC += 1 + else: + abc += 1 + + return (Abc, aBc, ABc, abC, AbC, aBC, ABC, abc) + + def plot_comparison( + self, a, b, c=None, labels=None, ax=None, figsize=None + ): + """""" + Create a Venn diagram showing genotype concordance between groups. + + This method supports comparison between two groups (Groups A & B) + as well as three groups (Groups A, B, & C). + + Parameters + ---------- + a, b : list + Sample names. The lists must have the same shape. + c : list, optional + Same as above. + labels : list, optional + List of labels to be displayed. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + matplotlib_venn._common.VennDiagram + VennDiagram object. + """""" + if len(a) != len(b): + raise ValueError('Groups A and B have different length.') + if c is not None and len(a) != len(c): + raise ValueError('Group C has unmatched length.') + if labels is None: + if c is None: + labels = ('A', 'B') + else: + labels = ('A', 'B', 'C') + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + venn_kws = dict(ax=ax, alpha=0.5, set_labels=labels) + if c is None: + out = self._plot_comparison_two(a, b, venn_kws) + else: + out = self._plot_comparison_three(a, b, c, venn_kws) + return ax, out + + def _plot_comparison_two(self, a, b, venn_kws): + n = [0, 0, 0, 0] + for i in range(len(a)): + n = [x + y for x, y in zip(n, self.calculate_concordance(a[i], b[i]))] + out = venn2(subsets=n[:-1], **venn_kws) + return out + + def _plot_comparison_three(self, a, b, c, venn_kws): + n = [0, 0, 0, 0, 0, 0, 0, 0] + for i in range(len(a)): + n = [x + y for x, y in zip(n, self.calculate_concordance(a[i], b[i], c[i]))] + out = venn3(subsets=n[:-1], **venn_kws) + return out + + def get_gene_concordance(self, gene, a, b): + """""" + Test whether two samples have the identical mutation profile for + specified gene. + + Parameters + ---------- + gene : str + Name of the gene. + a, b : str + Sample name. + + Returns + ------- + bool + True if the two samples have the same mutation profile. + """""" + df = self.df[self.df.Hugo_Symbol == gene] + df = df[df.Tumor_Sample_Barcode.isin([a, b])] + + # Both samples don't have any mutations. + if df.empty: + return True + + # Only one sample has mutation(s). + if df.Tumor_Sample_Barcode.nunique() == 1: + return False + + p1 = set(df[df.Tumor_Sample_Barcode == a].Protein_Change) + p2 = set(df[df.Tumor_Sample_Barcode == b].Protein_Change) + + return p1 == p2 +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/api/pyvcf.py",".py","237760","6823",""""""" +The pyvcf submodule is designed for working with VCF files. It implements +``pyvcf.VcfFrame`` which stores VCF data as ``pandas.DataFrame`` to allow +fast computation and easy manipulation. The ``pyvcf.VcfFrame`` class also +contains many useful plotting methods such as ``VcfFrame.plot_comparison`` +and ``VcfFrame.plot_tmb``. The submodule strictly adheres to the +standard `VCF specification +`_. + +A typical VCF file contains metadata lines (prefixed with '##'), a header +line (prefixed with '#'), and genotype lines that begin with a chromosome +identifier (e.g. 'chr1'). See the VCF specification above for an example +VCF file. + +Genotype lines usually consist of nine columns for storing variant +information (all fixed and mandatory except for the FORMAT column) plus +additional sample-specific columns for expressing individual genotype calls +(e.g. '0/1'). Missing values are allowed in some cases and can be specified +with a dot ('.'). The first nine columns are: + +.. list-table:: + :header-rows: 1 + + * - No. + - Column + - Description + - Required + - Missing + - Examples + * - 1 + - CHROM + - Chromosome or contig identifier + - ✅ + - ❌ + - 'chr2', '2', 'chrM' + * - 2 + - POS + - 1-based reference position + - ✅ + - ❌ + - 10041, 23042 + * - 3 + - ID + - ';'-separated variant identifiers + - ✅ + - ✅ + - '.', 'rs35', 'rs9;rs53' + * - 4 + - REF + - Reference allele + - ✅ + - ❌ + - 'A', 'GT' + * - 5 + - ALT + - ','-separated alternate alleles + - ✅ + - ❌ + - 'T', 'ACT', 'C,T' + * - 6 + - QUAL + - Phred-scaled quality score for ALT + - ✅ + - ✅ + - '.', 67, 12 + * - 7 + - FILTER + - ';'-separated filters that failed + - ✅ + - ✅ + - '.', 'PASS', 'q10;s50' + * - 8 + - INFO + - ';'-separated information fields + - ✅ + - ✅ + - '.', 'DP=14;AF=0.5;DB' + * - 9 + - FORMAT + - ':'-separated genotype fields + - ❌ + - ❌ + - 'GT', 'GT:AD:DP' + +You will sometimes come across VCF files that have only eight columns, and +do not contain the FORMAT column or sample-specific information. These are +called ""sites-only"" VCF files, and normally represent genetic variation that +has been observed in a large population. Generally, information about the +population of origin should be included in the header. Note that the pyvcf +submodule supports these sites-only VCF files as well. + +There are several reserved keywords in the INFO and FORMAT columns that are +standards across the community. Popular keywords are listed below: + +.. list-table:: + :header-rows: 1 + + * - Column + - Key + - Number + - Type + - Description + * - INFO + - AC + - A + - Integer + - Allele count in genotypes, for each ALT allele, in the same order as listed + * - INFO + - AN + - 1 + - Integer + - Total number of alleles in called genotypes + * - INFO + - AF + - A + - Float + - Allele frequency for each ALT allele in the same order as listed (estimated from primary data, not called genotypes) + * - FORMAT + - AD + - R + - Integer + - Total read depth for each allele + * - FORMAT + - AF + - 1 + - Float + - Allele fraction of the event in the tumor + * - FORMAT + - DP + - 1 + - Integer + - Read depth + +If sample annotation data are available for a given VCF file, use +the :class:`common.AnnFrame` class to import the data. +"""""" + +import os +import re +import sys +import gzip +from copy import deepcopy +import warnings +import tempfile + +from . import pybed, common, pymaf, pybam + +import numpy as np +import pandas as pd +import scipy.stats as stats +import statsmodels.formula.api as smf +from Bio import bgzf +import matplotlib.pyplot as plt +from matplotlib_venn import venn2, venn3 +import seaborn as sns +from pysam import VariantFile, bcftools +from io import StringIO + +HEADERS = { + 'CHROM': str, + 'POS': int, + 'ID': str, + 'REF': str, + 'ALT': str, + 'QUAL': str, + 'FILTER': str, + 'INFO': str, + 'FORMAT': str, +} + +CONTIGS = [ + '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', + '14', '15', '16', '17', '18', '19', '20', '21', '22', 'X', 'Y', 'M', + 'chr1', 'chr2', 'chr3', 'chr4', 'chr5', 'chr6', 'chr7', 'chr8', + 'chr9', 'chr10', 'chr11', 'chr12', 'chr13', 'chr14', 'chr15', + 'chr16', 'chr17', 'chr18', 'chr19', 'chr20', 'chr21', 'chr22', + 'chrX', 'chrY', 'chrM' +] + +# Below are reserved genotype keys copied from Table 2 of the VCF +# specification: https://samtools.github.io/hts-specs/VCFv4.3.pdf + +RESERVED_GENOTYPE_KEYS = { + 'AD': {'number': 'R', 'type': int}, # Read depth for each allele + 'ADF': {'number': 'R', 'type': int}, # Read depth for each allele on the forward strand + 'ADR': {'number': 'R', 'type': int}, # Read depth for each allele on the reverse strand + 'DP': {'number': 1, 'type': int}, # Read depth + 'EC': {'number': 'A', 'type': int}, # Expected alternate allele counts + 'FT': {'number': 1, 'type': str}, # Filter indicating if this genotype was “called” + 'GL': {'number': 'G', 'type': float}, # Genotype likelihoods + 'GP': {'number': 'G', 'type': float}, # Genotype posterior probabilities + 'GQ': {'number': 1, 'type': int}, # Conditional genotype quality + 'GT': {'number': 1, 'type': str}, # Genotype + 'HQ': {'number': 2, 'type': int}, # Haplotype quality + 'MQ': {'number': 1, 'type': int}, # RMS mapping quality + 'PL': {'number': 'G', 'type': int}, # Phred-scaled genotype likelihoods rounded to the closest integer + 'PP': {'number': 'G', 'type': int}, # Phred-scaled genotype posterior probabilities rounded to the closest integer + 'PQ': {'number': 1, 'type': int}, # Phasing quality + 'PS': {'number': 1, 'type': int}, # Phase set +} + +CUSTOM_GENOTYPE_KEYS = { + 'AF': {'number': 1, 'type': float}, # Allele fraction of the event in the tumor +} + +INFO_SPECIAL_KEYS = { + '#AC': ['AC', lambda x: sum([int(x) for x in x.split(',')]), True], + '#AF': ['AF', lambda x: sum([float(x) for x in x.split(',')]), True], +} + +FORMAT_SPECIAL_KEYS = { + '#DP': ['DP', lambda x: int(x), True], + '#AD_REF': ['AD', lambda x: float(x.split(',')[0]), True], + '#AD_ALT': ['AD', lambda x: sum([int(y) for y in x.split(',')[1:]]), True], + '#AD_FRAC_REF': ['AD', lambda x: np.nan if sum([int(y) for y in x.split(',')]) == 0 else int(x.split(',')[0]) / sum([int(y) for y in x.split(',')]), True], + '#AD_FRAC_ALT': ['AD', lambda x: np.nan if sum([int(y) for y in x.split(',')]) == 0 else sum([int(y) for y in x.split(',')[1:]]) / sum([int(y) for y in x.split(',')]), True], +} + +def call( + fasta, bams, regions=None, path=None, min_mq=1, max_depth=250, + dir_path=None, gap_frac=0.002, group_samples=None +): + """""" + Call SNVs and indels from BAM files. + + Under the hood, the method utilizes the bcftool program to call variants. + + Parameters + ---------- + fasta : str + Reference FASTA file. + bams : str or list + One or more input BAM files. Alternatively, you can provide a text + file (.txt, .tsv, .csv, or .list) containing one BAM file per line. + regions : str, list, or pybed.BedFrame, optional + By default (``regions=None``), the method looks at each genomic + position with coverage in BAM files, which can be excruciatingly slow + for large files (e.g. whole genome sequencing). Therefore, use this + argument to only call variants in given regions. Each region must + have the format chrom:start-end and be a half-open interval with + (start, end]. This means, for example, chr1:100-103 will extract + positions 101, 102, and 103. Alternatively, you can provide a BED + file (compressed or uncompressed) or a :class:`pybed.BedFrame` object + to specify regions. Note that the 'chr' prefix in contig names (e.g. + 'chr1' vs. '1') will be automatically added or removed as necessary + to match the input VCF's contig names. + path : str, optional + Output VCF file. Writes to stdout when ``path='-'``. If None is + provided the result is returned as a string. + min_mq : int, default: 1 + Minimum mapping quality for an alignment to be used. + max_depth : int, default: 250 + At a position, read maximally this number of reads per input file. + dir_path : str, optional + By default, intermediate files (likelihoods.bcf, calls.bcf, and + calls.normalized.bcf) will be stored in a temporary directory, which + is automatically deleted after creating final VCF. If you provide a + directory path, intermediate files will be stored there. + gap_frac : float, default: 0.002 + Minimum fraction of gapped reads for calling indels. + group_samples : str, optional + By default, all samples are assumed to come from a single population. + This option allows to group samples into populations and apply the + HWE assumption within but not across the populations. To use this + option, provide a tab-delimited text file with sample names in the + first column and group names in the second column. If + ``group_samples='-'`` is given instead, no HWE assumption is made at + all and single-sample calling is performed. Note that in low coverage + data this inflates the rate of false positives. Therefore, make sure + you know what you are doing. + + Returns + ------- + str + VcfFrame object. + """""" + # Parse input BAM files. + bams = common.parse_list_or_file(bams) + + # Check the 'chr' prefix. + if all([pybam.has_chr_prefix(x) for x in bams]): + chr_prefix = 'chr' + else: + chr_prefix = '' + + # Parse target regions, if provided. + if regions is not None: + if isinstance(regions, str): + regions = [regions] + elif isinstance(regions, list): + pass + elif isinstance(regions, pybed.BedFrame): + regions = regions.to_regions() + else: + raise TypeError(""Incorrect type of argument 'regions'"") + if '.bed' in regions[0]: + bf = pybed.BedFrame.from_file(regions[0]) + regions = bf.to_regions() + else: + regions = common.sort_regions(regions) + regions = [chr_prefix + x.replace('chr', '') for x in regions] + + if dir_path is None: + t = tempfile.TemporaryDirectory() + temp_dir = t.name + else: + temp_dir = dir_path + + # Step 1: Get genotype likelihoods. + args = ['-Ou', '-a', 'AD'] + args += ['-q', str(min_mq)] + args += ['--max-depth', str(max_depth)] + args += ['-f', fasta] + args += ['-F', str(gap_frac)] + args += ['-o', f'{temp_dir}/likelihoods.ubcf'] + if regions is not None: + args += ['-r', ','.join(regions)] + bcftools.mpileup(*(args + bams), catch_stdout=False) + + # Step 2: Call variants. + args = [f'{temp_dir}/likelihoods.ubcf', '-Ou', '-mv'] + args += ['-o', f'{temp_dir}/calls.ubcf'] + if group_samples is not None: + args += ['-G', group_samples] + bcftools.call(*args, catch_stdout=False) + + # Step 3: Normalize indels. + args = [f'{temp_dir}/calls.ubcf', '-Ou', '-f', fasta] + args += ['-o', f'{temp_dir}/calls.normalized.ubcf'] + bcftools.norm(*args, catch_stdout=False) + + # Step 4: Filter variant. + args = [f'{temp_dir}/calls.normalized.ubcf', '-Ov', '--IndelGap', '5'] + results = bcftools.filter(*args) + + if path is None: + return results + elif path == '-': + sys.stdout.write(results) + else: + with open(path, 'w') as f: + f.write(results) + + if dir_path is None: + t.cleanup() + +def rescue_filtered_variants(vfs, format='GT'): + """""" + Rescue filtered variants if they are PASS in at least one of the input + VCF files. + + Parameters + ---------- + vfs : list + List of VcfFrame objects. + + Returns + ------- + VcfFrame + VcfFrame object. + + Examples + -------- + + >>> from fuc import pyvcf + >>> data1 = { + ... 'CHROM': ['chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102], + ... 'ID': ['.', '.', '.'], + ... 'REF': ['G', 'T', 'C'], + ... 'ALT': ['A', 'C', 'T'], + ... 'QUAL': ['.', '.', '.'], + ... 'FILTER': ['PASS', 'weak_evidence', 'PASS'], + ... 'INFO': ['.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT'], + ... 'A': ['0/1', '0/1', '0/1'] + ... } + >>> data2 = { + ... 'CHROM': ['chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102], + ... 'ID': ['.', '.', '.'], + ... 'REF': ['G', 'T', 'C'], + ... 'ALT': ['A', 'C', 'T'], + ... 'QUAL': ['.', '.', '.'], + ... 'FILTER': ['orientation', 'weak_evidence', 'PASS'], + ... 'INFO': ['.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT'], + ... 'B': ['0/1', '0/1', '0/1'] + ... } + >>> data3 = { + ... 'CHROM': ['chr1', 'chr1', 'chr1'], + ... 'POS': [102, 103, 104], + ... 'ID': ['.', '.', '.'], + ... 'REF': ['C', 'T', 'A'], + ... 'ALT': ['T', 'C', 'T'], + ... 'QUAL': ['.', '.', '.'], + ... 'FILTER': ['PASS', 'weak_evidence', 'PASS'], + ... 'INFO': ['.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT'], + ... 'C': ['0/1', '0/1', '0/1'] + ... } + >>> vf1 = pyvcf.VcfFrame.from_dict([], data1) + >>> vf2 = pyvcf.VcfFrame.from_dict([], data2) + >>> vf3 = pyvcf.VcfFrame.from_dict([], data3) + >>> vf1.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A + 0 chr1 100 . G A . PASS . GT 0/1 + 1 chr1 101 . T C . weak_evidence . GT 0/1 + 2 chr1 102 . C T . PASS . GT 0/1 + >>> vf2.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT B + 0 chr1 100 . G A . orientation . GT 0/1 + 1 chr1 101 . T C . weak_evidence . GT 0/1 + 2 chr1 102 . C T . PASS . GT 0/1 + >>> vf3.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT C + 0 chr1 102 . C T . PASS . GT 0/1 + 1 chr1 103 . T C . weak_evidence . GT 0/1 + 2 chr1 104 . A T . PASS . GT 0/1 + >>> rescued_vf = pyvcf.rescue_filtered_variants([vf1, vf2, vf3]) + >>> rescued_vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C + 0 chr1 100 . G A . . . GT 0/1 0/1 ./. + 1 chr1 102 . C T . . . GT 0/1 0/1 0/1 + 2 chr1 104 . A T . . . GT ./. ./. 0/1 + """""" + # Check for duplicate samples. + samples = [] + for vf in vfs: + samples += vf.samples + s = pd.Series(samples) + duplicates = s[s.duplicated()].values + if duplicates: + raise ValueError(f'Duplicate samples found: {duplicates}.') + + dfs = [] + for vf in vfs: + df = vf.df[vf.df.FILTER == 'PASS'] + dfs.append(df[['CHROM', 'POS', 'REF', 'ALT']]) + df = pd.concat(dfs).drop_duplicates() + s = df.apply(lambda r: common.Variant(r.CHROM, r.POS, r.REF, r.ALT), axis=1) + filtered_vfs = [] + for vf in vfs: + i = vf.df.apply(lambda r: common.Variant(r.CHROM, r.POS, r.REF, r.ALT) in s.values, axis=1) + filtered_vf = vf.copy() + filtered_vf.df = vf.df[i] + filtered_vfs.append(filtered_vf) + merged_vf = merge(filtered_vfs, how='outer', format=format) + return merged_vf + +def gt_diploidize(g): + """""" + For given genotype, return its diploid form. + + This method will ignore diploid genotypes (e.g. 0/1) and is therefore + only effective for haploid genotypes (e.g. genotypes from the X + chromosome for males). + + Parameters + ---------- + g : str + Sample genotype. + + Returns + ------- + bool + Diploid genotype. + + See Also + -------- + VcfFrame.diploidize + Diploidize VcfFrame. + + Examples + -------- + + >>> from fuc import pyvcf + >>> pyvcf.gt_diploidize('0') + '0/0' + >>> pyvcf.gt_diploidize('1') + '0/1' + >>> pyvcf.gt_diploidize('.') + './.' + >>> pyvcf.gt_diploidize('1:34') + '0/1:34' + >>> pyvcf.gt_diploidize('0/1:34') + '0/1:34' + >>> pyvcf.gt_diploidize('./.') + './.' + """""" + if gt_ploidy(g) != 1: + return g + gt = g.split(':')[0] + if gt == '.': + return './' + g + else: + return '0/' + g + +def gt_miss(g): + """""" + For given genotype, return True if it has missing value. + + Parameters + ---------- + g : str + Sample genotype. + + Returns + ------- + bool + True if genotype is missing. + + Examples + -------- + + >>> from fuc import pyvcf + >>> pyvcf.gt_miss('0') + False + >>> pyvcf.gt_miss('0/0') + False + >>> pyvcf.gt_miss('0/1') + False + >>> pyvcf.gt_miss('0|0:48:1:51,51') + False + >>> pyvcf.gt_miss('./.:.:.') + True + >>> pyvcf.gt_miss('.:.') + True + >>> pyvcf.gt_miss('.') + True + >>> pyvcf.gt_miss('./.:13,3:16:41:41,0,402') + True + """""" + return '.' in g.split(':')[0] + +def gt_ploidy(g): + """""" + For given genotype, return its ploidy number. + + Parameters + ---------- + g : str + Sample genotype. + + Returns + ------- + int + Ploidy number. + + Examples + -------- + + >>> from fuc import pyvcf + >>> pyvcf.gt_ploidy('1') + 1 + >>> pyvcf.gt_ploidy('.') + 1 + >>> pyvcf.gt_ploidy('0/1') + 2 + >>> pyvcf.gt_ploidy('./.') + 2 + >>> pyvcf.gt_ploidy('0|1') + 2 + >>> pyvcf.gt_ploidy('1|0|1') + 3 + >>> pyvcf.gt_ploidy('0/./1/1') + 4 + """""" + gt = g.split(':')[0] + if '/' in gt: + return gt.count('/') + 1 + elif '|' in gt: + return gt.count('|') + 1 + else: + return 1 + +def gt_polyp(g): + """""" + For given genotype, return True if it is polyploid. + + Parameters + ---------- + g : str + Sample genotype. + + Returns + ------- + bool + True if genotype is polyploid. + + Examples + -------- + + >>> from fuc import pyvcf + >>> pyvcf.gt_polyp('1') + False + >>> pyvcf.gt_polyp('0/1') + False + >>> pyvcf.gt_polyp('0/1/1') + True + >>> pyvcf.gt_polyp('1|0|1') + True + >>> pyvcf.gt_polyp('0/./1/1') + True + """""" + return gt_ploidy(g) > 2 + +def gt_hasvar(g): + """""" + For given genotype, return True if it has variation. + + Parameters + ---------- + g : str + Sample genotype. + + Returns + ------- + bool + True if genotype has variation. + + Examples + -------- + + >>> from fuc import pyvcf + >>> pyvcf.gt_hasvar('0') + False + >>> pyvcf.gt_hasvar('0/0') + False + >>> pyvcf.gt_hasvar('./.') + False + >>> pyvcf.gt_hasvar('1') + True + >>> pyvcf.gt_hasvar('0/1') + True + >>> pyvcf.gt_hasvar('1/2') + True + >>> pyvcf.gt_hasvar('1|0') + True + >>> pyvcf.gt_hasvar('1|2:21:6:23,27') + True + """""" + if g.split(':')[0].replace('/', '').replace( + '|', '').replace('.', '').replace('0', ''): + return True + else: + return False + +def gt_unphase(g): + """""" + For given genotype, return its unphased form. + + Parameters + ---------- + g : str + Sample genotype. + + Returns + ------- + str + Unphased genotype. + + Examples + -------- + + >>> from fuc import pyvcf + >>> pyvcf.gt_unphase('1') + '1' + >>> pyvcf.gt_unphase('0/0') + '0/0' + >>> pyvcf.gt_unphase('0/1') + '0/1' + >>> pyvcf.gt_unphase('0/1:35:4') + '0/1:35:4' + >>> pyvcf.gt_unphase('0|1') + '0/1' + >>> pyvcf.gt_unphase('1|0') + '0/1' + >>> pyvcf.gt_unphase('2|1:2:0:18,2') + '1/2:2:0:18,2' + >>> pyvcf.gt_unphase('.') + '.' + >>> pyvcf.gt_unphase('./.') + './.' + >>> pyvcf.gt_unphase('.|.') + './.' + """""" + l = g.split(':') + gt = l[0] + if '|' not in gt: + return g + if '.' in gt: + return g.replace('|', '/') + l[0] = '/'.join([str(b) for b in sorted([int(a) for a in gt.split('|')])]) + return ':'.join(l) + +def gt_het(g): + """""" + For given genotype, return True if it is heterozygous. + + Parameters + ---------- + g : str + Genotype call. + + Returns + ------- + bool + True if genotype is heterozygous. + + Examples + -------- + + >>> from fuc import pyvcf + >>> pyvcf.gt_het('0/1') + True + >>> pyvcf.gt_het('0/0') + False + >>> pyvcf.gt_het('0|0') + False + >>> pyvcf.gt_het('1|0') + True + """""" + l = g.split(':') + gt = l[0] + if '/' in gt: + gt = gt.split('/') + elif '|' in gt: + gt = gt.split('|') + else: + return False + return gt[0] != gt[1] + +def gt_pseudophase(g): + """""" + For given genotype, return its pseudophased form. + + Parameters + ---------- + g : str + Genotype call. + + Returns + ------- + str + Pseudophased genotype call. + + Examples + -------- + + >>> from fuc import pyvcf + >>> pyvcf.gt_pseudophase('0/1') + '0|1' + >>> pyvcf.gt_pseudophase('0/0:34:10,24') + '0|0:34:10,24' + """""" + l = g.split(':') + l[0] = l[0].replace('/', '|') + return ':'.join(l) + +def has_chr_prefix(file, size=1000): + """""" + Return True if all of the sampled contigs from a VCF file have the + (annoying) 'chr' string. + + For GRCh38, the HLA contigs will be ignored. + + Parameters + ---------- + file : str + VCF file (compressed or uncompressed). + size : int, default: 1000 + Sampling size. + + Returns + ------- + bool + True if the 'chr' string is found. + """""" + n = 0 + vcf = VariantFile(file) + for record in vcf.fetch(): + n += 1 + if record.chrom.startswith('HLA'): + continue + if 'chr' not in record.chrom: + return False + if n > size: + break + vcf.close() + return True + +def merge( + vfs, how='inner', format='GT', sort=True, collapse=False +): + """""" + Merge VcfFrame objects. + + Parameters + ---------- + vfs : list + List of VcfFrames to be merged. Note that the 'chr' prefix in contig + names (e.g. 'chr1' vs. '1') will be automatically added or removed as + necessary to match the contig names of the first VCF. + how : str, default: 'inner' + Type of merge as defined in :meth:`pandas.merge`. + format : str, default: 'GT' + FORMAT subfields to be retained (e.g. 'GT:AD:DP'). + sort : bool, default: True + If True, sort the VcfFrame before returning. + collapse : bool, default: False + If True, collapse duplicate records. + + Returns + ------- + VcfFrame + Merged VcfFrame. + + See Also + -------- + VcfFrame.merge + Merge self with another VcfFrame. + + Examples + -------- + Assume we have the following data: + + >>> from fuc import pyvcf + >>> data1 = { + ... 'CHROM': ['chr1', 'chr1'], + ... 'POS': [100, 101], + ... 'ID': ['.', '.'], + ... 'REF': ['G', 'T'], + ... 'ALT': ['A', 'C'], + ... 'QUAL': ['.', '.'], + ... 'FILTER': ['.', '.'], + ... 'INFO': ['.', '.'], + ... 'FORMAT': ['GT:DP', 'GT:DP'], + ... 'Steven': ['0/0:32', '0/1:29'], + ... 'Sara': ['0/1:24', '1/1:30'], + ... } + >>> data2 = { + ... 'CHROM': ['chr1', 'chr1', 'chr2'], + ... 'POS': [100, 101, 200], + ... 'ID': ['.', '.', '.'], + ... 'REF': ['G', 'T', 'A'], + ... 'ALT': ['A', 'C', 'T'], + ... 'QUAL': ['.', '.', '.'], + ... 'FILTER': ['.', '.', '.'], + ... 'INFO': ['.', '.', '.'], + ... 'FORMAT': ['GT:DP', 'GT:DP', 'GT:DP'], + ... 'Dona': ['./.:.', '0/0:24', '0/0:26'], + ... 'Michel': ['0/1:24', '0/1:31', '0/1:26'], + ... } + >>> vf1 = pyvcf.VcfFrame.from_dict([], data1) + >>> vf2 = pyvcf.VcfFrame.from_dict([], data2) + >>> vf1.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven Sara + 0 chr1 100 . G A . . . GT:DP 0/0:32 0/1:24 + 1 chr1 101 . T C . . . GT:DP 0/1:29 1/1:30 + >>> vf2.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Dona Michel + 0 chr1 100 . G A . . . GT:DP ./.:. 0/1:24 + 1 chr1 101 . T C . . . GT:DP 0/0:24 0/1:31 + 2 chr2 200 . A T . . . GT:DP 0/0:26 0/1:26 + + We can merge the two VcfFrames with ``how='inner'`` (default): + + >>> pyvcf.merge([vf1, vf2]).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven Sara Dona Michel + 0 chr1 100 . G A . . . GT 0/0 0/1 ./. 0/1 + 1 chr1 101 . T C . . . GT 0/1 1/1 0/0 0/1 + + We can also merge with ``how='outer'``: + + >>> pyvcf.merge([vf1, vf2], how='outer').df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven Sara Dona Michel + 0 chr1 100 . G A . . . GT 0/0 0/1 ./. 0/1 + 1 chr1 101 . T C . . . GT 0/1 1/1 0/0 0/1 + 2 chr2 200 . A T . . . GT ./. ./. 0/0 0/1 + + Since both VcfFrames have the DP subfield, we can use ``format='GT:DP'``: + + >>> pyvcf.merge([vf1, vf2], how='outer', format='GT:DP').df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven Sara Dona Michel + 0 chr1 100 . G A . . . GT:DP 0/0:32 0/1:24 ./.:. 0/1:24 + 1 chr1 101 . T C . . . GT:DP 0/1:29 1/1:30 0/0:24 0/1:31 + 2 chr2 200 . A T . . . GT:DP ./.:. ./.:. 0/0:26 0/1:26 + """""" + merged_vf = vfs[0] + for vf in vfs[1:]: + merged_vf = merged_vf.merge(vf, how=how, format=format, sort=sort, + collapse=collapse) + return merged_vf + +def row_hasindel(r): + """""" + For given row, return True if it has indel. + + Parameters + ---------- + r : pandas.Series + VCF row. + + Returns + ------- + bool + True if the row has an indel. + + Examples + -------- + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102, 103], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['G', 'CT', 'A', 'C'], + ... 'ALT': ['A', 'C', 'C,AT', 'A'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT'], + ... 'Steven': ['0/1', '0/1', '1/2', '0/1'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . G A . . . GT 0/1 + 1 chr1 101 . CT C . . . GT 0/1 + 2 chr1 102 . A C,AT . . . GT 1/2 + 3 chr1 103 . C A . . . GT 0/1 + >>> vf.df.apply(pyvcf.row_hasindel, axis=1) + 0 False + 1 True + 2 True + 3 False + dtype: bool + """""" + ref_has = len(r['REF']) > 1 + alt_has = max([len(x) for x in r['ALT'].split(',')]) > 1 + return ref_has or alt_has + + +def row_computeinfo(r, key, decimals=3): + """""" + For given row, return AC/AN/AF calculation for INFO column. + + Parameters + ---------- + r : pandas.Series + VCF row. + key : {'AC', 'AN', 'AF'} + INFO key. + decimals : int, default: 3 + Number of decimals to display for AF. + + Returns + ------- + str + Requested INFO data. + + Example + ------- + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chrX'], + ... 'POS': [100, 101, 102, 100], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['G', 'T', 'A', 'A'], + ... 'ALT': ['A', 'C', 'T,G', 'G'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.'], + ... 'FORMAT': ['GT:DP', 'GT', 'GT', 'GT'], + ... 'A': ['1|0:29', '0|0', '1|0', '0'], + ... 'B': ['1/1:34', './.', '0/0', '0/1'], + ... 'C': ['0/0:23', '0/0', '1/2', '1'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C + 0 chr1 100 . G A . . . GT:DP 1|0:29 1/1:34 0/0:23 + 1 chr1 101 . T C . . . GT 0|0 ./. 0/0 + 2 chr1 102 . A T,G . . . GT 1|0 0/0 1/2 + 3 chrX 100 . A G . . . GT 0 0/1 1 + >>> pyvcf.row_computeinfo(vf.df.iloc[0, :], 'AC') + '3' + >>> pyvcf.row_computeinfo(vf.df.iloc[0, :], 'AN') + '6' + >>> pyvcf.row_computeinfo(vf.df.iloc[0, :], 'AF') + '0.500' + >>> pyvcf.row_computeinfo(vf.df.iloc[1, :], 'AC') + '0' + >>> pyvcf.row_computeinfo(vf.df.iloc[1, :], 'AN') + '4' + >>> pyvcf.row_computeinfo(vf.df.iloc[1, :], 'AF') + '0.000' + >>> pyvcf.row_computeinfo(vf.df.iloc[2, :], 'AC') + '2,1' + >>> pyvcf.row_computeinfo(vf.df.iloc[2, :], 'AN') + '6' + >>> pyvcf.row_computeinfo(vf.df.iloc[2, :], 'AF') + '0.333,0.167' + >>> pyvcf.row_computeinfo(vf.df.iloc[3, :], 'AC') + '2' + >>> pyvcf.row_computeinfo(vf.df.iloc[3, :], 'AN') + '4' + >>> pyvcf.row_computeinfo(vf.df.iloc[3, :], 'AF') + '0.500' + """""" + def get_ac(r): + def one_gt(g, i): + gt = g.split(':')[0] + if '/' in gt: + l = gt.split('/') + else: + l = gt.split('|') + return l.count(str(i + 1)) + counts = [] + for i, allele in enumerate(r.ALT.split(',')): + count = r[9:].apply(one_gt, args=(i, )) + counts.append(sum(count)) + return counts + + def get_an(r): + def one_gt(g): + if '.' in g: + return 0 + else: + return gt_ploidy(g) + return r[9:].apply(one_gt).sum() + + def get_af(r): + return [x / get_an(r) for x in get_ac(r)] + + methods = {'AC': get_ac, 'AN': get_an, 'AF': get_af} + + results = methods[key](r) + + if key == 'AC': + results = ','.join([str(x) for x in results]) + elif key == 'AN': + results = str(results) + else: + results = ','.join([f'{x:.{decimals}f}' for x in results]) + + return results + +def row_parseinfo(r, key): + """""" + For given row, return requested data from INFO column. + + Parameters + ---------- + r : pandas.Series + VCF row. + key : str + INFO key. + + Returns + ------- + str + Requested INFO data. Empty string if the key is not found. + + Examples + -------- + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102, 103], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['G', 'T', 'A', 'C'], + ... 'ALT': ['A', 'C', 'T', 'A'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': ['DB;AC=0', 'DB;H2;AC=1', 'DB;H2;AC=1', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT'], + ... 'Steven': ['0/0', '0/1', '0/1', '0/0'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . G A . . DB;AC=0 GT 0/0 + 1 chr1 101 . T C . . DB;H2;AC=1 GT 0/1 + 2 chr1 102 . A T . . DB;H2;AC=1 GT 0/1 + 3 chr1 103 . C A . . . GT 0/0 + >>> vf.df.apply(pyvcf.row_parseinfo, args=('AC',), axis=1) + 0 0 + 1 1 + 2 1 + 3 + dtype: object + """""" + result = '' + for field in r.INFO.split(';'): + if field.startswith(f'{key}='): + result = field[len(key)+1:] + return result + +def row_phased(r): + """""" + For given row, return True if all genotypes are phased. + + Parameters + ---------- + r : pandas.Series + VCF row. + + Returns + ------- + bool + True if the row is fully phased. + + Examples + -------- + + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102], + ... 'ID': ['.', '.', '.'], + ... 'REF': ['G', 'T', 'A'], + ... 'ALT': ['A', 'C', 'T'], + ... 'QUAL': ['.', '.', '.'], + ... 'FILTER': ['.', '.', '.'], + ... 'INFO': ['.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT'], + ... 'A': ['1|1', '0/0', '1|0'], + ... 'B': ['1|0', '0/1', '1/0'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B + 0 chr1 100 . G A . . . GT 1|1 1|0 + 1 chr1 101 . T C . . . GT 0/0 0/1 + 2 chr1 102 . A T . . . GT 1|0 1/0 + >>> vf.df.apply(pyvcf.row_phased, axis=1) + 0 True + 1 False + 2 False + dtype: bool + """""" + def one_gt(g): + return '|' in g.split(':')[0] + return r[9:].apply(one_gt).all() + +def row_updateinfo(r, key, value, force=True, missing=False): + """""" + For given row, return updated data from INFO column. + + Parameters + ---------- + r : pandas.Series + VCF row. + key : str + INFO key. + value : str + New value to be assigned. + force : bool, default: True + If True, overwrite any existing data. + missing : bool, default: False + By default (``missing=False``), the method will not update INFO field + if there is missing value ('.'). Setting ``missing=True`` will stop + this behavior. + + Returns + ------- + str + New INFO field. + + Examples + -------- + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102], + ... 'ID': ['.', '.', '.'], + ... 'REF': ['G', 'T', 'A'], + ... 'ALT': ['A', 'C', 'T'], + ... 'QUAL': ['.', '.', '.'], + ... 'FILTER': ['.', '.', '.'], + ... 'INFO': ['DB;AC=1', 'DB', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT'], + ... 'A': ['0/1', '1/1', '0/0'], + ... 'B': ['0/0', '0/1', '0/1'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B + 0 chr1 100 . G A . . DB;AC=1 GT 0/1 0/0 + 1 chr1 101 . T C . . DB GT 1/1 0/1 + 2 chr1 102 . A T . . . GT 0/0 0/1 + >>> pyvcf.row_updateinfo(vf.df.iloc[0, :], 'AC', '100') + 'DB;AC=100' + >>> pyvcf.row_updateinfo(vf.df.iloc[0, :], 'AC', '100', force=False) + 'DB;AC=1' + >>> pyvcf.row_updateinfo(vf.df.iloc[1, :], 'AC', '100') + 'DB;AC=100' + >>> pyvcf.row_updateinfo(vf.df.iloc[1, :], 'AC', '100', force=False) + 'DB;AC=100' + >>> pyvcf.row_updateinfo(vf.df.iloc[2, :], 'AC', '100') + '.' + >>> pyvcf.row_updateinfo(vf.df.iloc[2, :], 'AC', '100', force=False) + '.' + >>> pyvcf.row_updateinfo(vf.df.iloc[2, :], 'AC', '100', missing=True) + 'AC=100' + """""" + data = f'{key}={value}' + + if not missing and r.INFO == '.': + return r.INFO + + fields = r.INFO.split(';') + found = False + + for i, field in enumerate(fields): + if field.startswith(f'{key}='): + found = True + if force: + fields[i] = data + else: + pass + break + + if not found: + if r.INFO == '.': + fields = [data] + else: + fields.append(data) + + return ';'.join(fields) + +def row_missval(r): + """""" + For given row, return formatted missing genotype. + + Parameters + ---------- + r : pandas.Series + VCF row. + + Returns + ------- + str + Missing value. + + Examples + -------- + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chrX'], + ... 'POS': [100, 101, 102, 100], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['G', 'T', 'A', 'C'], + ... 'ALT': ['A', 'C', 'T', 'A'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.'], + ... 'FORMAT': ['GT', 'GT:AD', 'GT:AD:DP', 'GT'], + ... 'Steven': ['0/1', '0/1:14,15', '0/1:13,19:32', '0/1'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . G A . . . GT 0/1 + 1 chr1 101 . T C . . . GT:AD 0/1:14,15 + 2 chr1 102 . A T . . . GT:AD:DP 0/1:13,19:32 + 3 chrX 100 . C A . . . GT 0/1 + >>> vf.df.apply(pyvcf.row_missval, axis=1) + 0 ./. + 1 ./.:. + 2 ./.:.:. + 3 . + dtype: object + """""" + if 'X' in r.CHROM or 'Y' in r.CHROM: + m = '.' + else: + m = './.' + for i in range(1, len(r.FORMAT.split(':'))): + m += ':.' + return m + +def simulate_genotype( + p=0.5, noise_scale=0.05, dp_show=True, dp_loc=30, dp_scale=10, + ad_show=True, ad_loc=0.5, ad_scale=0.05, af_show=True +): + lower, upper = 0, 1 + mu, sigma = p, noise_scale + X = stats.truncnorm((lower - mu) / sigma, (upper - mu) / sigma, loc=mu, scale=sigma) + has_var = np.random.binomial(1, X.rvs(1)) == 1 + + if has_var: + result = '0/1' + else: + result = '0/0' + + dp = np.random.normal(loc=dp_loc, scale=dp_scale) + dp = round(abs(dp)) + + if has_var: + alt = round(abs(np.random.normal(loc=ad_loc, scale=ad_scale)) * dp) + ref = dp - alt + ad = f'{ref},{alt}' + else: + ad = f'{dp},0' + + if has_var: + af = round(alt / (ref + alt), 3) + else: + af = 0 + + if dp_show: + result += f':{dp}' + + if ad_show: + result += f':{ad}' + + if af_show: + result += f':{af}' + + return result + +def simulate_sample( + n, p=0.5, noise_scale=0.1, dp_show=True, dp_loc=30, dp_scale=10, + ad_show=True, ad_loc=0.5, ad_scale=0.05, af_show=True +): + l = [] + for i in range(n): + genotype = simulate_genotype( + p=p, noise_scale=noise_scale, dp_show=dp_show, + dp_loc=dp_loc, dp_scale=dp_scale, ad_show=ad_show, + ad_loc=ad_loc, ad_scale=ad_scale + ) + l.append(genotype) + return l + +def slice(file, regions, path=None): + """""" + Slice a VCF file for specified regions. + + Parameters + ---------- + file : str + Input VCF file must be already BGZF compressed (.gz) and indexed + (.tbi) to allow random access. + regions : str, list, or pybed.BedFrame + One or more regions to be sliced. Each region must have the format + chrom:start-end and be a half-open interval with (start, end]. This + means, for example, chr1:100-103 will extract positions 101, 102, and + 103. Alternatively, you can provide a BED file (compressed or + uncompressed) to specify regions. Note that the 'chr' prefix in + contig names (e.g. 'chr1' vs. '1') will be automatically added or + removed as necessary to match the input VCF's contig names. + path : str, optional + Output VCF file. Writes to stdout when ``path='-'``. If None is + provided the result is returned as a string. + + Returns + ------- + None or str + If ``path`` is None, returns the resulting VCF format as a string. + Otherwise returns None. + """""" + if isinstance(regions, str): + regions = [regions] + + if isinstance(regions, pybed.BedFrame): + regions = regions.to_regions() + elif isinstance(regions, list): + if '.bed' in regions[0]: + regions = pybed.BedFrame.from_file(regions[0]).to_regions() + else: + regions = common.sort_regions(regions) + else: + raise TypeError('Incorrect regions type') + + if has_chr_prefix(file): + regions = common.update_chr_prefix(regions, mode='add') + else: + regions = common.update_chr_prefix(regions, mode='remove') + + vcf = VariantFile(file) + + if path is None: + data = '' + data += str(vcf.header) + for region in regions: + chrom, start, end = common.parse_region(region) + if np.isnan(start): + start = None + if np.isnan(end): + end = None + for record in vcf.fetch(chrom, start, end): + data += str(record) + else: + data = None + output = VariantFile(path, 'w', header=vcf.header) + for region in regions: + chrom, start, end = common.parse_region(region) + for record in vcf.fetch(chrom, start, end): + output.write(record) + output.close() + + vcf.close() + + return data + +def split(vcf, clean=True): + """""" + Split VcfFrame by individual. + + Parameters + ---------- + vcf : str or VcfFrame + VCF file or VcfFrame to be split. + clean : bool, default: True + If True, only return variants present in each individual. In other + words, setting this as False will make sure that all individuals + have the same number of variants. + + Returns + ------- + list + List of individual VcfFrames. + + Examples + -------- + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1'], + ... 'POS': [100, 101], + ... 'ID': ['.', '.'], + ... 'REF': ['G', 'T'], + ... 'ALT': ['A', 'C'], + ... 'QUAL': ['.', '.'], + ... 'FILTER': ['.', '.'], + ... 'INFO': ['.', '.'], + ... 'FORMAT': ['GT', 'GT'], + ... 'A': ['0/1', '0/0'], + ... 'B': ['0/1', '0/1'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict(['##fileformat=VCFv4.3'], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B + 0 chr1 100 . G A . . . GT 0/1 0/1 + 1 chr1 101 . T C . . . GT 0/0 0/1 + >>> vfs = pyvcf.split(vf) + >>> vfs[0].df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A + 0 chr1 100 . G A . . . GT 0/1 + >>> vfs = pyvcf.split(vf, clean=False) + >>> vfs[0].df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A + 0 chr1 100 . G A . . . GT 0/1 + 1 chr1 101 . T C . . . GT 0/0 + """""" + # Parse the input VCF. + if isinstance(vcf, str): + vf = VcfFrame.from_file(vcf) + else: + vf = vcf + + vfs = [] + + for sample in vf.samples: + temp_vf = vf.subset(sample) + if clean: + temp_vf = temp_vf.filter_sampall() + vfs.append(temp_vf) + + return vfs + +def plot_af_correlation(vf1, vf2, ax=None, figsize=None): + """""" + Create a scatter plot showing the correlation of allele frequency between + two VCF files. + + This method will exclude the following sites: + + - non-onverlapping sites + - multiallelic sites + - sites with one or more missing genotypes + + Parameters + ---------- + vf1, vf2 : VcfFrame + VcfFrame objects to be compared. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + Examples + -------- + .. plot:: + :context: close-figs + + >>> from fuc import pyvcf, common + >>> import matplotlib.pyplot as plt + >>> data1 = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102, 103, 104, 105], + ... 'ID': ['.', '.', '.', '.', '.', '.'], + ... 'REF': ['G', 'T', 'G', 'T', 'A', 'C'], + ... 'ALT': ['A', 'C', 'C', 'G,A', 'C', 'T'], + ... 'QUAL': ['.', '.', '.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.', '.', '.'], + ... 'FORMAT': ['GT:DP', 'GT', 'GT', 'GT', 'GT', 'GT'], + ... 'A': ['0/1:30', '0/0', '1/1', '0/1', '1/1', '0/1'], + ... 'B': ['0/0:30', '0/0', '0/1', '0/1', '1/1', '0/1'], + ... 'C': ['1/1:30', '0/0', '1/1', '0/1', '1/1', '0/1'], + ... 'D': ['0/0:30', '0/0', '0/0', '0/0', '1/1', '0/1'], + ... 'E': ['0/0:30', '0/0', '0/0', '1/2', '1/1', '0/1'], + ... } + >>> vf1 = pyvcf.VcfFrame.from_dict([], data1) + >>> data2 = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chr1', 'chr1'], + ... 'POS': [101, 102, 103, 104, 105], + ... 'ID': ['.', '.', '.', '.', '.'], + ... 'REF': ['T', 'G', 'T', 'A', 'C'], + ... 'ALT': ['C', 'C', 'G,A', 'C', 'T'], + ... 'QUAL': ['.', '.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT', 'GT'], + ... 'F': ['0/0', '0/1', '0/1', '1/1', '0/0'], + ... 'G': ['0/0', '0/1', '0/1', '1/1', './.'], + ... 'H': ['0/0', '0/1', '0/1', '1/1', '1/1'], + ... 'I': ['0/0', '0/1', '0/0', '1/1', '1/1'], + ... 'J': ['0/0', '0/1', '1/2', '1/1', '0/1'], + ... } + >>> vf2 = pyvcf.VcfFrame.from_dict([], data2) + >>> pyvcf.plot_af_correlation(vf1, vf2) + >>> plt.tight_layout() + """""" + def one_gt(g): + alleles = g.split(':')[0].split('/') + alleles = [x for x in alleles if x != '0'] + return len(alleles) + + def one_row(r): + locus = f'{r.CHROM}-{r.POS}-{r.REF}-{r.ALT}' + ac = r[9:].apply(one_gt).sum() + if 'X' in r.CHROM or 'Y' in r.CHROM: + total = len(r[9:]) + else: + total = len(r[9:]) * 2 + af = ac / total + return pd.Series([locus, af]) + + s1 = vf1.filter_multialt().filter_empty(threshold=1).df.apply(one_row, axis=1) + s2 = vf2.filter_multialt().filter_empty(threshold=1).df.apply(one_row, axis=1) + + s1.columns = ['Locus', 'First'] + s2.columns = ['Locus', 'Second'] + + s1 = s1.set_index('Locus') + s2 = s2.set_index('Locus') + + df = pd.concat([s1, s2], axis=1).dropna() + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + sns.scatterplot(data=df, x='First', y='Second', ax=ax) + + return ax + +class VcfFrame: + """""" + Class for storing VCF data. + + Sites-only VCF files are supported. + + Parameters + ---------- + meta : list + List of metadata lines. + df : pandas.DataFrame + DataFrame containing VCF data. + + See Also + -------- + VcfFrame.from_dict + Construct VcfFrame from a dict of array-like or dicts. + VcfFrame.from_file + Construct VcfFrame from a VCF file. + VcfFrame.from_string + Construct VcfFrame from a string. + + Examples + -------- + Constructing VcfFrame from pandas DataFrame: + + >>> from fuc import pyvcf + >>> import pandas as pd + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102], + ... 'ID': ['.', '.', '.',], + ... 'REF': ['G', 'T', 'A'], + ... 'ALT': ['A', 'C', 'T'], + ... 'QUAL': ['.', '.', '.'], + ... 'FILTER': ['.', '.', '.'], + ... 'INFO': ['.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT'], + ... 'Steven': ['0/1', '0/1', '0/1'], + ... } + >>> df = pd.DataFrame(data) + >>> vf = pyvcf.VcfFrame(['##fileformat=VCFv4.3'], df) + >>> vf.meta + ['##fileformat=VCFv4.3'] + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . G A . . . GT 0/1 + 1 chr1 101 . T C . . . GT 0/1 + 2 chr1 102 . A T . . . GT 0/1 + """""" + + def _check_df(self, df): + df = df.reset_index(drop=True) + headers = HEADERS.copy() + # Handle ""sites-only"" VCF. + if 'FORMAT' not in df.columns: + del headers['FORMAT'] + if set(df.columns) != set(headers): + raise ValueError(""The input appears to be a sites-only VCF "" + ""because it's missing the FORMAT column; "" + ""however, it contains one or more incorrect "" + f""columns: {df.columns.to_list()}."") + df = df.astype(headers) + return df + + def __init__(self, meta, df): + self._meta = meta + self._df = self._check_df(df) + + @property + def meta(self): + """"""list : List of metadata lines."""""" + return self._meta + + @meta.setter + def meta(self, value): + self._meta = value + + @property + def df(self): + """"""pandas.DataFrame : DataFrame containing VCF data."""""" + return self._df + + @df.setter + def df(self, value): + self._df = self._check_df(value) + + @property + def samples(self): + """"""list : List of sample names."""""" + return self.df.columns[9:].to_list() + + @property + def shape(self): + """"""tuple : Dimensionality of VcfFrame (variants, samples)."""""" + return (self.df.shape[0], len(self.samples)) + + @property + def contigs(self): + """"""list : List of contig names."""""" + return list(self.df.CHROM.unique()) + + @property + def has_chr_prefix(self): + """"""bool : Whether the (annoying) 'chr' string is found."""""" + for contig in self.contigs: + if 'chr' in contig: + return True + return False + + @property + def sites_only(self): + """"""bool : Whether the VCF is sites-only."""""" + return not self.samples or 'FORMAT' not in self.df.columns + + @property + def phased(self): + """""" + Return True if every genotype in VcfFrame is haplotype phased. + + Returns + ------- + bool + If VcfFrame is fully phased, return True, if not return False. + Also return False if VcfFrame is empty. + + Examples + -------- + + >>> from fuc import pyvcf + >>> data1 = { + ... 'CHROM': ['chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102], + ... 'ID': ['.', '.', '.'], + ... 'REF': ['G', 'T', 'A'], + ... 'ALT': ['A', 'C', 'T'], + ... 'QUAL': ['.', '.', '.'], + ... 'FILTER': ['.', '.', '.'], + ... 'INFO': ['.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT'], + ... 'A': ['1|1', '0|0', '1|0'], + ... 'B': ['1|0', '0|1', '1|0'], + ... } + >>> vf1 = pyvcf.VcfFrame.from_dict([], data1) + >>> vf1.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B + 0 chr1 100 . G A . . . GT 1|1 1|0 + 1 chr1 101 . T C . . . GT 0|0 0|1 + 2 chr1 102 . A T . . . GT 1|0 1|0 + >>> vf1.phased + True + >>> data2 = { + ... 'CHROM': ['chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102], + ... 'ID': ['.', '.', '.'], + ... 'REF': ['G', 'T', 'A'], + ... 'ALT': ['A', 'C', 'T'], + ... 'QUAL': ['.', '.', '.'], + ... 'FILTER': ['.', '.', '.'], + ... 'INFO': ['.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT'], + ... 'C': ['1|1', '0/0', '1|0'], + ... 'D': ['1|0', '0/1', '1|0'], + ... } + >>> vf2 = pyvcf.VcfFrame.from_dict([], data2) + >>> vf2.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT C D + 0 chr1 100 . G A . . . GT 1|1 1|0 + 1 chr1 101 . T C . . . GT 0/0 0/1 + 2 chr1 102 . A T . . . GT 1|0 1|0 + >>> vf2.phased + False + """""" + if self.empty: + return False + s = self.df.apply(row_phased, axis=1) + return s.all() + + @property + def empty(self): + """""" + Indicator whether VcfFrame is empty. + + Returns + ------- + bool + If VcfFrame is empty, return True, if not return False. + + Examples + -------- + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr2'], + ... 'POS': [100, 101], + ... 'ID': ['.', '.'], + ... 'REF': ['G', 'T'], + ... 'ALT': ['A', 'C'], + ... 'QUAL': ['.', '.'], + ... 'FILTER': ['.', '.'], + ... 'INFO': ['.', '.'], + ... 'FORMAT': ['GT', 'GT'], + ... 'A': ['0/1', '1/1'] + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A + 0 chr1 100 . G A . . . GT 0/1 + 1 chr2 101 . T C . . . GT 1/1 + >>> vf.df = vf.df[0:0] + >>> vf.df + Empty DataFrame + Columns: [CHROM, POS, ID, REF, ALT, QUAL, FILTER, INFO, FORMAT, A] + Index: [] + >>> vf.empty + True + """""" + return self.df.empty + + def add_af(self, decimals=3): + """""" + Compute AF from AD and then add it to the FORMAT field. + + This method will compute allele fraction for each ALT allele in the + same order as listed. + + Parameters + ---------- + decimals : int, default: 3 + Number of decimals to display. + + Returns + ------- + VcfFrame + Updated VcfFrame object. + + Examples + -------- + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102, 103], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['A', 'G', 'A', 'C'], + ... 'ALT': ['C', 'T', 'G', 'G,A'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.'], + ... 'FORMAT': ['GT:AD', 'GT:AD', 'GT', 'GT:AD'], + ... 'A': ['0/1:12,15', '0/0:32,1', '0/1', './.:.'], + ... 'B': ['0/1:13,17', '0/1:14,15', './.', '1/2:0,11,17'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B + 0 chr1 100 . A C . . . GT:AD 0/1:12,15 0/1:13,17 + 1 chr1 101 . G T . . . GT:AD 0/0:32,1 0/1:14,15 + 2 chr1 102 . A G . . . GT 0/1 ./. + 3 chr1 103 . C G,A . . . GT:AD ./.:. 1/2:0,11,17 + >>> vf.add_af().df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B + 0 chr1 100 . A C . . . GT:AD:AF 0/1:12,15:0.444,0.556 0/1:13,17:0.433,0.567 + 1 chr1 101 . G T . . . GT:AD:AF 0/0:32,1:0.970,0.030 0/1:14,15:0.483,0.517 + 2 chr1 102 . A G . . . GT:AF 0/1:. ./.:. + 3 chr1 103 . C G,A . . . GT:AD:AF ./.:.:. 1/2:0,11,17:0.000,0.393,0.607 + """""" + def one_row(r): + try: + i = r.FORMAT.split(':').index('AD') + except ValueError: + i = None + + def one_gt(g): + if i is None: + ad = None + else: + ad = g.split(':')[i] + + if ad is None or ad == '.': + af = '.' + else: + depths = [int(x) for x in ad.split(',')] + total = sum(depths) + if total == 0: + af = '.' + else: + af = ','.join([f'{x/total:.{decimals}f}' for x in depths]) + + return f'{g}:{af}' + + r.iloc[9:] = r.iloc[9:].apply(one_gt) + r.FORMAT += ':AF' + + return r + + df = self.df.apply(one_row, axis=1) + + return self.__class__(self.copy_meta(), df) + + def add_dp(self): + """""" + Compute DP using AD and add it to the FORMAT field. + + Returns + ------- + VcfFrame + Updated VcfFrame. + + Examples + -------- + Assume we have the following data: + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr2', 'chr2'], + ... 'POS': [100, 100, 200, 200], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['A', 'A', 'C', 'C'], + ... 'ALT': ['C', 'T', 'G', 'G,A'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.'], + ... 'FORMAT': ['GT:AD', 'GT:AD', 'GT:AD', 'GT:AD'], + ... 'Steven': ['0/1:12,15', '0/0:32,1', '0/1:16,12', './.:.'], + ... 'Sara': ['0/1:13,17', '0/1:14,15', './.:.', '1/2:0,11,17'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven Sara + 0 chr1 100 . A C . . . GT:AD 0/1:12,15 0/1:13,17 + 1 chr1 100 . A T . . . GT:AD 0/0:32,1 0/1:14,15 + 2 chr2 200 . C G . . . GT:AD 0/1:16,12 ./.:. + 3 chr2 200 . C G,A . . . GT:AD ./.:. 1/2:0,11,17 + + We can add the DP subfield to our genotype data: + + >>> vf.add_dp().df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven Sara + 0 chr1 100 . A C . . . GT:AD:DP 0/1:12,15:27 0/1:13,17:30 + 1 chr1 100 . A T . . . GT:AD:DP 0/0:32,1:33 0/1:14,15:29 + 2 chr2 200 . C G . . . GT:AD:DP 0/1:16,12:28 ./.:.:. + 3 chr2 200 . C G,A . . . GT:AD:DP ./.:.:. 1/2:0,11,17:28 + """""" + def outfunc(r): + i = r.FORMAT.split(':').index('AD') + def infunc(x): + ad = x.split(':')[i].split(',') + dp = 0 + for depth in ad: + if depth == '.': + return f'{x}:.' + dp += int(depth) + return f'{x}:{dp}' + r.iloc[9:] = r.iloc[9:].apply(infunc) + r.FORMAT += ':DP' + return r + df = self.df.apply(outfunc, axis=1) + vf = self.__class__(self.copy_meta(), df) + return vf + + def add_flag(self, flag, order='last', index=None): + """""" + Add the given flag to the INFO field. + + The default behavior is to add the flag to all rows in the VcfFrame. + + Parameters + ---------- + flag : str + INFO flag. + order : {'last', 'first', False}, default: 'last' + Determines the order in which the flag will be added. + + - ``last`` : Add to the end of the list. + - ``first`` : Add to the beginning of the list. + - ``False`` : Overwrite the existing field. + + index : list or pandas.Series, optional + Boolean index array indicating which rows should be updated. + + Returns + ------- + VcfFrame + Updated VcfFrame. + + Examples + -------- + Assume we have the following data: + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102, 103], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['G', 'T', 'A', 'C'], + ... 'ALT': ['A', 'C', 'T', 'A'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': ['.', 'DB', 'DB', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT'], + ... 'Steven': ['0/0', '0/1', '0/1', '1/1'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . G A . . . GT 0/0 + 1 chr1 101 . T C . . DB GT 0/1 + 2 chr1 102 . A T . . DB GT 0/1 + 3 chr1 103 . C A . . . GT 1/1 + + We can add the SOMATIC flag to the INFO field: + + >>> vf.add_flag('SOMATIC').df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . G A . . SOMATIC GT 0/0 + 1 chr1 101 . T C . . DB;SOMATIC GT 0/1 + 2 chr1 102 . A T . . DB;SOMATIC GT 0/1 + 3 chr1 103 . C A . . SOMATIC GT 1/1 + + Setting ``order='first'`` will append the flag at the beginning: + + >>> vf.add_flag('SOMATIC', order='first').df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . G A . . SOMATIC GT 0/0 + 1 chr1 101 . T C . . SOMATIC;DB GT 0/1 + 2 chr1 102 . A T . . SOMATIC;DB GT 0/1 + 3 chr1 103 . C A . . SOMATIC GT 1/1 + + Setting ``order=False`` will overwrite the INFO field: + + >>> vf.add_flag('SOMATIC', order=False).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . G A . . SOMATIC GT 0/0 + 1 chr1 101 . T C . . SOMATIC GT 0/1 + 2 chr1 102 . A T . . SOMATIC GT 0/1 + 3 chr1 103 . C A . . SOMATIC GT 1/1 + + We can also specify which rows should be updated: + + >>> vf.add_flag('SOMATIC', index=[True, True, False, False]).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . G A . . SOMATIC GT 0/0 + 1 chr1 101 . T C . . DB;SOMATIC GT 0/1 + 2 chr1 102 . A T . . DB GT 0/1 + 3 chr1 103 . C A . . . GT 1/1 + """""" + if index is None: + index = [True for i in range(self.shape[0])] + def f(r): + if not index[r.name]: + return r + if r.INFO == '.': + r.INFO = flag + elif not order: + r.INFO = flag + elif order == 'first': + r.INFO = f'{flag};{r.INFO}' + else: + r.INFO += f';{flag}' + return r + df = self.df.apply(f, axis=1) + vf = self.__class__(self.copy_meta(), df) + return vf + + def collapse(self): + """""" + Collapse duplicate records in the VcfFrame. + + Duplicate records have the identical values for CHROM, POS, and REF. + They can result from merging two VCF files. + + .. note:: + The method will sort the order of ALT alleles. + + Returns + ------- + VcfFrame + Collapsed VcfFrame. + + Examples + -------- + Assume we have the following data: + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr2', 'chr2'], + ... 'POS': [100, 100, 200, 200], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['A', 'A', 'C', 'C'], + ... 'ALT': ['C', 'T', 'G', 'G,A'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.'], + ... 'FORMAT': ['GT:AD', 'GT:AD', 'GT:AD', 'GT:AD'], + ... 'Steven': ['0/1:12,15', './.:.', '0/1:16,12', './.:.'], + ... 'Sara': ['./.:.', '0/1:14,15', './.:.', '1/2:0,11,17'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven Sara + 0 chr1 100 . A C . . . GT:AD 0/1:12,15 ./.:. + 1 chr1 100 . A T . . . GT:AD ./.:. 0/1:14,15 + 2 chr2 200 . C G . . . GT:AD 0/1:16,12 ./.:. + 3 chr2 200 . C G,A . . . GT:AD ./.:. 1/2:0,11,17 + + We collapse the VcfFrame: + + >>> vf.collapse().df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven Sara + 0 chr1 100 . A C,T . . . GT:AD 0/1:12,15,0 0/2:14,0,15 + 2 chr2 200 . C A,G . . . GT:AD 0/2:16,0,12 1/2:0,17,11 + """""" + df = self.df.copy() + dup_idx = df.duplicated(['CHROM', 'POS', 'REF'], keep=False) + dups = {} + for i, r in df[dup_idx].iterrows(): + name = f'{r.CHROM}:{r.POS}:{r.REF}' + if name not in dups: + dups[name] = [] + dups[name].append(i) + + def collapse_one(df): + ref_allele = df.REF.unique()[0] + alt_alleles = [] + for i, r in df.iterrows(): + alt_alleles += r.ALT.split(',') + alt_alleles = sorted(list(set(alt_alleles)), + key=lambda x: (len(x), x)) + all_alleles = [ref_allele] + alt_alleles + + def infunc(x, r_all_alleles, index_map): + if gt_miss(x): + return '' + old_fields = x.split(':') + old_gt = old_fields[0] + new_gt = '/'.join([str(x) for x in + sorted([index_map[int(i)] for i in old_gt.split('/')]) + ]) + new_fields = [new_gt] + for old_field in old_fields[1:]: + old_subfields = old_field.split(',') + new_subfields = ['0' for x in all_alleles] + if len(old_subfields) == len(r_all_alleles): + for i, old_subfield in enumerate(old_subfields): + new_subfields[index_map[i]] = old_subfield + new_fields.append(','.join(new_subfields)) + else: + new_fields.append(old_field) + return ':'.join(new_fields) + + def outfunc(r): + r_alt_alleles = r.ALT.split(',') + r_all_alleles = [r.REF] + r_alt_alleles + old_indicies = [i for i in range(len(r_all_alleles))] + new_indicies = [all_alleles.index(x) for x in r_all_alleles] + index_map = dict(zip(old_indicies, new_indicies)) + r[9:] = r[9:].apply(infunc, args=(r_all_alleles, index_map)) + return r + + df2 = df.apply(outfunc, axis=1) + + def raise_error(c): + if sum(c.values != '') > 1: + message = ('cannot collapse following ' + f'records:\n{df.loc[c.index]}') + raise ValueError(message) + + df2.iloc[:, 9:].apply(raise_error) + df2 = df2.groupby(['CHROM', 'POS', 'REF']).agg(''.join) + df2 = df2.reset_index() + cols = list(df2) + cols[2], cols[3] = cols[3], cols[2] + df2 = df2[cols] + df2.ID = df.ID.unique()[0] + df2.ALT = ','.join(alt_alleles) + df2.QUAL = df.QUAL.unique()[0] + df2.FILTER = df.FILTER.unique()[0] + df2.INFO = df.INFO.unique()[0] + df2.FORMAT = df.FORMAT.unique()[0] + s = df2.squeeze() + s = s.replace('', row_missval(s)) + return s + + for name, i in dups.items(): + df.iloc[i] = collapse_one(df.iloc[i]) + df.drop_duplicates(subset=['CHROM', 'POS', 'REF'], inplace=True) + + vf = self.__class__(self.copy_meta(), df) + return vf + + def compute_info(self, key): + """""" + Compute AC/AN/AF for INFO column. + + The method will ignore and overwrite any existing data for selected + key. + + Returns + ------- + VcfFrame + Updated VcfFrame. + key : {'AC', 'AN', 'AF'} + INFO key. + + Example + ------- + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chrX'], + ... 'POS': [100, 101, 102, 100], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['G', 'T', 'A', 'C'], + ... 'ALT': ['A', 'C', 'T,G', 'A'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': ['AC=100', 'MQ=59', '.', '.'], + ... 'FORMAT': ['GT:DP', 'GT', 'GT', 'GT'], + ... 'A': ['1|0:34', '0|0', '1|0', '0'], + ... 'B': ['1/1:23', '0/1', '0/0', '0/0'], + ... 'C': ['0/0:28', './.', '1/2', '1'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C + 0 chr1 100 . G A . . AC=100 GT:DP 1|0:34 1/1:23 0/0:28 + 1 chr1 101 . T C . . MQ=59 GT 0|0 0/1 ./. + 2 chr1 102 . A T,G . . . GT 1|0 0/0 1/2 + 3 chrX 100 . C A . . . GT 0 0/0 1 + >>> vf = vf.compute_info('AC') + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C + 0 chr1 100 . G A . . AC=1 GT:DP 1|0:34 1/1:23 0/0:28 + 1 chr1 101 . T C . . MQ=59;AC=1 GT 0|0 0/1 ./. + 2 chr1 102 . A T,G . . AC=1,1 GT 1|0 0/0 1/2 + 3 chrX 100 . C A . . AC=1 GT 0 0/0 1 + >>> vf = vf.compute_info('AN') + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C + 0 chr1 100 . G A . . AC=1;AN=6 GT:DP 1|0:34 1/1:23 0/0:28 + 1 chr1 101 . T C . . MQ=59;AC=1;AN=4 GT 0|0 0/1 ./. + 2 chr1 102 . A T,G . . AC=1,1;AN=6 GT 1|0 0/0 1/2 + 3 chrX 100 . C A . . AC=1;AN=4 GT 0 0/0 1 + >>> vf = vf.compute_info('AF') + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C + 0 chr1 100 . G A . . AC=1;AN=6;AF=0.167 GT:DP 1|0:34 1/1:23 0/0:28 + 1 chr1 101 . T C . . MQ=59;AC=1;AN=4;AF=0.250 GT 0|0 0/1 ./. + 2 chr1 102 . A T,G . . AC=1,1;AN=6;AF=0.167,0.167 GT 1|0 0/0 1/2 + 3 chrX 100 . C A . . AC=1;AN=4;AF=0.250 GT 0 0/0 1 + """""" + def one_row(r, key): + data = row_computeinfo(r, key) + r.INFO = row_updateinfo(r, key, data, missing=True) + return r + + df = self.df.apply(one_row, args=(key,), axis=1) + + return self.__class__(self.copy_meta(), df) + + @classmethod + def from_dict(cls, meta, data): + """""" + Construct VcfFrame from a dict of array-like or dicts. + + Parameters + ---------- + meta : list + List of the metadata lines. + data : dict + Of the form {field : array-like} or {field : dict}. + + Returns + ------- + VcfFrame + VcfFrame. + + See Also + -------- + VcfFrame + VcfFrame object creation using constructor. + VcfFrame.from_file + Construct VcfFrame from a VCF file. + VcfFrame.from_string + Construct VcfFrame from a string. + + Examples + -------- + Below is a simple example: + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr2'], + ... 'POS': [100, 101], + ... 'ID': ['.', '.'], + ... 'REF': ['G', 'T'], + ... 'ALT': ['A', 'C'], + ... 'QUAL': ['.', '.'], + ... 'FILTER': ['.', '.'], + ... 'INFO': ['.', '.'], + ... 'FORMAT': ['GT', 'GT'], + ... 'A': ['0/1', '1/1'] + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A + 0 chr1 100 . G A . . . GT 0/1 + 1 chr2 101 . T C . . . GT 1/1 + """""" + return cls(meta, pd.DataFrame(data)) + + @classmethod + def from_file( + cls, fn, compression=False, meta_only=False, regions=None + ): + """""" + Construct VcfFrame from a VCF file. + + The method will automatically use BGZF decompression if the filename + ends with '.gz'. + + If the file is large you can speicfy regions of interest to speed up + data processing. Note that this requires the file be BGZF compressed + and indexed (.tbi) for random access. Each region to be sliced must + have the format chrom:start-end and be a half-open interval with + (start, end]. This means, for example, 'chr1:100-103' will extract + positions 101, 102, and 103. Alternatively, you can provide BED data + to specify regions. + + Parameters + ---------- + fn : str or file-like object + VCF file (compressed or uncompressed). By file-like object, we + refer to objects with a :meth:`read()` method, such as a file + handle. + compression : bool, default: False + If True, use BGZF decompression regardless of the filename. + meta_only : bool, default: False + If True, only read metadata and header lines. + regions : str, list, or pybed.BedFrame, optional + Region or list of regions to be sliced. Also accepts a BED file + or a BedFrame. + + Returns + ------- + VcfFrame + VcfFrame object. + + See Also + -------- + VcfFrame + VcfFrame object creation using constructor. + VcfFrame.from_dict + Construct VcfFrame from a dict of array-like or dicts. + VcfFrame.from_string + Construct VcfFrame from a string. + + Examples + -------- + + >>> from fuc import pyvcf + >>> vf = pyvcf.VcfFrame.from_file('unzipped.vcf') + >>> vf = pyvcf.VcfFrame.from_file('zipped.vcf.gz') + >>> vf = pyvcf.VcfFrame.from_file('zipped.vcf', compression=True) + """""" + if isinstance(fn, str): + if regions is None: + s = '' + if fn.startswith('~'): + fn = os.path.expanduser(fn) + if fn.endswith('.gz') or compression: + f = bgzf.open(fn, 'rt') + else: + f = open(fn) + for line in f: + s += line + f.close() + else: + s = slice(fn, regions) + elif hasattr(fn, 'read'): + s = fn.read() + try: + s = s.decode('utf-8') + except AttributeError: + pass + else: + raise TypeError(f'Incorrect input type: {type(fn).__name__}') + vf = cls.from_string(s) + return vf + + @classmethod + def from_string(cls, s, meta_only=False): + """""" + Construct VcfFrame from a string. + + Parameters + ---------- + s : str + String representation of a VCF file. + + Returns + ------- + VcfFrame + VcfFrame object. + + See Also + -------- + VcfFrame + VcfFrame object creation using constructor. + VcfFrame.from_file + Construct VcfFrame from a VCF file. + VcfFrame.from_dict + Construct VcfFrame from a dict of array-like or dicts. + + Examples + -------- + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1'], + ... 'POS': [100, 101], + ... 'ID': ['.', '.'], + ... 'REF': ['G', 'T'], + ... 'ALT': ['A', 'C'], + ... 'QUAL': ['.', '.'], + ... 'FILTER': ['.', '.'], + ... 'INFO': ['.', '.'], + ... 'FORMAT': ['GT', 'GT'], + ... 'A': ['0/1', '0/1'] + ... } + >>> vf = pyvcf.VcfFrame.from_dict(['##fileformat=VCFv4.3'], data) + >>> s = vf.to_string() + >>> print(s[:20]) + ##fileformat=VCFv4.3 + >>> vf = pyvcf.VcfFrame.from_string(s) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A + 0 chr1 100 . G A . . . GT 0/1 + 1 chr1 101 . T C . . . GT 0/1 + """""" + skiprows = 0 + meta = [] + for line in s.split('\n'): + if line.startswith('##'): + meta.append(line.strip()) + skiprows += 1 + elif line.startswith('#CHROM'): + columns = line.strip().split('\t') + skiprows += 1 + else: + break + columns[0] = 'CHROM' + for header in HEADERS: + if header not in columns and header != 'FORMAT': + raise ValueError(f""Required VCF column missing: '{header}'"") + if meta_only: + df = pd.DataFrame(columns=columns) + else: + dtype = {**HEADERS, **{x: str for x in columns[9:]}} + df = pd.read_table(StringIO(s), skiprows=skiprows, + names=columns, dtype=dtype) + return cls(meta, df) + + def calculate_concordance(self, a, b, c=None, mode='all'): + """""" + Calculate genotype concordance between two (A, B) or three (A, B, C) + samples. + + This method will return (Ab, aB, AB, ab) for comparison between two + samples and (Abc, aBc, ABc, abC, AbC, aBC, ABC, abc) for three + samples. Note that the former is equivalent to (FP, FN, TP, TN) if + we assume A is the test sample and B is the truth sample. + + Only biallelic sites will be used for calculation. Additionally, the + method will ignore zygosity and only consider presence or absence of + variant calls (e.g. ``0/1`` and ``1/1`` will be treated the same). + + Parameters + ---------- + a, b : str or int + Name or index of Samples A and B. + c : str or int, optional + Name or index of Sample C. + mode : {'all', 'snv', 'indel'}, default: 'all' + Determines which variant types should be analyzed: + + - 'all': Include both SNVs and INDELs. + - 'snv': Include SNVs only. + - 'indel': Include INDELs only. + + Returns + ------- + tuple + Four- or eight-element tuple depending on the number of samples. + + See Also + -------- + fuc.api.common.sumstat + Return various summary statistics from (FP, FN, TP, TN). + + Examples + -------- + Assume we have the following data: + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102, 103, 104], + ... 'ID': ['.', '.', '.', '.', '.'], + ... 'REF': ['G', 'CT', 'T', 'C', 'A'], + ... 'ALT': ['A', 'C', 'A', 'T', 'G,C'], + ... 'QUAL': ['.', '.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT', 'GT'], + ... 'A': ['0/1', '0/0', '0/0', '0/1', '0/0'], + ... 'B': ['1/1', '0/1', './.', '0/1', '0/0'], + ... 'C': ['0/1', '0/1', '1/1', './.', '1/2'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C + 0 chr1 100 . G A . . . GT 0/1 1/1 0/1 + 1 chr1 101 . CT C . . . GT 0/0 0/1 0/1 + 2 chr1 102 . T A . . . GT 0/0 ./. 1/1 + 3 chr1 103 . C T . . . GT 0/1 0/1 ./. + 4 chr1 104 . A G,C . . . GT 0/0 0/0 1/2 + + We can first compare the samples A and B: + + >>> vf.calculate_concordance('A', 'B', mode='all') + (0, 1, 2, 1) + >>> vf.calculate_concordance('A', 'B', mode='snv') + (0, 0, 2, 1) + >>> vf.calculate_concordance('A', 'B', mode='indel') + (0, 1, 0, 0) + + We can also compare all three samples at once: + + >>> vf.calculate_concordance('A', 'B', 'C') + (0, 0, 1, 1, 0, 1, 1, 0) + """""" + vf = self.filter_multialt() + + if mode == 'all': + pass + elif mode == 'snv': + vf = vf.filter_indel() + elif mode == 'indel': + vf = vf.filter_indel(opposite=True) + else: + raise ValueError(f'Incorrect mode: {mode}.') + + if c is None: + result = self._compare_two(vf, a, b) + else: + result = self._compare_three(vf, a, b, c) + + return result + + def _compare_two(self, vf, a, b): + a = a if isinstance(a, str) else vf.samples[a] + b = b if isinstance(b, str) else vf.samples[b] + def func(r): + a_has = gt_hasvar(r[a]) + b_has = gt_hasvar(r[b]) + if a_has and not b_has: + return 'Ab' + elif not a_has and b_has: + return 'aB' + elif a_has and b_has: + return 'AB' + else: + return 'ab' + d = vf.df.apply(func, axis=1).value_counts().to_dict() + Ab = d['Ab'] if 'Ab' in d else 0 + aB = d['aB'] if 'aB' in d else 0 + AB = d['AB'] if 'AB' in d else 0 + ab = d['ab'] if 'ab' in d else 0 + return (Ab, aB, AB, ab) + + def _compare_three(self, vf, a, b, c): + a = a if isinstance(a, str) else vf.samples[a] + b = b if isinstance(b, str) else vf.samples[b] + c = c if isinstance(c, str) else vf.samples[c] + def func(r): + a_has = gt_hasvar(r[a]) + b_has = gt_hasvar(r[b]) + c_has = gt_hasvar(r[c]) + if a_has and not b_has and not c_has: + return 'Abc' + elif not a_has and b_has and not c_has: + return 'aBc' + elif a_has and b_has and not c_has: + return 'ABc' + elif not a_has and not b_has and c_has: + return 'abC' + elif a_has and not b_has and c_has: + return 'AbC' + elif not a_has and b_has and c_has: + return 'aBC' + elif a_has and b_has and c_has: + return 'ABC' + else: + return 'abc' + d = vf.df.apply(func, axis=1).value_counts().to_dict() + Abc = d['Abc'] if 'Abc' in d else 0 + aBc = d['aBc'] if 'aBc' in d else 0 + ABc = d['ABc'] if 'ABc' in d else 0 + abC = d['abC'] if 'abC' in d else 0 + AbC = d['AbC'] if 'AbC' in d else 0 + aBC = d['aBC'] if 'aBC' in d else 0 + ABC = d['ABC'] if 'ABC' in d else 0 + abc = d['abc'] if 'abc' in d else 0 + return (Abc, aBc, ABc, abC, AbC, aBC, ABC, abc) + + def combine(self, a, b): + """""" + Combine genotype data from two samples (A, B). + + This method can be especially useful when you want to consolidate + genotype data from replicate samples. See examples below for more + details. + + Parameters + ---------- + a, b : str or int + Name or index of Samples A and B. + + Returns + ------- + pandas.Series + Resulting VCF column. + + See Also + -------- + VcfFrame.subtract + Subtract genotype data between two samples (A, B). + + Examples + -------- + Assume we have following data where a cancer patient's tissue sample + has been sequenced twice: + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102, 103, 104], + ... 'ID': ['.', '.', '.', '.', '.'], + ... 'REF': ['G', 'T', 'T', 'A', 'C'], + ... 'ALT': ['A', 'C', 'A', 'C', 'G'], + ... 'QUAL': ['.', '.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.', '.'], + ... 'FORMAT': ['GT:DP', 'GT:DP', 'GT:DP', 'GT:DP', 'GT:DP'], + ... 'Tissue1': ['./.:.', '0/0:7', '0/1:28', '0/1:4', '0/1:32'], + ... 'Tissue2': ['0/1:24', '0/1:42', './.:.', './.:.', '0/1:19'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Tissue1 Tissue2 + 0 chr1 100 . G A . . . GT:DP ./.:. 0/1:24 + 1 chr1 101 . T C . . . GT:DP 0/0:7 0/1:42 + 2 chr1 102 . T A . . . GT:DP 0/1:28 ./.:. + 3 chr1 103 . A C . . . GT:DP 0/1:4 ./.:. + 4 chr1 104 . C G . . . GT:DP 0/1:32 0/1:19 + + We can combine genotype data from 'Tissue1' and 'Tissue2' to get a + more comprehensive variant profile: + + >>> vf.df['Combined'] = vf.combine('Tissue1', 'Tissue2') + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Tissue1 Tissue2 Combined + 0 chr1 100 . G A . . . GT:DP ./.:. 0/1:24 0/1:24 + 1 chr1 101 . T C . . . GT:DP 0/0:7 0/1:42 0/1:42 + 2 chr1 102 . T A . . . GT:DP 0/1:28 ./.:. 0/1:28 + 3 chr1 103 . A C . . . GT:DP 0/1:4 ./.:. 0/1:4 + 4 chr1 104 . C G . . . GT:DP 0/1:32 0/1:19 0/1:32 + """""" + a = a if isinstance(a, str) else self.samples[a] + b = b if isinstance(b, str) else self.samples[b] + def func(r): + a_has = gt_hasvar(r[a]) + b_has = gt_hasvar(r[b]) + if a_has and b_has: + return r[a] + elif a_has and not b_has: + return r[a] + elif not a_has and b_has: + return r[b] + else: + return r[a] + s = self.df.apply(func, axis=1) + return s + + def copy_meta(self): + """"""Return a copy of the metadata."""""" + return deepcopy(self.meta) + + def copy_df(self): + """"""Return a copy of the dataframe."""""" + return self.df.copy() + + def copy(self): + """"""Return a copy of the VcfFrame."""""" + return self.__class__(self.copy_meta(), self.copy_df()) + + def to_bed(self): + """""" + Convert VcfFrame to BedFrame. + + Returns + ------- + BedFrame + BedFrame obejct. + + Examples + -------- + Assume we have the following data: + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102, 103, 104], + ... 'ID': ['.', '.', '.', '.', '.'], + ... 'REF': ['A', 'A', 'C', 'C', 'ACGT'], + ... 'ALT': ['C', 'T,G', 'G', 'A,G,CT', 'A'], + ... 'QUAL': ['.', '.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.', '.'], + ... 'FORMAT': ['GT:DP', 'GT:DP', 'GT:DP', 'GT:DP', 'GT:DP'], + ... 'Steven': ['0/1:32', './.:.', '0/1:27', '0/2:34', '0/0:31'], + ... 'Sara': ['0/0:28', '1/2:30', '1/1:29', '1/2:38', '0/1:27'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven Sara + 0 chr1 100 . A C . . . GT:DP 0/1:32 0/0:28 + 1 chr1 101 . A T,G . . . GT:DP ./.:. 1/2:30 + 2 chr1 102 . C G . . . GT:DP 0/1:27 1/1:29 + 3 chr1 103 . C A,G,CT . . . GT:DP 0/2:34 1/2:38 + 4 chr1 104 . ACGT A . . . GT:DP 0/0:31 0/1:27 + + We can construct BedFrame from the VcfFrame: + + >>> bf = vf.to_bed() + >>> bf.gr.df + Chromosome Start End + 0 chr1 100 100 + 1 chr1 101 101 + 2 chr1 102 102 + 3 chr1 103 103 + 4 chr1 103 104 + 5 chr1 105 107 + """""" + def one_row(r): + if len(r.REF) == len(r.ALT) == 1: + start = r.POS + end = r.POS + elif len(r.REF) > len(r.ALT): + start = r.POS + 1 + end = r.POS + len(r.REF) - len(r.ALT) + else: + start = r.POS + end = r.POS + 1 + return pd.Series([r.CHROM, start, end]) + df = self.expand().df.apply(one_row, axis=1) + df.columns = ['Chromosome', 'Start', 'End'] + df = df.drop_duplicates() + bf = pybed.BedFrame.from_frame([], df) + return bf + + def to_file(self, fn, compression=False): + """""" + Write VcfFrame to a VCF file. + + If the filename ends with '.gz', the method will automatically + use the BGZF compression when writing the file. + + Parameters + ---------- + fn : str + VCF file path. + compression : bool, default: False + If True, use the BGZF compression. + + Examples + -------- + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr2'], + ... 'POS': [100, 101], + ... 'ID': ['.', '.'], + ... 'REF': ['G', 'T'], + ... 'ALT': ['A', 'C'], + ... 'QUAL': ['.', '.'], + ... 'FILTER': ['.', '.'], + ... 'INFO': ['.', '.'], + ... 'FORMAT': ['GT', 'GT'], + ... 'Steven': ['0/1', '1/1'] + ... } + >>> vf = pyvcf.VcfFrame.from_dict(['##fileformat=VCFv4.3'], data) + >>> vf.to_file('unzipped.vcf') + >>> vf.to_file('zipped.vcf.gz') + >>> vf.to_file('zipped.vcf.gz', compression=True) + """""" + if fn.endswith('.gz') or compression: + f = bgzf.open(fn, 'w') + else: + f = open(fn, 'w') + f.write(self.to_string()) + f.close() + + def to_string(self): + """""" + Render the VcfFrame to a console-friendly tabular output. + + Returns + ------- + str + String representation of the VcfFrame. + + Examples + -------- + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1'], + ... 'POS': [100, 101], + ... 'ID': ['.', '.'], + ... 'REF': ['G', 'T'], + ... 'ALT': ['A', 'C'], + ... 'QUAL': ['.', '.'], + ... 'FILTER': ['.', '.'], + ... 'INFO': ['.', '.'], + ... 'FORMAT': ['GT', 'GT'], + ... 'A': ['0/1', '0/1'] + ... } + >>> vf = pyvcf.VcfFrame.from_dict(['##fileformat=VCFv4.3'], data) + >>> print(vf.to_string()) + ##fileformat=VCFv4.3 + #CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A + chr1 100 . G A . . . GT 0/1 + chr1 101 . T C . . . GT 0/1 + """""" + s = '' + if self.meta: + s += '\n'.join(self.meta) + '\n' + s += self.df.rename(columns={'CHROM': '#CHROM'} + ).to_csv(index=False, sep='\t') + return s + + def to_variants(self): + """""" + List unique variants in VcfFrame. + + Returns + ------- + list + List of unique variants. + + Examples + -------- + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr2'], + ... 'POS': [100, 101], + ... 'ID': ['.', '.'], + ... 'REF': ['G', 'T'], + ... 'ALT': ['A', 'A,C'], + ... 'QUAL': ['.', '.'], + ... 'FILTER': ['.', '.'], + ... 'INFO': ['.', '.'], + ... 'FORMAT': ['GT', 'GT'], + ... 'A': ['0/1', '1/2'] + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.variants() + ['chr1-100-G-A', 'chr2-101-T-A', 'chr2-101-T-C'] + """""" + def one_row(r): + result = [] + for alt in r.ALT.split(','): + result.append(f'{r.CHROM}-{r.POS}-{r.REF}-{alt}') + return ','.join(result) + s = self.df.apply(one_row, axis=1) + s = ','.join(s) + return s.split(',') + + def strip(self, format='GT', metadata=False): + """""" + Remove any unnecessary data. + + Parameters + ---------- + format : str, default: 'GT' + FORMAT keys to retain (e.g. 'GT:AD:DP'). + metadata : bool, default: False + If True, keep the metadata. + + Returns + ------- + VcfFrame + Stripped VcfFrame. + + Examples + -------- + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102], + ... 'ID': ['.', '.', '.'], + ... 'REF': ['G', 'T', 'A'], + ... 'ALT': ['A', 'C', 'T'], + ... 'QUAL': ['.', '.', '.'], + ... 'FILTER': ['.', '.', '.'], + ... 'INFO': ['.', '.', '.'], + ... 'FORMAT': ['GT:DP:AD', 'GT:DP:AD', 'GT'], + ... 'A': ['0/1:30:15,15', '1/1:28:0,28', '0/1'] + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A + 0 chr1 100 . G A . . . GT:DP:AD 0/1:30:15,15 + 1 chr1 101 . T C . . . GT:DP:AD 1/1:28:0,28 + 2 chr1 102 . A T . . . GT 0/1 + >>> vf.strip('GT:DP').df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A + 0 chr1 100 . G A . . . GT:DP 0/1:30 + 1 chr1 101 . T C . . . GT:DP 1/1:28 + 2 chr1 102 . A T . . . GT:DP 0/1:. + """""" + new_keys = format.split(':') + + def one_row(r): + old_keys = r.FORMAT.split(':') + indicies = [ + old_keys.index(x) if x in old_keys else None for x in new_keys + ] + + def one_gt(g): + old_fields = g.split(':') + new_fields = [ + '.' if x is None + else '.' if x >= len(old_fields) + else old_fields[x] + for x in indicies + ] + return ':'.join(new_fields) + + r.iloc[9:] = r.iloc[9:].apply(one_gt) + + return r + + df = self.df.copy() + df[['ID', 'QUAL', 'FILTER', 'INFO']] = '.' + df = df.apply(one_row, axis=1) + df.FORMAT = format + + if metadata: + meta = self.copy_meta() + else: + meta = [] + vf = self.__class__(meta, df) + return vf + + def merge( + self, other, how='inner', format='GT', sort=True, collapse=False + ): + """""" + Merge with the other VcfFrame. + + Parameters + ---------- + other : VcfFrame + Other VcfFrame. Note that the 'chr' prefix in contig names (e.g. + 'chr1' vs. '1') will be automatically added or removed as + necessary to match the contig names of ``self``. + how : str, default: 'inner' + Type of merge as defined in :meth:`pandas.DataFrame.merge`. + format : str, default: 'GT' + FORMAT subfields to be retained (e.g. 'GT:AD:DP'). + sort : bool, default: True + If True, sort the VcfFrame before returning. + collapse : bool, default: False + If True, collapse duplicate records. + + Returns + ------- + VcfFrame + Merged VcfFrame. + + See Also + -------- + merge + Merge multiple VcfFrame objects. + + Examples + -------- + Assume we have the following data: + + >>> from fuc import pyvcf + >>> data1 = { + ... 'CHROM': ['chr1', 'chr1'], + ... 'POS': [100, 101], + ... 'ID': ['.', '.'], + ... 'REF': ['G', 'T'], + ... 'ALT': ['A', 'C'], + ... 'QUAL': ['.', '.'], + ... 'FILTER': ['.', '.'], + ... 'INFO': ['.', '.'], + ... 'FORMAT': ['GT:DP', 'GT:DP'], + ... 'A': ['0/0:32', '0/1:29'], + ... 'B': ['0/1:24', '1/1:30'], + ... } + >>> data2 = { + ... 'CHROM': ['chr1', 'chr1', 'chr2'], + ... 'POS': [100, 101, 200], + ... 'ID': ['.', '.', '.'], + ... 'REF': ['G', 'T', 'A'], + ... 'ALT': ['A', 'C', 'T'], + ... 'QUAL': ['.', '.', '.'], + ... 'FILTER': ['.', '.', '.'], + ... 'INFO': ['.', '.', '.'], + ... 'FORMAT': ['GT:DP', 'GT:DP', 'GT:DP'], + ... 'C': ['./.:.', '0/0:24', '0/0:26'], + ... 'D': ['0/1:24', '0/1:31', '0/1:26'], + ... } + >>> vf1 = pyvcf.VcfFrame.from_dict([], data1) + >>> vf2 = pyvcf.VcfFrame.from_dict([], data2) + >>> vf1.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B + 0 chr1 100 . G A . . . GT:DP 0/0:32 0/1:24 + 1 chr1 101 . T C . . . GT:DP 0/1:29 1/1:30 + >>> vf2.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT C D + 0 chr1 100 . G A . . . GT:DP ./.:. 0/1:24 + 1 chr1 101 . T C . . . GT:DP 0/0:24 0/1:31 + 2 chr2 200 . A T . . . GT:DP 0/0:26 0/1:26 + + We can merge the two VcfFrames with ``how='inner'`` (default): + + >>> vf1.merge(vf2).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C D + 0 chr1 100 . G A . . . GT 0/0 0/1 ./. 0/1 + 1 chr1 101 . T C . . . GT 0/1 1/1 0/0 0/1 + + We can also merge with ``how='outer'``: + + >>> vf1.merge(vf2, how='outer').df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C D + 0 chr1 100 . G A . . . GT 0/0 0/1 ./. 0/1 + 1 chr1 101 . T C . . . GT 0/1 1/1 0/0 0/1 + 2 chr2 200 . A T . . . GT ./. ./. 0/0 0/1 + + Since both VcfFrames have the DP subfield, we can use ``format='GT:DP'``: + + >>> vf1.merge(vf2, how='outer', format='GT:DP').df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C D + 0 chr1 100 . G A . . . GT:DP 0/0:32 0/1:24 ./.:. 0/1:24 + 1 chr1 101 . T C . . . GT:DP 0/1:29 1/1:30 0/0:24 0/1:31 + 2 chr2 200 . A T . . . GT:DP ./.:. ./.:. 0/0:26 0/1:26 + """""" + if self.has_chr_prefix and other.has_chr_prefix: + pass + elif self.has_chr_prefix and not other.has_chr_prefix: + other = other.update_chr_prefix('add') + elif not self.has_chr_prefix and other.has_chr_prefix: + other = other.update_chr_prefix('remove') + else: + pass + + if self.sites_only and other.sites_only: + df = pd.concat([self.df, other.df]) + merged = self.__class__([], df) + merged = merged.drop_duplicates() + else: + vf1 = self.strip(format=format) + vf2 = other.strip(format=format) + dropped = ['ID', 'QUAL', 'FILTER', 'INFO', 'FORMAT'] + shared = ['CHROM', 'POS', 'REF', 'ALT'] + df = vf1.df.merge(vf2.df.drop(columns=dropped), on=shared, how=how) + + # This ensures that the column order is intact when either of the + # dataframes is empty. + cols = vf1.df.columns.to_list() + vf2.df.columns[9:].to_list() + df = df[cols] + + df[dropped] = df[dropped].fillna('.') + df.FORMAT = format + def func(r): + n = len(r.FORMAT.split(':')) + x = './.' + for i in range(1, n): + x += ':.' + r = r.fillna(x) + return r + df = df.apply(func, axis=1) + merged = self.__class__([], df) + + if collapse: + merged = merged.collapse() + if sort: + merged = merged.sort() + + return merged + + def meta_keys(self): + """"""Print metadata lines with a key."""""" + for line in self.meta: + if '=>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr2'], + ... 'POS': [100, 101], + ... 'ID': ['.', '.'], + ... 'REF': ['G', 'T'], + ... 'ALT': ['A', 'C'], + ... 'QUAL': ['.', '.'], + ... 'FILTER': ['.', '.'], + ... 'INFO': ['.', '.'], + ... 'FORMAT': ['GT', 'GT'], + ... 'A': ['./.', '1/1'], + ... 'B': ['./.', './.'] + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B + 0 chr1 100 . G A . . . GT ./. ./. + 1 chr2 101 . T C . . . GT 1/1 ./. + >>> new_vf = vf.miss2ref() + >>> new_vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B + 0 chr1 100 . G A . . . GT 0/0 0/0 + 1 chr2 101 . T C . . . GT 1/1 0/0 + """""" + df = self.copy_df() + def one_gt(g): + l = [g.split(':')[0].replace('.', '0')] + g.split(':')[1:] + return ':'.join(l) + df.iloc[:, 9:] = df.iloc[:, 9:].applymap(one_gt) + return self.__class__(self.copy_meta(), df) + + def plot_region( + self, sample, k='#DP', color=None, region=None, label=None, ax=None, + figsize=None, **kwargs + ): + """""" + Create a scatter plot showing read depth profile of a sample for + the specified region. + + Parameters + ---------- + sample : str or int + Name or index of target sample. + k : str, default: '#DP' + Genotype key to use for extracting data: + + - '#DP': Return read depth. + - '#AD_REF': Return REF allele depth. + - '#AD_ALT': Return ALT allele depth. + - '#AD_FRAC_REF': Return REF allele fraction. + - '#AD_FRAC_ALT': Return ALT allele fraction. + + color : str, optional + Marker color. + region : str, optional + Target region ('chrom:start-end'). + label : str, optional + Label to use for the data points. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`matplotlib.axes.Axes.scatter`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + Examples + -------- + Below is a simple example: + + .. plot:: + :context: close-figs + + >>> from fuc import pyvcf, common + >>> import matplotlib.pyplot as plt + >>> common.load_dataset('pyvcf') + >>> vcf_file = '~/fuc-data/pyvcf/getrm-cyp2d6-vdr.vcf' + >>> vf = pyvcf.VcfFrame.from_file(vcf_file) + >>> vf.plot_region('NA18973') + >>> plt.tight_layout() + + We can display allele fraction of REF and ALT instead of DP: + + .. plot:: + :context: close-figs + + >>> ax = vf.plot_region('NA18973', k='#AD_FRAC_REF', label='REF') + >>> vf.plot_region('NA18973', k='#AD_FRAC_ALT', label='ALT', ax=ax) + >>> plt.tight_layout() + """""" + if self.df.empty: + raise ValueError('VcfFrame is empty') + + sample = sample if isinstance(sample, str) else self.samples[sample] + + if region is None: + if len(self.contigs) == 1: + vf = self.copy() + else: + raise ValueError('Multiple contigs found.') + else: + vf = self.slice(region) + + df = vf.extract_format(k) + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + ax.scatter( + x=vf.df.POS, y=df[sample], c=color, label=label, **kwargs + ) + + ax.set_xlabel('Position') + ax.set_ylabel('Depth') + + return ax + + def plot_comparison( + self, a, b, c=None, labels=None, ax=None, figsize=None + ): + """""" + Create a Venn diagram showing genotype concordance between groups. + + This method supports comparison between two groups (Groups A & B) + as well as three groups (Groups A, B, & C). + + Parameters + ---------- + a, b : list + Sample names. The lists must have the same shape. + c : list, optional + Same as above. + labels : list, optional + List of labels to be displayed. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + matplotlib_venn._common.VennDiagram + VennDiagram object. + + Examples + -------- + + .. plot:: + :context: close-figs + + >>> from fuc import pyvcf, common + >>> common.load_dataset('pyvcf') + >>> f = '~/fuc-data/pyvcf/plot_comparison.vcf' + >>> vf = pyvcf.VcfFrame.from_file(f) + >>> a = ['Steven_A', 'John_A', 'Sara_A'] + >>> b = ['Steven_B', 'John_B', 'Sara_B'] + >>> c = ['Steven_C', 'John_C', 'Sara_C'] + >>> vf.plot_comparison(a, b) + + .. plot:: + :context: close-figs + + >>> vf.plot_comparison(a, b, c) + """""" + if len(a) != len(b): + raise ValueError('Groups A and B have different length.') + if c is not None and len(a) != len(c): + raise ValueError('Group C has unmatched length.') + if labels is None: + if c is None: + labels = ('A', 'B') + else: + labels = ('A', 'B', 'C') + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + venn_kws = dict(ax=ax, alpha=0.5, set_labels=labels) + if c is None: + out = self._plot_comparison_two(a, b, venn_kws) + else: + out = self._plot_comparison_three(a, b, c, venn_kws) + return ax, out + + def _plot_comparison_two(self, a, b, venn_kws): + n = [0, 0, 0, 0] + for i in range(len(a)): + n = [x + y for x, y in zip(n, self.calculate_concordance(a[i], b[i]))] + out = venn2(subsets=n[:-1], **venn_kws) + return out + + def _plot_comparison_three(self, a, b, c, venn_kws): + n = [0, 0, 0, 0, 0, 0, 0, 0] + for i in range(len(a)): + n = [x + y for x, y in zip(n, self.calculate_concordance(a[i], b[i], c[i]))] + out = venn3(subsets=n[:-1], **venn_kws) + return out + + def plot_hist_format( + self, k, af=None, group_col=None, group_order=None, kde=True, + ax=None, figsize=None, **kwargs + ): + """""" + Create a histogram showing the distribution of data for the + specified FORMAT key. + + Parameters + ---------- + k : str + One of the special FORMAT keys as defined in + :meth:`VcfFrame.extract_format`. + af : common.AnnFrame + AnnFrame containing sample annotation data. + group_col : list, optional + AnnFrame column containing sample group information. + group_order : list, optional + List of sample group names. + kde : bool, default: True + Compute a kernel density estimate to smooth the distribution. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`seaborn.histplot`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + Examples + -------- + Below is a simple example: + + .. plot:: + :context: close-figs + + >>> from fuc import common, pyvcf + >>> common.load_dataset('pyvcf') + >>> vcf_file = '~/fuc-data/pyvcf/normal-tumor.vcf' + >>> vf = pyvcf.VcfFrame.from_file(vcf_file) + >>> vf.plot_hist_format('#DP') + + We can draw multiple histograms with hue mapping: + + .. plot:: + :context: close-figs + + >>> annot_file = '~/fuc-data/pyvcf/normal-tumor-annot.tsv' + >>> af = common.AnnFrame.from_file(annot_file, sample_col='Sample') + >>> vf.plot_hist_format('#DP', af=af, group_col='Tissue') + + We can show AF instead of DP: + + .. plot:: + :context: close-figs + + >>> vf.plot_hist_format('#AD_FRAC_REF') + """""" + if k not in FORMAT_SPECIAL_KEYS: + raise ValueError('Incorrect FORMAT key.') + + df = self.extract_format(k) + + df = df.T + id_vars = ['index'] + if group_col is not None: + df = pd.concat([df, af.df[group_col]], axis=1, join='inner') + id_vars.append(group_col) + df = df.reset_index() + df = pd.melt(df, id_vars=id_vars) + df = df.dropna() + df = df.rename(columns={'value': k}) + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + sns.histplot( + data=df, x=k, hue=group_col, hue_order=group_order, kde=kde, + ax=ax, **kwargs + ) + + return ax + + def plot_hist_info( + self, k, kde=True, ax=None, figsize=None, **kwargs + ): + """""" + Create a histogram showing the distribution of data for the + specified INFO key. + + Parameters + ---------- + k : str + One of the special INFO keys as defined in + :meth:`VcfFrame.extract_info`. + kde : bool, default: True + Compute a kernel density estimate to smooth the distribution. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`seaborn.histplot`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + Examples + -------- + Below is a simple example: + + .. plot:: + :context: close-figs + + >>> from fuc import common, pyvcf + >>> common.load_dataset('pyvcf') + >>> vcf_file = '~/fuc-data/pyvcf/getrm-cyp2d6-vdr.vcf' + >>> vf = pyvcf.VcfFrame.from_file(vcf_file) + >>> vf.plot_hist_info('#AC') + + We can show AF instead of AC: + + .. plot:: + :context: close-figs + + >>> vf.plot_hist_info('#AF') + """""" + if k not in INFO_SPECIAL_KEYS: + raise ValueError('Incorrect INFO key.') + + s = self.extract_info(k) + + if s.isnull().all(): + raise ValueError('Dataset is empty.') + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + sns.histplot( + data=s, kde=kde, ax=ax, **kwargs + ) + + ax.set_xlabel(k) + + return ax + + def plot_tmb( + self, af=None, group_col=None, group_order=None, kde=True, ax=None, + figsize=None, **kwargs + ): + """""" + Create a histogram showing TMB distribution. + + Parameters + ---------- + af : common.AnnFrame + AnnFrame containing sample annotation data (requires ``hue``). + group_col : str, optional + AnnFrame column containing sample group information. + group_order : list, optional + List of sample group names. + kde : bool, default: True + Compute a kernel density estimate to smooth the distribution. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`seaborn.histplot`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + Examples + -------- + Below is a simple example: + + .. plot:: + :context: close-figs + + >>> from fuc import common, pyvcf + >>> common.load_dataset('pyvcf') + >>> vcf_file = '~/fuc-data/pyvcf/normal-tumor.vcf' + >>> vf = pyvcf.VcfFrame.from_file(vcf_file) + >>> vf.plot_tmb() + + We can draw multiple histograms with hue mapping: + + .. plot:: + :context: close-figs + + >>> annot_file = '~/fuc-data/pyvcf/normal-tumor-annot.tsv' + >>> af = common.AnnFrame.from_file(annot_file, sample_col='Sample') + >>> vf.plot_tmb(af=af, group_col='Tissue') + """""" + s = self.df.iloc[:, 9:].applymap(gt_hasvar).sum() + s.name = 'TMB' + if af is None: + df = s.to_frame() + else: + df = pd.concat([af.df, s], axis=1, join='inner') + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + sns.histplot( + data=df, x='TMB', ax=ax, hue=group_col, hue_order=group_order, + kde=kde, **kwargs + ) + + return ax + + def plot_regplot_tmb( + self, a, b, ax=None, figsize=None, **kwargs + ): + """""" + Create a scatter plot with a linear regression model fit visualizing + correlation between TMB in two sample groups. + + The method will automatically calculate and print summary statistics + including R-squared and p-value. + + Parameters + ---------- + a, b : array-like + Lists of sample names. The lists must have the same shape. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`seaborn.regplot`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + See Also + -------- + fuc.api.pymaf.MafFrame.plot_regplot_tmb + Similar method for the :meth:`fuc.api.pymaf.MafFrame` class. + + Examples + -------- + + .. plot:: + + >>> from fuc import common, pyvcf + >>> common.load_dataset('pyvcf') + >>> vcf_file = '~/fuc-data/pyvcf/normal-tumor.vcf' + >>> annot_file = '~/fuc-data/pyvcf/normal-tumor-annot.tsv' + >>> vf = pyvcf.VcfFrame.from_file(vcf_file) + >>> af = common.AnnFrame.from_file(annot_file, sample_col='Sample') + >>> normal = af.df[af.df.Tissue == 'Normal'].index + >>> normal.name = 'Normal' + >>> tumor = af.df[af.df.Tissue == 'Tumor'].index + >>> tumor.name = 'Tumor' + >>> vf.plot_regplot_tmb(normal, tumor) + Results for B ~ A: + R^2 = 0.01 + P = 7.17e-01 + >>> plt.tight_layout() + """""" + s = self.df.iloc[:, 9:].applymap(gt_hasvar).sum() + df = pd.concat([s[a].reset_index(), s[b].reset_index()], axis=1) + df.columns = ['A_Label', 'A_TMB', 'B_Label', 'B_TMB'] + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + sns.regplot(x='A_TMB', y='B_TMB', data=df, ax=ax, **kwargs) + + try: + ax.set_xlabel(a.name) + except AttributeError: + ax.set_xlabel('A') + + try: + ax.set_ylabel(b.name) + except AttributeError: + ax.set_ylabel('B') + + # Print summary statistics including R-squared and p-value. + results = smf.ols(f'B_TMB ~ A_TMB', data=df).fit() + print(f'Results for B ~ A:') + print(f'R^2 = {results.rsquared:.2f}') + print(f' P = {results.f_pvalue:.2e}') + + return ax + + def markmiss( + self, expr, greedy=False, opposite=False, samples=None, as_nan=False + ): + """""" + Mark all genotypes that satisfy the query expression as missing. + + Parameters + ---------- + expr : str + The expression to evaluate. See the examples below for details. + greedy : bool, default: False + If True, mark even ambiguous genotypes as missing. + opposite : bool, default: False + If True, mark all genotypes that do not satisfy the query + expression as missing and leave those that do intact. + sampels : list, optional + If provided, apply the marking only to these samples. + as_nan : bool, default: False + If True, mark genotypes as ``NaN`` instead of as missing. + + Returns + ------- + VcfFrame + Updated VcfFrame. + + Examples + -------- + Assume we have the following data: + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102], + ... 'ID': ['.', '.', '.'], + ... 'REF': ['G', 'T', 'T'], + ... 'ALT': ['A', 'C', 'G'], + ... 'QUAL': ['.', '.', '.'], + ... 'FILTER': ['.', '.', '.'], + ... 'INFO': ['.', '.', '.'], + ... 'FORMAT': ['GT:DP:AD', 'GT:DP:AD', 'GT:DP:AD'], + ... 'A': ['0/0:26:0,26', '0/1:32:16,16', '0/0:.:.'], + ... 'B': ['./.:.:.', '0/0:31:29,2', './.:.:.'], + ... 'C': ['0/1:18:12,6', '0/0:24:24,0', '1/1:8:0,8'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C + 0 chr1 100 . G A . . . GT:DP:AD 0/0:26:0,26 ./.:.:. 0/1:18:12,6 + 1 chr1 101 . T C . . . GT:DP:AD 0/1:32:16,16 0/0:31:29,2 0/0:24:24,0 + 2 chr1 102 . T G . . . GT:DP:AD 0/0:.:. ./.:.:. 1/1:8:0,8 + + To mark as missing all genotypes with ``0/0``: + + >>> vf.markmiss('GT == ""0/0""').df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C + 0 chr1 100 . G A . . . GT:DP:AD ./.:.:. ./.:.:. 0/1:18:12,6 + 1 chr1 101 . T C . . . GT:DP:AD 0/1:32:16,16 ./.:.:. ./.:.:. + 2 chr1 102 . T G . . . GT:DP:AD ./.:.:. ./.:.:. 1/1:8:0,8 + + To mark as missing all genotypes that do not have ``0/0``: + + >>> vf.markmiss('GT != ""0/0""').df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C + 0 chr1 100 . G A . . . GT:DP:AD 0/0:26:0,26 ./.:.:. ./.:.:. + 1 chr1 101 . T C . . . GT:DP:AD ./.:.:. 0/0:31:29,2 0/0:24:24,0 + 2 chr1 102 . T G . . . GT:DP:AD 0/0:.:. ./.:.:. ./.:.:. + + To mark as missing all genotypes whose ``DP`` is below 30: + + >>> vf.markmiss('DP < 30').df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C + 0 chr1 100 . G A . . . GT:DP:AD ./.:.:. ./.:.:. ./.:.:. + 1 chr1 101 . T C . . . GT:DP:AD 0/1:32:16,16 0/0:31:29,2 ./.:.:. + 2 chr1 102 . T G . . . GT:DP:AD 0/0:.:. ./.:.:. ./.:.:. + + Note that the genotype ``0/0:.:.`` was not marked as missing because + its ``DP`` is missing and therefore it could not be evaluated + properly. To mark even ambiguous genotypes like this one as missing, + you can set ``greedy`` as True: + + >>> vf.markmiss('DP < 30', greedy=True).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C + 0 chr1 100 . G A . . . GT:DP:AD ./.:.:. ./.:.:. ./.:.:. + 1 chr1 101 . T C . . . GT:DP:AD 0/1:32:16,16 0/0:31:29,2 ./.:.:. + 2 chr1 102 . T G . . . GT:DP:AD ./.:.:. ./.:.:. ./.:.:. + + To mark as missing all genotypes whose ALT allele has read depth + below 10: + + >>> vf.markmiss('AD[1] < 10', greedy=True).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C + 0 chr1 100 . G A . . . GT:DP:AD 0/0:26:0,26 ./.:.:. ./.:.:. + 1 chr1 101 . T C . . . GT:DP:AD 0/1:32:16,16 ./.:.:. ./.:.:. + 2 chr1 102 . T G . . . GT:DP:AD ./.:.:. ./.:.:. ./.:.:. + + To mark as missing all genotypes whose ALT allele has read depth + below 10 and ``DP`` is below 30: + + >>> vf.markmiss('AD[1] < 10 and DP < 30', greedy=True).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C + 0 chr1 100 . G A . . . GT:DP:AD 0/0:26:0,26 ./.:.:. ./.:.:. + 1 chr1 101 . T C . . . GT:DP:AD 0/1:32:16,16 0/0:31:29,2 ./.:.:. + 2 chr1 102 . T G . . . GT:DP:AD ./.:.:. ./.:.:. ./.:.:. + + To mark as missing all genotypes whose ALT allele has read depth + below 10 or ``DP`` is below 30: + + >>> vf.markmiss('AD[1] < 10 or DP < 30', greedy=True).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C + 0 chr1 100 . G A . . . GT:DP:AD ./.:.:. ./.:.:. ./.:.:. + 1 chr1 101 . T C . . . GT:DP:AD 0/1:32:16,16 ./.:.:. ./.:.:. + 2 chr1 102 . T G . . . GT:DP:AD ./.:.:. ./.:.:. ./.:.:. + + To only retain genotypes whose ALT allele has read depth below 10 or + ``DP`` is below 30: + + >>> vf.markmiss('AD[1] < 10 or DP < 30', opposite=True).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C + 0 chr1 100 . G A . . . GT:DP:AD 0/0:26:0,26 ./.:.:. 0/1:18:12,6 + 1 chr1 101 . T C . . . GT:DP:AD ./.:.:. 0/0:31:29,2 0/0:24:24,0 + 2 chr1 102 . T G . . . GT:DP:AD ./.:.:. ./.:.:. 1/1:8:0,8 + + To mark as missing all genotypes whose mean of ``AD`` is below 10: + + >>> vf.markmiss('np.mean(AD) < 10', greedy=True).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C + 0 chr1 100 . G A . . . GT:DP:AD 0/0:26:0,26 ./.:.:. ./.:.:. + 1 chr1 101 . T C . . . GT:DP:AD 0/1:32:16,16 0/0:31:29,2 0/0:24:24,0 + 2 chr1 102 . T G . . . GT:DP:AD ./.:.:. ./.:.:. ./.:.:. + + To do the same as above, but only for the samples A and B: + + >>> vf.markmiss('np.mean(AD) < 10', greedy=True, samples=['A', 'B']).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C + 0 chr1 100 . G A . . . GT:DP:AD 0/0:26:0,26 ./.:.:. 0/1:18:12,6 + 1 chr1 101 . T C . . . GT:DP:AD 0/1:32:16,16 0/0:31:29,2 0/0:24:24,0 + 2 chr1 102 . T G . . . GT:DP:AD ./.:.:. ./.:.:. 1/1:8:0,8 + + To mark as ``NaN`` all genotypes whose sum of ``AD`` is below 10: + + >>> vf.markmiss('sum(AD) < 10', as_nan=True).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C + 0 chr1 100 . G A . . . GT:DP:AD 0/0:26:0,26 ./.:.:. 0/1:18:12,6 + 1 chr1 101 . T C . . . GT:DP:AD 0/1:32:16,16 0/0:31:29,2 0/0:24:24,0 + 2 chr1 102 . T G . . . GT:DP:AD 0/0:.:. ./.:.:. NaN + + Marking as ``NaN`` is useful when, for example, it is necessary to + count how many genotypes are marked: + + >>> vf.markmiss('sum(AD) < 10', as_nan=True).df.isna().sum().sum() + 1 + """""" + genotype_keys = {**RESERVED_GENOTYPE_KEYS, **CUSTOM_GENOTYPE_KEYS} + types = {} + for k, v in genotype_keys.items(): + if v['number'] == 1: + types[k] = v['type'] + else: + types[k] = lambda x: [v['type'](x) for x in x.split(',')] + # Extract unique genotype keys from the expression. + target_keys = re.findall('[a-z]+', expr, flags=re.IGNORECASE) + target_keys = list(set(target_keys)) + target_keys = [x for x in target_keys if x in genotype_keys] + # Define the marking algorithm for each row. + def one_row(r): + row_keys = r.FORMAT.split(':') + # Infer the most appropriate missing value. + if as_nan: + missing = np.nan + else: + missing = row_missval(r) + # Define the marking algorithm for each genotype. + def one_gt(g): + if opposite: + matched, unmatched = g, missing + else: + matched, unmatched = missing, g + subfields = g.split(':') + for target_key in target_keys: + try: + i = row_keys.index(target_key) + x = subfields[i] + ambiguous = not x.replace('.', '').replace('/', '' + ).replace('|', '') + except ValueError: + ambiguous = True + if ambiguous: + if greedy: + return matched + else: + return unmatched + locals()[target_key] = types[target_key](x) + if eval(expr): + return matched + else: + return unmatched + # Apply the marking to each genotype. + if samples is None: + r[9:] = r[9:].apply(one_gt) + else: + r[samples] = r[samples].apply(one_gt) + return r + # Apply the marking to each row. + df = self.df.apply(one_row, axis=1) + vf = self.__class__(self.copy_meta(), df) + return vf + + def empty_samples(self, threshold=0, opposite=False, as_list=False): + """""" + Remove samples with high missingness. + + Samples with missingness >= threshold will be removed. + + Parameters + ---------- + threshold : int or float, default: 0 + Number or fraction of missing variants. By default + (``threshold=0``), only samples with 100% missingness will be + removed. + opposite : bool, default: False + If True, return samples that don't meet the said criteria. + as_list : bool, default: False + If True, return a list of sample names instead of a VcfFrame. + + Returns + ------- + VcfFrame + Subsetted VcfFrame. + + Examples + -------- + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102, 103], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['G', 'T', 'G', 'T'], + ... 'ALT': ['A', 'C', 'C', 'C'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT'], + ... 'A': ['0/0', '0/0', '0/0', '0/0'], + ... 'B': ['./.', '0/0', '0/0', '0/0'], + ... 'C': ['./.', './.', '0/0', '0/0'], + ... 'D': ['./.', './.', './.', '0/0'], + ... 'E': ['./.', './.', './.', './.'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C D E + 0 chr1 100 . G A . . . GT 0/0 ./. ./. ./. ./. + 1 chr1 101 . T C . . . GT 0/0 0/0 ./. ./. ./. + 2 chr1 102 . G C . . . GT 0/0 0/0 0/0 ./. ./. + 3 chr1 103 . T C . . . GT 0/0 0/0 0/0 0/0 ./. + >>> vf.empty_samples().df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C D + 0 chr1 100 . G A . . . GT 0/0 ./. ./. ./. + 1 chr1 101 . T C . . . GT 0/0 0/0 ./. ./. + 2 chr1 102 . G C . . . GT 0/0 0/0 0/0 ./. + 3 chr1 103 . T C . . . GT 0/0 0/0 0/0 0/0 + >>> vf.empty_samples(threshold=2).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B + 0 chr1 100 . G A . . . GT 0/0 ./. + 1 chr1 101 . T C . . . GT 0/0 0/0 + 2 chr1 102 . G C . . . GT 0/0 0/0 + 3 chr1 103 . T C . . . GT 0/0 0/0 + >>> vf.empty_samples(threshold=0.5).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B + 0 chr1 100 . G A . . . GT 0/0 ./. + 1 chr1 101 . T C . . . GT 0/0 0/0 + 2 chr1 102 . G C . . . GT 0/0 0/0 + 3 chr1 103 . T C . . . GT 0/0 0/0 + >>> vf.empty_samples(threshold=0.5, opposite=True).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT C D E + 0 chr1 100 . G A . . . GT ./. ./. ./. + 1 chr1 101 . T C . . . GT ./. ./. ./. + 2 chr1 102 . G C . . . GT 0/0 ./. ./. + 3 chr1 103 . T C . . . GT 0/0 0/0 ./. + >>> vf.empty_samples(threshold=0.5, opposite=True, as_list=True) + ['C', 'D', 'E'] + """""" + total = self.shape[0] + + if not threshold: + threshold = total + + if isinstance(threshold, int): + use_fraction = False + elif isinstance(threshold, float): + use_fraction = True + else: + raise TypeError(""Incorrect argument type 'threshold'"") + + def one_col(c): + data = sum(c.apply(gt_miss)) + if use_fraction: + data /= total + return data + + s = self.df.iloc[:, 9:].apply(one_col, axis=0) < threshold + + if opposite: + s = s[s == False] + else: + s = s[s == True] + + l = s.index.to_list() + + if as_list: + return l + + return self.subset(l) + + def expand(self): + """""" + Expand each multiallelic locus to multiple rows. + + Only the GT subfield of FORMAT will be retained. + + Returns + ------- + VcfFrame + Expanded VcfFrame. + + See Also + -------- + VcfFrame.collapse + Collapse duplicate records in the VcfFrame. + + Examples + -------- + Assume we have the following data: + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102, 103], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['A', 'A', 'C', 'C'], + ... 'ALT': ['C', 'T,G', 'G', 'A,G,CT'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.'], + ... 'FORMAT': ['GT:DP', 'GT:DP', 'GT:DP', 'GT:DP'], + ... 'Steven': ['0/1:32', './.:.', '0/1:27', '0/2:34'], + ... 'Sara': ['0/0:28', '1/2:30', '1/1:29', '1/2:38'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven Sara + 0 chr1 100 . A C . . . GT:DP 0/1:32 0/0:28 + 1 chr1 101 . A T,G . . . GT:DP ./.:. 1/2:30 + 2 chr1 102 . C G . . . GT:DP 0/1:27 1/1:29 + 3 chr1 103 . C A,G,CT . . . GT:DP 0/2:34 1/2:38 + + We can expand each of the multiallelic loci: + + >>> vf.expand().df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven Sara + 0 chr1 100 . A C . . . GT 0/1 0/0 + 1 chr1 101 . A T . . . GT ./. 0/1 + 2 chr1 101 . A G . . . GT ./. 0/1 + 3 chr1 102 . C G . . . GT 0/1 1/1 + 4 chr1 103 . C A . . . GT 0/0 0/1 + 5 chr1 103 . C G . . . GT 0/1 0/1 + 6 chr1 103 . C CT . . . GT 0/0 0/0 + """""" + data = [] + def one_gt(g, i): + if gt_miss(g): + return g + l = g.split('/') + l = ['1' if x == str(i+1) else '0' for x in l] + l = sorted(l) + return '/'.join(l) + for i, r in self.df.iterrows(): + r.FORMAT = 'GT' + r[9:] = r[9:].apply(lambda x: x.split(':')[0]) + alt_alleles = r.ALT.split(',') + if len(alt_alleles) == 1: + data.append(r) + continue + for i, alt_allele in enumerate(alt_alleles): + s = r.copy() + s.ALT = alt_allele + s[9:] = s[9:].apply(one_gt, args=(i,)) + data.append(s) + return self.__class__(self.copy_meta(), pd.concat(data, axis=1).T) + + def filter_bed(self, bed, opposite=False, as_index=False): + """""" + Filter rows intersecting with given BED. + + Only variants intersecting with given BED data will remain. + + Parameters + ---------- + bed : pybed.BedFrame or str + BedFrame or path to a BED file. + opposite : bool, default: False + If True, return rows that don't meet the said criteria. + as_index : bool, default: False + If True, return boolean index array instead of VcfFrame. + + Returns + ------- + VcfFrame or pandas.Series + Filtered VcfFrame or boolean index array. + + Examples + -------- + Assume we have the following data: + + >>> from fuc import pybed, pyvcf + >>> data = { + ... 'Chromosome': ['chr1', 'chr2', 'chr3'], + ... 'Start': [100, 400, 100], + ... 'End': [200, 500, 200] + ... } + >>> bf = pybed.BedFrame.from_dict([], data) + >>> bf.gr.df + Chromosome Start End + 0 chr1 100 200 + 1 chr2 400 500 + 2 chr3 100 200 + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr2', 'chr3'], + ... 'POS': [100, 201, 450, 99], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['G', 'CT', 'A', 'C'], + ... 'ALT': ['A', 'C', 'AT', 'A'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT'], + ... 'Steven': ['0/1', '1/1', '0/1', '0/1'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . G A . . . GT 0/1 + 1 chr1 201 . CT C . . . GT 1/1 + 2 chr2 450 . A AT . . . GT 0/1 + 3 chr3 99 . C A . . . GT 0/1 + + We can select rows that overlap with the BED data: + + >>> vf.filter_bed(bf).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . G A . . . GT 0/1 + 1 chr2 450 . A AT . . . GT 0/1 + + We can also remove those rows: + + >>> vf.filter_bed(bf, opposite=True).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 201 . CT C . . . GT 1/1 + 1 chr3 99 . C A . . . GT 0/1 + + Finally, we can return boolean index array from the filtering: + + >>> vf.filter_bed(bf, as_index=True) + 0 True + 1 False + 2 True + 3 False + dtype: bool + >>> + """""" + if isinstance(bed, pybed.BedFrame): + bf = bed + else: + bf = pybed.BedFrame.from_file(bed) + f = lambda r: not bf.gr[r.CHROM, r.POS:r.POS+1].empty + i = self.df.apply(f, axis=1) + if opposite: + i = ~i + if as_index: + return i + if i.empty: + return self.__class__(self.copy_meta(), self.copy_df()) + return self.__class__(self.copy_meta(), self.df[i]) + + def filter_empty(self, threshold=0, opposite=False, as_index=False): + """""" + Filter rows with high missingness. + + Variants with missingness >= threshold will be removed. + + Parameters + ---------- + threshold: int, default: 0 + Exclude the row if it has a number of missing genotypes that is + greater than or equal to this number. When 0 (default), exclude + rows where all of the samples have a missing genotype. + opposite : bool, default: False + If True, return rows that don't meet the said criteria. + as_index : bool, default: False + If True, return boolean index array instead of VcfFrame. + + Returns + ------- + VcfFrame or pandas.Series + Filtered VcfFrame or boolean index array. + + Examples + -------- + Assume we have the following data: + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102, 103, 104], + ... 'ID': ['.', '.', '.', '.', '.'], + ... 'REF': ['G', 'T', 'A', 'C', 'C'], + ... 'ALT': ['A', 'C', 'T', 'A', 'T'], + ... 'QUAL': ['.', '.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT', 'GT'], + ... 'A': ['0/1', './.', './.', './.', './.'], + ... 'B': ['0/0', '0/1', './.', './.', './.'], + ... 'C': ['0/0', '0/0', '0/1', './.', './.'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C + 0 chr1 100 . G A . . . GT 0/1 0/0 0/0 + 1 chr1 101 . T C . . . GT ./. 0/1 0/0 + 2 chr1 102 . A T . . . GT ./. ./. 0/1 + 3 chr1 103 . C A . . . GT ./. ./. ./. + 4 chr1 104 . C T . . . GT ./. ./. ./. + + We can remove rows that are completely empty: + + >>> vf.filter_empty().df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C + 0 chr1 100 . G A . . . GT 0/1 0/0 0/0 + 1 chr1 101 . T C . . . GT ./. 0/1 0/0 + 2 chr1 102 . A T . . . GT ./. ./. 0/1 + + We can remove rows where at least two samples have missing genotype: + + >>> vf.filter_empty(threshold=2).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C + 0 chr1 100 . G A . . . GT 0/1 0/0 0/0 + 1 chr1 101 . T C . . . GT ./. 0/1 0/0 + + We can show rows that are completely empty: + + >>> vf.filter_empty(opposite=True).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C + 0 chr1 103 . C A . . . GT ./. ./. ./. + 1 chr1 104 . C T . . . GT ./. ./. ./. + + Finally, we can return boolean index array from the filtering: + + >>> vf.filter_empty(as_index=True) + 0 True + 1 True + 2 True + 3 False + 4 False + dtype: bool + """""" + if not threshold: + threshold = self.shape[1] + + def one_row(r): + s = r[9:].apply(gt_miss) + return s.sum() < threshold + + i = self.df.apply(one_row, axis=1) + + if opposite: + i = ~i + if as_index: + return i + if i.empty: + return self.__class__(self.copy_meta(), self.copy_df()) + return self.__class__(self.copy_meta(), self.df[i]) + + def filter_flagall(self, flags, opposite=False, as_index=False): + """""" + Filter rows with all given INFO flags. + + Only variants with all given INFO flags will remain. + + Parameters + ---------- + flags : list + List of INFO flags. + opposite : bool, default: False + If True, return rows that don't meet the said criteria. + as_index : bool, default: False + If True, return boolean index array instead of VcfFrame. + + Returns + ------- + VcfFrame or pandas.Series + Filtered VcfFrame or boolean index array. + + See Also + -------- + VcfFrame.filter_flagany + Similar method that selects rows if any one of the given + INFO flags is present. + + Examples + -------- + Assume we have the following data: + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102, 103], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['G', 'T', 'A', 'C'], + ... 'ALT': ['A', 'C', 'T', 'A'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': ['DB', 'DB;H2', 'DB;H2', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT'], + ... 'Steven': ['0/0', '0/1', '0/1', '0/0'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . G A . . DB GT 0/0 + 1 chr1 101 . T C . . DB;H2 GT 0/1 + 2 chr1 102 . A T . . DB;H2 GT 0/1 + 3 chr1 103 . C A . . . GT 0/0 + + We can select rows with both the H2 and DB tags: + + >>> vf.filter_flagall(['H2', 'DB']).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 101 . T C . . DB;H2 GT 0/1 + 1 chr1 102 . A T . . DB;H2 GT 0/1 + + We can also remove those rows: + + >>> vf.filter_flagall(['H2', 'DB'], opposite=True).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . G A . . DB GT 0/0 + 1 chr1 103 . C A . . . GT 0/0 + + Finally, we can return boolean index array from the filtering: + + >>> vf.filter_flagall(['H2', 'DB'], as_index=True) + 0 False + 1 True + 2 True + 3 False + dtype: bool + """""" + def f(r): + l = r.INFO.split(';') + return all([x in l for x in flags]) + i = self.df.apply(f, axis=1) + if opposite: + i = ~i + if as_index: + return i + if i.empty: + return self.__class__(self.copy_meta(), self.copy_df()) + return self.__class__(self.copy_meta(), self.df[i]) + + def filter_flagany(self, flags, opposite=False, as_index=False): + """""" + Filter rows with any given INFO flags. + + Only variants with any given INFO flags will remain. + + Parameters + ---------- + flags : list + List of INFO flags. + opposite : bool, default: False + If True, return rows that don't meet the said criteria. + as_index : bool, default: False + If True, return boolean index array instead of VcfFrame. + + Returns + ------- + VcfFrame or pandas.Series + Filtered VcfFrame or boolean index array. + + See Also + -------- + VcfFrame.filter_flagall + Similar method that selects rows if all of the given INFO + flags are present. + + Examples + -------- + Assume we have the following data: + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102, 103], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['G', 'T', 'A', 'C'], + ... 'ALT': ['A', 'C', 'T', 'A'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': ['DB', 'DB;H2', 'DB;H2', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT'], + ... 'Steven': ['0/0', '0/1', '0/1', '0/0'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . G A . . DB GT 0/0 + 1 chr1 101 . T C . . DB;H2 GT 0/1 + 2 chr1 102 . A T . . DB;H2 GT 0/1 + 3 chr1 103 . C A . . . GT 0/0 + + We can select rows with the H2 tag: + + >>> vf.filter_flagany(['H2']).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 101 . T C . . DB;H2 GT 0/1 + 1 chr1 102 . A T . . DB;H2 GT 0/1 + + We can also remove those rows: + + >>> vf.filter_flagany(['H2'], opposite=True).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . G A . . DB GT 0/0 + 1 chr1 103 . C A . . . GT 0/0 + + Finally, we can return boolean index array from the filtering: + + >>> vf.filter_flagany(['H2'], as_index=True) + 0 False + 1 True + 2 True + 3 False + dtype: bool + """""" + def f(r): + l = r.INFO.split(';') + return any([x in l for x in flags]) + i = self.df.apply(f, axis=1) + if opposite: + i = ~i + if as_index: + return i + if i.empty: + return self.__class__(self.copy_meta(), self.copy_df()) + return self.__class__(self.copy_meta(), self.df[i]) + + def filter_gsa(self, opposite=False, as_index=False): + """""" + Filter rows specific to Illumina's GSA array. + + This function will remove variants that are specific to Illimina's + Infinium Global Screening (GSA) array. More specifically, variants + are removed if they contain one of the characters {'I', 'D', 'N', + ','} as either REF or ALT. + + Parameters + ---------- + opposite : bool, default: False + If True, return rows that don't meet the said criteria. + as_index : bool, default: False + If True, return boolean index array instead of VcfFrame. + + Returns + ------- + VcfFrame or pandas.Series + Filtered VcfFrame or boolean index array. + + Examples + -------- + Assume we have the following data: + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102, 103], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['D', 'N', 'A', 'C'], + ... 'ALT': ['I', '.', '.', 'A'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT'], + ... 'Steven': ['0/1', '0/0', './.', '0/1'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . D I . . . GT 0/1 + 1 chr1 101 . N . . . . GT 0/0 + 2 chr1 102 . A . . . . GT ./. + 3 chr1 103 . C A . . . GT 0/1 + + We can remove rows that are GSA-specific: + + >>> vf.filter_gsa().df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 103 . C A . . . GT 0/1 + + We can also select those rows: + + >>> vf.filter_gsa(opposite=True).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . D I . . . GT 0/1 + 1 chr1 101 . N . . . . GT 0/0 + 2 chr1 102 . A . . . . GT ./. + + Finally, we can return boolean index array from the filtering: + + >>> vf.filter_gsa(as_index=True) + 0 False + 1 False + 2 False + 3 True + dtype: bool + """""" + def one_row(r): + alleles = ['I', 'D', '.', 'N'] + return r.REF in alleles or r.ALT in alleles + i = ~self.df.apply(one_row, axis=1) + if opposite: + i = ~i + if as_index: + return i + if i.empty: + return self.__class__(self.copy_meta(), self.copy_df()) + return self.__class__(self.copy_meta(), self.df[i]) + + def filter_indel(self, opposite=False, as_index=False): + """""" + Filter rows with indel. + + Variants with indel will be removed. + + Parameters + ---------- + opposite : bool, default: False + If True, return rows that don't meet the said criteria. + as_index : bool, default: False + If True, return boolean index array instead of VcfFrame. + + Returns + ------- + VcfFrame or pandas.Series + Filtered VcfFrame or boolean index array. + + Examples + -------- + Assume we have the following data: + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102, 103], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['G', 'CT', 'A', 'C'], + ... 'ALT': ['A', 'C', 'C,AT', 'A'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT'], + ... 'Steven': ['0/1', '0/1', '1/2', '0/1'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . G A . . . GT 0/1 + 1 chr1 101 . CT C . . . GT 0/1 + 2 chr1 102 . A C,AT . . . GT 1/2 + 3 chr1 103 . C A . . . GT 0/1 + + We can remove rows with an indel: + + >>> vf.filter_indel().df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . G A . . . GT 0/1 + 1 chr1 103 . C A . . . GT 0/1 + + We can also select those rows: + + >>> vf.filter_indel(opposite=True).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 101 . CT C . . . GT 0/1 + 1 chr1 102 . A C,AT . . . GT 1/2 + + Finally, we can return boolean index array from the filtering: + + >>> vf.filter_indel(as_index=True) + 0 True + 1 False + 2 False + 3 True + dtype: bool + """""" + i = ~self.df.apply(row_hasindel, axis=1) + if opposite: + i = ~i + if as_index: + return i + if i.empty: + return self.__class__(self.copy_meta(), self.copy_df()) + return self.__class__(self.copy_meta(), self.df[i]) + + def filter_multialt(self, opposite=False, as_index=False): + """""" + Filter rows with multiple ALT alleles. + + Variants with multiple ALT alleles will be removed. + + Parameters + ---------- + opposite : bool, default: False + If True, return rows that don't meet the said criteria. + as_index : bool, default: False + If True, return boolean index array instead of VcfFrame. + + Returns + ------- + VcfFrame or pandas.Series + Filtered VcfFrame or boolean index array. + + Examples + -------- + + Assume we have the following data: + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102, 103], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['A', 'A', 'C', 'C'], + ... 'ALT': ['C,T', 'T', 'G', 'G,A'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT'], + ... 'A': ['0/2', '0/0', '0/1', './.'], + ... 'B': ['0/1', '0/1', './.', '1/2'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B + 0 chr1 100 . A C,T . . . GT 0/2 0/1 + 1 chr1 101 . A T . . . GT 0/0 0/1 + 2 chr1 102 . C G . . . GT 0/1 ./. + 3 chr1 103 . C G,A . . . GT ./. 1/2 + + We can remove rows with multiple ALT alleles: + + >>> vf.filter_multialt().df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B + 0 chr1 101 . A T . . . GT 0/0 0/1 + 1 chr1 102 . C G . . . GT 0/1 ./. + + We can also select those rows: + + >>> vf.filter_multialt(opposite=True).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B + 0 chr1 100 . A C,T . . . GT 0/2 0/1 + 1 chr1 103 . C G,A . . . GT ./. 1/2 + + Finally, we can return boolean index array from the filtering: + + >>> vf.filter_multialt(as_index=True) + 0 False + 1 True + 2 True + 3 False + dtype: bool + """""" + i = self.df.apply(lambda r: ',' not in r.ALT, axis=1) + if opposite: + i = ~i + if as_index: + return i + if i.empty: + return self.__class__(self.copy_meta(), self.copy_df()) + return self.__class__(self.copy_meta(), self.df[i]) + + def filter_pass(self, opposite=False, as_index=False): + """""" + Filter rows with PASS in FILTER column. + + Only variants with PASS in the FILTER column will remain. + + Parameters + ---------- + opposite : bool, default: False + If True, return rows that don't meet the said criteria. + as_index : bool, default: False + If True, return boolean index array instead of VcfFrame. + + Returns + ------- + VcfFrame or pandas.Series + Filtered VcfFrame or boolean index array. + + Examples + -------- + Assume we have the following data: + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102, 103], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['G', 'T', 'A', 'C'], + ... 'ALT': ['A', 'C', 'T', 'A'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['PASS', 'FAIL', 'PASS', 'FAIL'], + ... 'INFO': ['.', '.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT'], + ... 'Steven': ['0/0', './.', '0/1', './.'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . G A . PASS . GT 0/0 + 1 chr1 101 . T C . FAIL . GT ./. + 2 chr1 102 . A T . PASS . GT 0/1 + 3 chr1 103 . C A . FAIL . GT ./. + + We can select rows with PASS: + + >>> vf.filter_pass().df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . G A . PASS . GT 0/0 + 1 chr1 102 . A T . PASS . GT 0/1 + + We can also remove those rows: + + >>> vf.filter_pass(opposite=True).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 101 . T C . FAIL . GT ./. + 1 chr1 103 . C A . FAIL . GT ./. + + Finally, we can return boolean index array from the filtering: + + >>> vf.filter_pass(as_index=True) + 0 True + 1 False + 2 True + 3 False + dtype: bool + """""" + f = lambda r: r.FILTER == 'PASS' + i = self.df.apply(f, axis=1) + if opposite: + i = ~i + if as_index: + return i + if i.empty: + return self.__class__(self.copy_meta(), self.copy_df()) + return self.__class__(self.copy_meta(), self.df[i]) + + def filter_phased(self, opposite=False, as_index=False): + """""" + Filter rows with phased genotypes. + + Variants with phased genotypes will be removed. + + Parameters + ---------- + opposite : bool, default: False + If True, return rows that don't meet the said criteria. + as_index : bool, default: False + If True, return boolean index array instead of VcfFrame. + + Returns + ------- + VcfFrame or pandas.Series + Filtered VcfFrame or boolean index array. + + Examples + -------- + Assume we have the following data: + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102, 103], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['G', 'CT', 'A', 'C'], + ... 'ALT': ['A', 'C', 'C', 'A'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT'], + ... 'Steven': ['1|0', '0/1', '0/1', '0|1'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . G A . . . GT 1|0 + 1 chr1 101 . CT C . . . GT 0/1 + 2 chr1 102 . A C . . . GT 0/1 + 3 chr1 103 . C A . . . GT 0|1 + + We can remove rows with a phased genotype: + + >>> vf.filter_phased().df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 101 . CT C . . . GT 0/1 + 1 chr1 102 . A C,AT . . . GT 0/1 + + We can also select those rows: + + >>> vf.filter_phased(opposite=True).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . G A . . . GT 1|0 + 1 chr1 103 . C A . . . GT 0|1 + + Finally, we can return boolean index array from the filtering: + + >>> vf.filter_phased(as_index=True) + 0 False + 1 True + 2 True + 3 False + dtype: bool + """""" + f = lambda r: not any(['|' in gt.split(':')[0] for gt in r[9:]]) + i = self.df.apply(f, axis=1) + if opposite: + i = ~i + if as_index: + return i + if i.empty: + return self.__class__(self.copy_meta(), self.copy_df()) + return self.__class__(self.copy_meta(), self.df[i]) + + def filter_polyp(self, opposite=False, as_index=False): + """""" + Filter rows with polyploid genotypes. + + Variants with polyploid genotypes will be removed. + + Parameters + ---------- + opposite : bool, default: False + If True, return rows that don't meet the said criteria. + as_index : bool, default: False + If True, return boolean index array instead of VcfFrame. + + Returns + ------- + VcfFrame or pandas.Series + Filtered VcfFrame or boolean index array. + + Examples + -------- + Assume we have the following data: + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr2', 'chr2'], + ... 'POS': [100, 100, 200, 200], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['A', 'A', 'C', 'C'], + ... 'ALT': ['C', 'T', 'G', 'G'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT'], + ... 'Steven': ['0/0/1', '0/0', '1/1/1', './.'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . A C . . . GT 0/0/1 + 1 chr1 100 . A T . . . GT 0/0 + 2 chr2 200 . C G . . . GT 1/1/1 + 3 chr2 200 . C G . . . GT ./. + + We can remove rows with a polyploid genotype call: + + >>> vf.filter_polyp().df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . A T . . . GT 0/0 + 1 chr2 200 . C G . . . GT ./. + + We can also select those rows: + + >>> vf.filter_polyp(opposite=True).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . A C . . . GT 0/0/1 + 1 chr2 200 . C G . . . GT 1/1/1 + + Finally, we can return boolean index array from the filtering: + + >>> vf.filter_polyp(as_index=True) + 0 False + 1 True + 2 False + 3 True + dtype: bool + """""" + f = lambda r: not any([gt_polyp(x) for x in r[9:]]) + i = self.df.apply(f, axis=1) + if opposite: + i = ~i + if as_index: + return i + if i.empty: + return self.__class__(self.copy_meta(), self.copy_df()) + return self.__class__(self.copy_meta(), self.df[i]) + + def filter_qual(self, threshold, opposite=False, as_index=False): + """""" + Filter rows with low QUAL values. + + Only variants with QUAL >= threashold will remain. + + Parameters + ---------- + threshold : float + Minimum QUAL value. + opposite : bool, default: False + If True, return rows that don't meet the said criteria. + as_index : bool, default: False + If True, return boolean index array instead of VcfFrame. + + Returns + ------- + VcfFrame or pandas.Series + Filtered VcfFrame or boolean index array. + + Examples + -------- + Assume we have the following data: + + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102, 103, 104], + ... 'ID': ['.', '.', '.', '.', '.'], + ... 'REF': ['G', 'T', 'A', 'C', 'C'], + ... 'ALT': ['A', 'C', 'T', 'A', 'T'], + ... 'QUAL': ['.', 30, 19, 41, 29], + ... 'FILTER': ['.', '.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT', 'GT'], + ... 'Steven': ['0/1', '1/1', '0/1', '0/1', '1/1'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . G A . . . GT 0/1 + 1 chr1 101 . T C 30 . . GT 1/1 + 2 chr1 102 . A T 19 . . GT 0/1 + 3 chr1 103 . C A 41 . . GT 0/1 + 4 chr1 104 . C T 29 . . GT 1/1 + + We can select rows with minimum QUAL value of 30: + + >>> vf.filter_qual(30).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 101 . T C 30 . . GT 1/1 + 1 chr1 103 . C A 41 . . GT 0/1 + + We can also remove those rows: + + >>> vf.filter_qual(30, opposite=True).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . G A . . . GT 0/1 + 1 chr1 102 . A T 19 . . GT 0/1 + 2 chr1 104 . C T 29 . . GT 1/1 + + Finally, we can return boolean index array from the filtering: + + >>> vf.filter_qual(30, as_index=True) + 0 False + 1 True + 2 False + 3 True + 4 False + dtype: bool + """""" + def one_row(r): + if isinstance(r.QUAL, str): + return False + return r.QUAL >= threshold + i = self.df.apply(one_row, axis=1) + if opposite: + i = ~i + if as_index: + return i + if i.empty: + return self.__class__(self.copy_meta(), self.copy_df()) + return self.__class__(self.copy_meta(), self.df[i]) + + def filter_sampall(self, samples=None, opposite=False, as_index=False): + """""" + Filter rows where all given samples have variant. + + Only variants where all given samples have variant. The default + behavior is to use all samples in the VcfFrame. + + Parameters + ---------- + samples : list, optional + List of sample names or indicies. + opposite : bool, default: False + If True, return rows that don't meet the said criteria. + as_index : bool, default: False + If True, return boolean index array instead of VcfFrame. + + Returns + ------- + VcfFrame or pandas.Series + Filtered VcfFrame or boolean index array. + + See Also + -------- + VcfFrame.filter_sampany + Similar method that selects rows if any one of the given + samples has the variant. + + Examples + -------- + Assume we have the following data: + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102, 103], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['G', 'T', 'T', 'T'], + ... 'ALT': ['A', 'C', 'A', 'C'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT'], + ... 'Steven': ['0/1', '0/0', '0/1', '0/1'], + ... 'Sara': ['0/1', '0/1', '0/0', '0/1'], + ... 'James': ['0/1', '0/1', '0/1', '0/1'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven Sara James + 0 chr1 100 . G A . . . GT 0/1 0/1 0/1 + 1 chr1 101 . T C . . . GT 0/0 0/1 0/1 + 2 chr1 102 . T A . . . GT 0/1 0/0 0/1 + 3 chr1 103 . T C . . . GT 0/1 0/1 0/1 + + We can select rows where all three samples have the variant: + + >>> vf.filter_sampall().df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven Sara James + 0 chr1 100 . G A . . . GT 0/1 0/1 0/1 + 1 chr1 103 . T C . . . GT 0/1 0/1 0/1 + + We can also remove those rows: + + >>> vf.filter_sampall(opposite=True).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven Sara James + 0 chr1 101 . T C . . . GT 0/0 0/1 0/1 + 1 chr1 102 . T A . . . GT 0/1 0/0 0/1 + + We can select rows where both Sara and James have the variant: + + >>> vf.filter_sampall(samples=['Sara', 'James']).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven Sara James + 0 chr1 100 . G A . . . GT 0/1 0/1 0/1 + 1 chr1 101 . T C . . . GT 0/0 0/1 0/1 + 2 chr1 103 . T C . . . GT 0/1 0/1 0/1 + + Finally, we can return boolean index array from the filtering: + + >>> vf.filter_sampall(as_index=True) + 0 True + 1 False + 2 False + 3 True + dtype: bool + """""" + if samples is None: + samples = self.samples + else: + samples = [x if isinstance(x, str) else self.samples[x] + for x in samples] + f = lambda r: all(r[samples].apply(gt_hasvar)) + i = self.df.apply(f, axis=1) + if opposite: + i = ~i + if as_index: + return i + if i.empty: + return self.__class__(self.copy_meta(), self.copy_df()) + return self.__class__(self.copy_meta(), self.df[i]) + + def filter_sampany(self, samples=None, opposite=False, as_index=False): + """""" + Filter rows where any given samples have variant. + + Only variants where any given samples have variant will remain. The + default behavior is to use all samples in the VcfFrame. + + Parameters + ---------- + samples : list, optional + List of sample names or indicies. + opposite : bool, default: False + If True, return rows that don't meet the said criteria. + as_index : bool, default: False + If True, return boolean index array instead of VcfFrame. + + Returns + ------- + VcfFrame or pandas.Series + Filtered VcfFrame or boolean index array. + + See Also + -------- + VcfFrame.filter_sampall + Similar method that selects rows if all of the given + samples have the variant. + + Examples + -------- + Assume we have the following data: + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102, 103], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['G', 'T', 'T', 'T'], + ... 'ALT': ['A', 'C', 'A', 'C'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT'], + ... 'Steven': ['0/0', '0/0', '0/1', '0/0'], + ... 'Sara': ['0/0', '0/1', '0/0', '0/0'], + ... 'James': ['0/1', '0/0', '0/0', '0/0'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven Sara James + 0 chr1 100 . G A . . . GT 0/0 0/0 0/1 + 1 chr1 101 . T C . . . GT 0/0 0/1 0/0 + 2 chr1 102 . T A . . . GT 0/1 0/0 0/0 + 3 chr1 103 . T C . . . GT 0/0 0/0 0/0 + + We can select rows where at least one sample has the variant: + + >>> vf.filter_sampany().df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven Sara James + 0 chr1 100 . G A . . . GT 0/0 0/0 0/1 + 1 chr1 101 . T C . . . GT 0/0 0/1 0/0 + 2 chr1 102 . T A . . . GT 0/1 0/0 0/0 + + We can also remove those rows: + + >>> vf.filter_sampany(opposite=True).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven Sara James + 0 chr1 103 . T C . . . GT 0/0 0/0 0/0 + + We can select rows where either Sara or James has the variant: + + >>> vf.filter_sampany(samples=['Sara', 'James']).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven Sara James + 0 chr1 100 . G A . . . GT 0/0 0/0 0/1 + 1 chr1 101 . T C . . . GT 0/0 0/1 0/0 + + Finally, we can return boolean index array from the filtering: + + >>> vf.filter_sampany(as_index=True) + 0 True + 1 True + 2 True + 3 False + dtype: bool + """""" + if samples is None: + samples = self.samples + else: + samples = [x if isinstance(x, str) else self.samples[x] + for x in samples] + f = lambda r: any(r[samples].apply(gt_hasvar)) + i = self.df.apply(f, axis=1) + if opposite: + i = ~i + if as_index: + return i + if i.empty: + return self.__class__(self.copy_meta(), self.copy_df()) + return self.__class__(self.copy_meta(), self.df[i]) + + def filter_sampnum(self, threshold, opposite=False, as_index=False): + """""" + Filter rows with high variant prevalence. + + Only variants with variant prevalence >= threshold will remian. + + Parameters + ---------- + threshold : int or float + Minimum number or fraction of samples with the variant. + opposite : bool, default: False + If True, return rows that don't meet the said criteria. + as_index : bool, default: False + If True, return boolean index array instead of VcfFrame. + + Returns + ------- + VcfFrame or pandas.Series + Filtered VcfFrame or boolean index array. + + Examples + -------- + Assume we have the following data: + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102], + ... 'ID': ['.', '.', '.'], + ... 'REF': ['G', 'T', 'T'], + ... 'ALT': ['A', 'C', 'A'], + ... 'QUAL': ['.', '.', '.'], + ... 'FILTER': ['.', '.', '.'], + ... 'INFO': ['.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT'], + ... 'Steven': ['0/1', '0/1', '0/1'], + ... 'Sara': ['0/0', '0/1', '0/0'], + ... 'James': ['0/1', '0/1', '0/0'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven Sara James + 0 chr1 100 . G A . . . GT 0/1 0/0 0/1 + 1 chr1 101 . T C . . . GT 0/1 0/1 0/1 + 2 chr1 102 . T A . . . GT 0/1 0/0 0/0 + + We can select rows where at least two samples have the variant: + + >>> vf.filter_sampnum(2).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven Sara James + 0 chr1 100 . G A . . . GT 0/1 0/0 0/1 + 1 chr1 101 . T C . . . GT 0/1 0/1 0/1 + + Similarly, we can select rows where at least 50% of the samples + have the variant: + + >>> vf.filter_sampnum(0.5).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven Sara James + 0 chr1 100 . G A . . . GT 0/1 0/0 0/1 + 1 chr1 101 . T C . . . GT 0/1 0/1 0/1 + + We can also remove those rows: + + >>> vf.filter_sampnum(0.5, opposite=True).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven Sara James + 0 chr1 102 . T A . . . GT 0/1 0/0 0/0 + + Finally, we can return boolean index array from the filtering: + + >>> vf.filter_sampnum(2, as_index=True) + 0 True + 1 True + 2 False + dtype: bool + """""" + def f(r): + n = r[9:].apply(gt_hasvar).sum() + if isinstance(threshold, int): + return n >= threshold + else: + return n / self.shape[1] >= threshold + i = self.df.apply(f, axis=1) + if opposite: + i = ~i + if as_index: + return i + if i.empty: + return self.__class__(self.copy_meta(), self.copy_df()) + return self.__class__(self.copy_meta(), self.df[i]) + + def filter_vcf(self, vcf, opposite=False, as_index=False): + """""" + Filter rows intersecting with given VCF. + + Only variants intersecting with given VCF data will remain. + + Parameters + ---------- + vcf : VcfFrame or str + VcfFrame or VCF file. + opposite : bool, default: False + If True, return rows that don't meet the said criteria. + as_index : bool, default: False + If True, return boolean index array instead of VcfFrame. + + Returns + ------- + VcfFrame or pandas.Series + Filtered VcfFrame or boolean index array. + + Examples + -------- + Assume we have the following data: + + >>> from fuc import pyvcf + >>> data1 = { + ... 'CHROM': ['chr1', 'chr1', 'chr4', 'chr8', 'chr8'], + ... 'POS': [100, 203, 192, 52, 788], + ... 'ID': ['.', '.', '.', '.', '.'], + ... 'REF': ['A', 'C', 'T', 'T', 'GA'], + ... 'ALT': ['C', 'G', 'A', 'G', 'G'], + ... 'QUAL': ['.', '.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT', 'GT'], + ... 'A': ['0/1', '0/1', '0/1', '0/1', '0/1'], + ... } + >>> vf1 = pyvcf.VcfFrame.from_dict([], data1) + >>> vf1.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A + 0 chr1 100 . A C . . . GT 0/1 + 1 chr1 203 . C G . . . GT 0/1 + 2 chr4 192 . T A . . . GT 0/1 + 3 chr8 52 . T G . . . GT 0/1 + 4 chr8 788 . GA G . . . GT 0/1 + >>> data2 = { + ... 'CHROM': ['chr1', 'chr8'], + ... 'POS': [100, 788], + ... 'ID': ['.', '.'], + ... 'REF': ['A', 'GA'], + ... 'ALT': ['C', 'G'], + ... 'QUAL': ['.', '.'], + ... 'FILTER': ['.', '.'], + ... 'INFO': ['.', '.'], + ... } + >>> vf2 = pyvcf.VcfFrame.from_dict([], data2) + >>> vf2.df + CHROM POS ID REF ALT QUAL FILTER INFO + 0 chr1 100 . A C . . . + 1 chr8 788 . GA G . . . + + We can select rows that overlap with the VCF data: + + >>> vf1.filter_vcf(vf2).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A + 0 chr1 100 . A C . . . GT 0/1 + 1 chr8 788 . GA G . . . GT 0/1 + + We can also remove those rows: + + >>> vf1.filter_vcf(vf2, opposite=True).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A + 0 chr1 203 . C G . . . GT 0/1 + 1 chr4 192 . T A . . . GT 0/1 + 2 chr8 52 . T G . . . GT 0/1 + + Finally, we can return boolean index array from the filtering: + + >>> vf1.filter_vcf(vf2, as_index=True) + 0 True + 1 False + 2 False + 3 False + 4 True + dtype: bool + """""" + if isinstance(vcf, VcfFrame): + vf = vcf + else: + vf = VcfFrame.from_file(vcf) + df1 = self.df[['CHROM', 'POS', 'REF', 'ALT']] + df2 = vf.df[['CHROM', 'POS', 'REF', 'ALT', 'ID']] + df3 = df1.merge(df2, how='left') + i = ~pd.isna(df3.ID) + i.name = None + if opposite: + i = ~i + if as_index: + return i + if i.empty: + return self.__class__(self.copy_meta(), self.copy_df()) + return self.__class__(self.copy_meta(), self.df[i]) + + def subtract(self, a, b): + """""" + Subtract genotype data between two samples (A, B). + + This method can be especially useful when you want to distinguish + between somatic and germline variants for an individual. See examples + below for more details. + + Parameters + ---------- + a, b : str or int + Name or index of Samples A and B. + + Returns + ------- + pandas.Series + Resulting VCF column. + + See Also + -------- + VcfFrame.combine + Combine genotype data from two samples (A, B). + + Examples + -------- + Assume we have following data for a cancer patient: + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102, 103, 104], + ... 'ID': ['rs1', 'rs2', 'rs3', 'rs4', 'rs5'], + ... 'REF': ['G', 'T', 'C', 'A', 'G'], + ... 'ALT': ['A', 'G', 'T', 'C', 'C'], + ... 'QUAL': ['.', '.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT', 'GT'], + ... 'Tissue': ['./.', '0/1', '0/1', '0/0', '0/1'], + ... 'Blood': ['0/1', '0/1', './.', '0/1', '0/0'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Tissue Blood + 0 chr1 100 rs1 G A . . . GT ./. 0/1 + 1 chr1 101 rs2 T G . . . GT 0/1 0/1 + 2 chr1 102 rs3 C T . . . GT 0/1 ./. + 3 chr1 103 rs4 A C . . . GT 0/0 0/1 + 4 chr1 104 rs5 G C . . . GT 0/1 0/0 + + We can compare genotype data between 'Tissue' and 'Blood' to identify + somatic variants (i.e. rs3 and rs5; rs2 is most likely germline): + + >>> vf.df['Somatic'] = vf.subtract('Tissue', 'Blood') + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Tissue Blood Somatic + 0 chr1 100 rs1 G A . . . GT ./. 0/1 ./. + 1 chr1 101 rs2 T G . . . GT 0/1 0/1 ./. + 2 chr1 102 rs3 C T . . . GT 0/1 ./. 0/1 + 3 chr1 103 rs4 A C . . . GT 0/0 0/1 0/0 + 4 chr1 104 rs5 G C . . . GT 0/1 0/0 0/1 + """""" + a = a if isinstance(a, str) else self.samples[a] + b = b if isinstance(b, str) else self.samples[b] + def func(r): + m = row_missval(r) + a_has = gt_hasvar(r[a]) + b_bas = gt_hasvar(r[b]) + if a_has and b_bas: + return m + elif a_has and not b_bas: + return r[a] + elif not a_has and b_bas: + return r[a] + else: + return r[a] + s = self.df.apply(func, axis=1) + return s + + def sort(self): + """""" + Sort the VcfFrame by chromosome and position. + + Returns + ------- + VcfFrame + Sorted VcfFrame. + + Examples + -------- + Assume we have the following data: + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr10', 'chr2', 'chr1', 'chr2'], + ... 'POS': [100, 101, 102, 90], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['G', 'T', 'T', 'A'], + ... 'ALT': ['A', 'C', 'A', 'T'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.'], + ... 'FORMAT': ['GT:DP', 'GT:DP', 'GT:DP', 'GT:DP'], + ... 'Steven': ['./.:.', '0/0:29', '0/0:28', '0/1:17'] + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr10 100 . G A . . . GT:DP ./.:. + 1 chr2 101 . T C . . . GT:DP 0/0:29 + 2 chr1 102 . T A . . . GT:DP 0/0:28 + 3 chr2 90 . A T . . . GT:DP 0/1:17 + + We can sort the VcfFrame by: + + >>> vf.sort().df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 102 . T A . . . GT:DP 0/0:28 + 1 chr2 90 . A T . . . GT:DP 0/1:17 + 2 chr2 101 . T C . . . GT:DP 0/0:29 + 3 chr10 100 . G A . . . GT:DP ./.:. + """""" + def f(col): + return [CONTIGS.index(x) if x in CONTIGS + else len(CONTIGS) if isinstance(x, str) + else x for x in col] + + df = self.df.sort_values(by=['CHROM', 'POS'], + ignore_index=True, key=f) + vf = self.__class__(self.copy_meta(), df) + + return vf + + def subset(self, samples, exclude=False): + """""" + Subset VcfFrame for specified samples. + + Parameters + ---------- + samples : str or list + Sample name or list of names (the order matters). + exclude : bool, default: False + If True, exclude specified samples. + + Returns + ------- + VcfFrame + Subsetted VcfFrame. + + Examples + -------- + Assume we have the following data: + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1'], + ... 'POS': [100, 101], + ... 'ID': ['.', '.'], + ... 'REF': ['G', 'T'], + ... 'ALT': ['A', 'C'], + ... 'QUAL': ['.', '.'], + ... 'FILTER': ['.', '.'], + ... 'INFO': ['.', '.'], + ... 'FORMAT': ['GT', 'GT'], + ... 'A': ['0/1', '0/1'], + ... 'B': ['0/0', '0/1'], + ... 'C': ['0/0', '0/0'], + ... 'D': ['0/1', '0/0'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C D + 0 chr1 100 . G A . . . GT 0/1 0/0 0/0 0/1 + 1 chr1 101 . T C . . . GT 0/1 0/1 0/0 0/0 + + We can subset the VcfFrame for the samples A and B: + + >>> vf.subset(['A', 'B']).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B + 0 chr1 100 . G A . . . GT 0/1 0/0 + 1 chr1 101 . T C . . . GT 0/1 0/1 + + Alternatively, we can exclude those samples: + + >>> vf.subset(['A', 'B'], exclude=True).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT C D + 0 chr1 100 . G A . . . GT 0/0 0/1 + 1 chr1 101 . T C . . . GT 0/0 0/0 + """""" + if isinstance(samples, str): + samples = [samples] + if exclude: + samples = [x for x in self.samples if x not in samples] + cols = self.df.columns[:9].to_list() + samples + df = self.df[cols] + vf = self.__class__(self.copy_meta(), df) + return vf + + def unphase(self): + """""" + Unphase all the sample genotypes. + + Returns + ------- + VcfFrame + Unphased VcfFrame. + + Examples + -------- + Assume we have the following data: + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102, 103], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['G', 'T', 'A', 'C'], + ... 'ALT': ['A', 'C', 'T', 'A'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT'], + ... 'Steven': ['1|0', './.', '0|1', '0/1'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . G A . . . GT 1|0 + 1 chr1 101 . T C . . . GT ./. + 2 chr1 102 . A T . . . GT 0|1 + 3 chr1 103 . C A . . . GT 0/1 + + We can unphase the samples genotypes: + + >>> vf.unphase().df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . G A . . . GT 0/1 + 1 chr1 101 . T C . . . GT ./. + 2 chr1 102 . A T . . . GT 0/1 + 3 chr1 103 . C A . . . GT 0/1 + """""" + def func(r): + r[9:] = r[9:].apply(gt_unphase) + return r + df = self.df.apply(func, axis=1) + vf = self.__class__(self.copy_meta(), df) + return vf + + def slice(self, region): + """""" + Slice VcfFrame for specified region. + + Parameters + ---------- + region : str + Region to slice ('chrom:start-end'). The 'chr' string will be + handled automatically. For example, 'chr1' and '1' will have the + same effect in slicing. + + Returns + ------- + VcfFrame + Sliced VcfFrame. + + Examples + -------- + + Assume we have following data: + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chr2'], + ... 'POS': [100, 205, 297, 101], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['G', 'T', 'A', 'C'], + ... 'ALT': ['A', 'C', 'T', 'A'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT'], + ... 'A': ['0/1', '1/1', '0/0', '0/0'], + ... 'B': ['0/0', '0/0', '0/1', '0/1'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B + 0 chr1 100 . G A . . . GT 0/1 0/0 + 1 chr1 205 . T C . . . GT 1/1 0/0 + 2 chr1 297 . A T . . . GT 0/0 0/1 + 3 chr2 101 . C A . . . GT 0/0 0/1 + + We can specify a full region: + + >>> vf.slice('chr1:101-300').df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B + 0 chr1 205 . T C . . . GT 1/1 0/0 + 1 chr1 297 . A T . . . GT 0/0 0/1 + + We can specify a region without the 'chr' string: + + >>> vf.slice('1:101-300').df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B + 0 chr1 205 . T C . . . GT 1/1 0/0 + 1 chr1 297 . A T . . . GT 0/0 0/1 + + We can specify the contig only: + + >>> vf.slice('chr1').df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B + 0 chr1 100 . G A . . . GT 0/1 0/0 + 1 chr1 205 . T C . . . GT 1/1 0/0 + 2 chr1 297 . A T . . . GT 0/0 0/1 + + We can omit the start position: + + >>> vf.slice('chr1:-296').df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B + 0 chr1 100 . G A . . . GT 0/1 0/0 + 1 chr1 205 . T C . . . GT 1/1 0/0 + + We can omit the end position as well: + + >>> vf.slice('chr1:101').df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B + 0 chr1 205 . T C . . . GT 1/1 0/0 + 1 chr1 297 . A T . . . GT 0/0 0/1 + + You can also omit the end position this way: + + >>> vf.slice('chr1:101-').df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B + 0 chr1 205 . T C . . . GT 1/1 0/0 + 1 chr1 297 . A T . . . GT 0/0 0/1 + """""" + if self.has_chr_prefix: + region = common.update_chr_prefix(region, mode='add') + else: + region = common.update_chr_prefix(region, mode='remove') + chrom, start, end = common.parse_region(region) + df = self.df[self.df.CHROM == chrom] + if not pd.isna(start): + df = df[df.POS >= start] + if not pd.isna(end): + df = df[df.POS <= end] + return self.__class__(self.copy_meta(), df) + + def extract_format(self, k, func=None, as_nan=False): + """""" + Extract data for the specified FORMAT key. + + By default, this method will return string data. Use ``func`` and + ``as_nan`` to output numbers. Alternatvely, select one of the special + keys for ``k``, which have predetermined values of ``func`` and + ``as_nan`` for convenience. + + Parameters + ---------- + k : str + FORMAT key to use when extracting data. In addition to regular + FORMAT keys (e.g. 'DP', 'AD'), the method also accepts the + special keys listed below: + + - '#DP': Return numeric DP. + - '#AD_REF': Return numeric AD for REF. + - '#AD_ALT': Return numeric AD for ALT. If multiple values are + available (i.e. multiallelic site), return the sum. + - '#AD_FRAC_REF': Return allele fraction for REF. + - '#AD_FRAC_ALT': Return allele fraction for ALT. If multiple + values are available (i.e. multiallelic site), return the sum. + + func : function, optional + Function to apply to each of the extracted results. + as_nan : bool, default: False + If True, return missing values as ``NaN``. + + Returns + ------- + pandas.DataFrame + DataFrame containing requested data. + + Examples + -------- + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102], + ... 'ID': ['.', '.', '.'], + ... 'REF': ['A', 'C', 'A'], + ... 'ALT': ['G', 'T', 'C,T'], + ... 'QUAL': ['.', '.', '.'], + ... 'FILTER': ['.', '.', '.'], + ... 'INFO': ['.', '.', '.'], + ... 'FORMAT': ['GT:AD:DP', 'GT', 'GT:AD:DP'], + ... 'A': ['0/1:15,13:28', '0/0', '0/1:9,14,0:23'], + ... 'B': ['./.:.:.', '1/1', '1/2:0,11,15:26'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B + 0 chr1 100 . A G . . . GT:AD:DP 0/1:15,13:28 ./.:.:. + 1 chr1 101 . C T . . . GT 0/0 1/1 + 2 chr1 102 . A C,T . . . GT:AD:DP 0/1:9,14,0:23 1/2:0,11,15:26 + >>> vf.extract_format('GT') + A B + 0 0/1 ./. + 1 0/0 1/1 + 2 0/1 1/2 + >>> vf.extract_format('GT', as_nan=True) + A B + 0 0/1 NaN + 1 0/0 1/1 + 2 0/1 1/2 + >>> vf.extract_format('AD') + A B + 0 15,13 . + 1 NaN NaN + 2 9,14,0 0,11,15 + >>> vf.extract_format('DP', func=lambda x: int(x), as_nan=True) + A B + 0 28.0 NaN + 1 NaN NaN + 2 23.0 26.0 + >>> vf.extract_format('#DP') # Same as above + A B + 0 28.0 NaN + 1 NaN NaN + 2 23.0 26.0 + >>> vf.extract_format('AD', func=lambda x: float(x.split(',')[0]), as_nan=True) + A B + 0 15.0 NaN + 1 NaN NaN + 2 9.0 0.0 + >>> vf.extract_format('#AD_REF') # Same as above + A B + 0 15.0 NaN + 1 NaN NaN + 2 9.0 0.0 + """""" + def one_row(r, k, func, as_nan): + try: + i = r.FORMAT.split(':').index(k) + except ValueError: + return pd.Series([np.nan] * len(self.samples), index=self.samples) + def one_gt(g): + if k == 'GT' and gt_miss(g) and as_nan: + return np.nan + v = g.split(':')[i] + if v == '.' and as_nan: + return np.nan + if func is not None: + return func(v) + return v + return r[9:].apply(one_gt) + + if k in FORMAT_SPECIAL_KEYS: + k, func, as_nan = FORMAT_SPECIAL_KEYS[k] + + df = self.df.apply(one_row, args=(k, func, as_nan), axis=1) + + return df + + def extract_info(vf, k, func=None, as_nan=False): + """""" + Extract data for the specified INFO key. + + By default, this method will return string data. Use ``func`` and + ``as_nan`` to output numbers. Alternatvely, select one of the special + keys for ``k``, which have predetermined values of ``func`` and + ``as_nan`` for convenience. + + Parameters + ---------- + k : str + INFO key to use when extracting data. In addition to regular + INFO keys (e.g. 'AC', 'AF'), the method also accepts the + special keys listed below: + + - '#AC': Return numeric AC. If multiple values are available + (i.e. multiallelic site), return the sum. + - '#AF': Similar to '#AC'. + + func : function, optional + Function to apply to each of the extracted results. + as_nan : bool, default: False + If True, return missing values as ``NaN``. + + Returns + ------- + pandas.Series + Requested data. + + Examples + -------- + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102, 103], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['A', 'C', 'A', 'A'], + ... 'ALT': ['G', 'T', 'C,T', 'T'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': ['AC=1;AF=0.167;H2', 'AC=2;AF=0.333', 'AC=1,2;AF=0.167,0.333;H2', 'AC=.;AF=.'], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT'], + ... 'A': ['0/1', '0/0', '0/1', './.'], + ... 'B': ['0/0', '1/1', '0/2', './.'], + ... 'C': ['0/0', '0/0', '0/2', './.'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C + 0 chr1 100 . A G . . AC=1;AF=0.167;H2 GT 0/1 0/0 0/0 + 1 chr1 101 . C T . . AC=2;AF=0.333 GT 0/0 1/1 0/0 + 2 chr1 102 . A C,T . . AC=1,2;AF=0.167,0.333;H2 GT 0/1 0/2 0/2 + 3 chr1 103 . A T . . AC=.;AF=. GT ./. ./. ./. + >>> vf.extract_info('H2') + 0 H2 + 1 NaN + 2 H2 + 3 NaN + dtype: object + >>> vf.extract_info('AC') + 0 1 + 1 2 + 2 1,2 + 3 . + dtype: object + >>> vf.extract_info('AC', as_nan=True) + 0 1 + 1 2 + 2 1,2 + 3 NaN + dtype: object + >>> vf.extract_info('AC', func=lambda x: sum([int(x) for x in x.split(',')]), as_nan=True) + 0 1.0 + 1 2.0 + 2 3.0 + 3 NaN + dtype: float64 + >>> vf.extract_info('#AC') # Same as above + 0 1.0 + 1 2.0 + 2 3.0 + 3 NaN + dtype: float64 + """""" + def one_row(r, k, func, as_nan): + d = {} + + for field in r.INFO.split(';'): + if '=' not in field: + d[field] = field + else: + d[field.split('=')[0]] = field.split('=')[1] + + try: + result = d[k] + except KeyError: + return np.nan + + if result == '.' and as_nan: + return np.nan + + if func is not None: + return func(result) + + return result + + if k in INFO_SPECIAL_KEYS: + k, func, as_nan = INFO_SPECIAL_KEYS[k] + + s = vf.df.apply(one_row, args=(k, func, as_nan), axis=1) + + return s + + def rename(self, names, indicies=None): + """""" + Rename the samples. + + Parameters + ---------- + names : dict or list + Dict of old names to new names or list of new names. + indicies : list or tuple, optional + List of 0-based sample indicies. Alternatively, a tuple + (int, int) can be used to specify an index range. + + Returns + ------- + VcfFrame + Updated VcfFrame. + + Examples + -------- + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr2'], + ... 'POS': [100, 101], + ... 'ID': ['.', '.'], + ... 'REF': ['G', 'T'], + ... 'ALT': ['A', 'C'], + ... 'QUAL': ['.', '.'], + ... 'FILTER': ['.', '.'], + ... 'INFO': ['.', '.'], + ... 'FORMAT': ['GT', 'GT'], + ... 'A': ['0/1', '0/1'], + ... 'B': ['0/1', '0/1'], + ... 'C': ['0/1', '0/1'], + ... 'D': ['0/1', '0/1'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B C D + 0 chr1 100 . G A . . . GT 0/1 0/1 0/1 0/1 + 1 chr2 101 . T C . . . GT 0/1 0/1 0/1 0/1 + >>> vf.rename(['1', '2', '3', '4']).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT 1 2 3 4 + 0 chr1 100 . G A . . . GT 0/1 0/1 0/1 0/1 + 1 chr2 101 . T C . . . GT 0/1 0/1 0/1 0/1 + >>> vf.rename({'B': '2', 'C': '3'}).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A 2 3 D + 0 chr1 100 . G A . . . GT 0/1 0/1 0/1 0/1 + 1 chr2 101 . T C . . . GT 0/1 0/1 0/1 0/1 + >>> vf.rename(['2', '4'], indicies=[1, 3]).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A 2 C 4 + 0 chr1 100 . G A . . . GT 0/1 0/1 0/1 0/1 + 1 chr2 101 . T C . . . GT 0/1 0/1 0/1 0/1 + >>> vf.rename(['2', '3'], indicies=(1, 3)).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A 2 3 D + 0 chr1 100 . G A . . . GT 0/1 0/1 0/1 0/1 + 1 chr2 101 . T C . . . GT 0/1 0/1 0/1 0/1 + """""" + samples = common.rename(self.samples, names, indicies=indicies) + columns = self.df.columns[:9].to_list() + samples + vf = self.copy() + vf.df.columns = columns + return vf + + def duplicated(self, subset=None, keep='first'): + """""" + Return boolean Series denoting duplicate rows in VcfFrame. + + This method essentially wraps the :meth:`pandas.DataFrame.duplicated` + method. + + Considering certain columns is optional. + + Parameters + ---------- + subset : column label or sequence of labels, optional + Only consider certain columns for identifying duplicates, by + default use all of the columns. + keep : {'first', 'last', False}, default 'first' + Determines which duplicates (if any) to keep. + + - ``first`` : Mark duplicates as ``True`` except for the first + occurrence. + - ``last`` : Mark duplicates as ``True`` except for the last + occurrence. + - False : Mark all duplicates as ``True``. + + Returns + ------- + Series + Boolean series for each duplicated rows. + + Examples + -------- + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr2', 'chr2'], + ... 'POS': [100, 100, 200, 200], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['A', 'A', 'C', 'C'], + ... 'ALT': ['C', 'T', 'G', 'G,A'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT'], + ... 'A': ['0/1', './.', '0/1', './.'], + ... 'B': ['./.', '0/1', './.', '1/2'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B + 0 chr1 100 . A C . . . GT 0/1 ./. + 1 chr1 100 . A T . . . GT ./. 0/1 + 2 chr2 200 . C G . . . GT 0/1 ./. + 3 chr2 200 . C G,A . . . GT ./. 1/2 + >>> vf.duplicated(['CHROM', 'POS', 'REF']) + 0 False + 1 True + 2 False + 3 True + dtype: bool + >>> vf.duplicated(['CHROM', 'POS', 'REF'], keep='last') + 0 True + 1 False + 2 True + 3 False + dtype: bool + """""" + return self.df.duplicated(subset=subset, keep=keep) + + def drop_duplicates(self, subset=None, keep='first'): + """""" + Return VcfFrame with duplicate rows removed. + + This method essentially wraps the + :meth:`pandas.DataFrame.drop_duplicates` method. + + Considering certain columns is optional. + + Parameters + ---------- + subset : column label or sequence of labels, optional + Only consider certain columns for identifying duplicates, by + default use all of the columns. + keep : {'first', 'last', False}, default 'first' + Determines which duplicates (if any) to keep. + + - ``first`` : Drop duplicates except for the first occurrence. + - ``last`` : Drop duplicates except for the last occurrence. + - False : Drop all duplicates. + + Returns + ------- + VcfFrame + VcfFrame with duplicates removed. + + Examples + -------- + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr2', 'chr2'], + ... 'POS': [100, 100, 200, 200], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['A', 'A', 'C', 'C'], + ... 'ALT': ['C', 'T', 'G', 'G,A'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT'], + ... 'A': ['0/1', './.', '0/1', './.'], + ... 'B': ['./.', '0/1', './.', '1/2'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B + 0 chr1 100 . A C . . . GT 0/1 ./. + 1 chr1 100 . A T . . . GT ./. 0/1 + 2 chr2 200 . C G . . . GT 0/1 ./. + 3 chr2 200 . C G,A . . . GT ./. 1/2 + >>> vf.drop_duplicates(['CHROM', 'POS', 'REF']).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B + 0 chr1 100 . A C . . . GT 0/1 ./. + 1 chr2 200 . C G . . . GT 0/1 ./. + >>> vf.drop_duplicates(['CHROM', 'POS', 'REF'], keep='last').df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B + 0 chr1 100 . A T . . . GT ./. 0/1 + 1 chr2 200 . C G,A . . . GT ./. 1/2 + """""" + df = self.df.drop_duplicates(subset=subset, keep=keep) + return self.__class__(self.copy_meta(), df) + + def plot_titv( + self, af=None, group_col=None, group_order=None, flip=False, ax=None, + figsize=None, **kwargs + ): + """""" + Create a box plot showing the :ref:`Ti/Tv ` proportions of samples. + + Under the hood, this method simply converts the VcfFrame to the + :class:`pymaf.MafFrame` class and then applies the + :meth:`pymaf.MafFrame.plot_titv` method. + + Parameters + ---------- + af : AnnFrame, optional + AnnFrame containing sample annotation data. + group_col : str, optional + AnnFrame column containing sample group information. + group_order : list, optional + List of sample group names. + flip : bool, default: False + If True, flip the x and y axes. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`seaborn.boxplot`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + See Also + -------- + fuc.api.pymaf.MafFrame.plot_titv + Similar method for the :class:`fuc.api.pymaf.MafFrame` class. + + Examples + -------- + Below is a simple example: + + .. plot:: + :context: close-figs + + >>> import matplotlib.pyplot as plt + >>> from fuc import common, pyvcf + >>> common.load_dataset('tcga-laml') + >>> vcf_file = '~/fuc-data/tcga-laml/tcga_laml.vcf' + >>> vf = pyvcf.VcfFrame.from_file(vcf_file) + >>> vf.plot_titv() + >>> plt.tight_layout() + + We can create a grouped bar plot based on FAB classification: + + .. plot:: + :context: close-figs + + >>> annot_file = '~/fuc-data/tcga-laml/tcga_laml_annot.tsv' + >>> af = common.AnnFrame.from_file(annot_file, sample_col=0) + >>> vf.plot_titv(af=af, + ... group_col='FAB_classification', + ... group_order=['M0', 'M1', 'M2']) + >>> plt.tight_layout() + """""" + mf = pymaf.MafFrame.from_vcf(self) + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + mf.plot_titv( + af=af, group_col=group_col, group_order=group_order, flip=flip, + ax=ax, figsize=figsize, **kwargs + ) + + return ax + + def plot_rainfall( + self, sample, palette=None, ax=None, figsize=None, legend='auto', + **kwargs + ): + """""" + Create a rainfall plot visualizing inter-variant distance on a linear + genomic scale for single sample. + + Under the hood, this method simply converts the VcfFrame to the + :class:`fuc.api.pymaf.MafFrame` class and then applies the + :meth:`fuc.api.pymaf.MafFrame.plot_rainfall` method. + + Parameters + ---------- + sample : str + Name of the sample. + palette : str, optional + Name of the seaborn palette. See the :ref:`tutorials:Control plot + colors` tutorial for details. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`seaborn.scatterplot`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + See Also + -------- + fuc.api.pymaf.MafFrame.plot_rainfall + Similar method for the :meth:`fuc.api.pymaf.MafFrame` class. + + Examples + -------- + + .. plot:: + + >>> import matplotlib.pyplot as plt + >>> import seaborn as sns + >>> from fuc import common, pyvcf + >>> common.load_dataset('brca') + >>> vcf_file = '~/fuc-data/brca/brca.vcf' + >>> vf = pyvcf.VcfFrame.from_file(vcf_file) + >>> vf.plot_rainfall('TCGA-A8-A08B', + ... figsize=(14, 7), + ... palette=sns.color_palette('Set2')[:6]) + >>> plt.tight_layout() + """""" + mf = pymaf.MafFrame.from_vcf(self) + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + mf.plot_rainfall( + sample, palette=palette, ax=ax, legend=legend, **kwargs + ) + + return ax + + def plot_snvclsc( + self, af=None, group_col=None, group_order=None, palette=None, + flip=False, ax=None, figsize=None, **kwargs + ): + """""" + Create a bar plot summarizing the count distrubtions of the six + :ref:`glossary:SNV classes` for all samples. + + A grouped bar plot can be created with ``group_col`` (requires an AnnFrame). + + Under the hood, this method simply converts the VcfFrame to the + :class:`fuc.api.pymaf.MafFrame` class and then applies the + :meth:`fuc.api.pymaf.MafFrame.plot_snvclsc` method. + + Parameters + ---------- + af : AnnFrame, optional + AnnFrame containing sample annotation data. + group_col : str, optional + AnnFrame column containing sample group information. + group_order : list, optional + List of sample group names. + palette : str, optional + Name of the seaborn palette. See the :ref:`tutorials:Control plot + colors` tutorial for details. + flip : bool, default: False + If True, flip the x and y axes. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`seaborn.barplot`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + See Also + -------- + fuc.api.pymaf.MafFrame.plot_snvclsc + Similar method for the :meth:`fuc.api.pymaf.MafFrame` class. + + Examples + -------- + Below is a simple example: + + .. plot:: + :context: close-figs + + >>> import matplotlib.pyplot as plt + >>> import seaborn as sns + >>> from fuc import common, pyvcf + >>> common.load_dataset('tcga-laml') + >>> vcf_file = '~/fuc-data/tcga-laml/tcga_laml.vcf' + >>> vf = pyvcf.VcfFrame.from_file(vcf_file) + >>> vf.plot_snvclsc(palette=sns.color_palette('Pastel1')) + >>> plt.tight_layout() + + We can create a grouped bar plot based on FAB classification: + + .. plot:: + :context: close-figs + + >>> annot_file = '~/fuc-data/tcga-laml/tcga_laml_annot.tsv' + >>> af = common.AnnFrame.from_file(annot_file, sample_col=0) + >>> vf.plot_snvclsc(af=af, + ... group_col='FAB_classification', + ... group_order=['M0', 'M1', 'M2']) + >>> plt.tight_layout() + """""" + mf = pymaf.MafFrame.from_vcf(self) + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + mf.plot_snvclsc( + af=af, group_col=group_col, group_order=group_order, + palette=palette, flip=flip, ax=ax, **kwargs + ) + + return ax + + def plot_snvclsp( + self, af=None, group_col=None, group_order=None, palette=None, flip=False, + ax=None, figsize=None, **kwargs + ): + """""" + Create a box plot summarizing the proportion distrubtions of the six + :ref:`glossary:SNV classes` for all sample. + + Under the hood, this method simply converts the VcfFrame to the + :class:`fuc.api.pymaf.MafFrame` class and then applies the + :meth:`fuc.api.pymaf.MafFrame.plot_snvclsp` method. + + Parameters + ---------- + af : AnnFrame, optional + AnnFrame containing sample annotation data. + group_col : str, optional + AnnFrame column containing sample group information. + group_order : list, optional + List of sample group names. + palette : str, optional + Name of the seaborn palette. See the :ref:`tutorials:Control plot + colors` tutorial for details. + flip : bool, default: False + If True, flip the x and y axes. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`seaborn.boxplot`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + See Also + -------- + fuc.api.pymaf.MafFrame.plot_snvclsp + Similar method for the :meth:`fuc.api.pymaf.MafFrame` class. + + Examples + -------- + Below is a simple example: + + .. plot:: + :context: close-figs + + >>> import matplotlib.pyplot as plt + >>> import seaborn as sns + >>> from fuc import common, pyvcf + >>> common.load_dataset('tcga-laml') + >>> vcf_file = '~/fuc-data/tcga-laml/tcga_laml.vcf' + >>> vf = pyvcf.VcfFrame.from_file(vcf_file) + >>> vf.plot_snvclsp(palette=sns.color_palette('Pastel1')) + >>> plt.tight_layout() + + We can create a grouped bar plot based on FAB classification: + + .. plot:: + :context: close-figs + + >>> annot_file = '~/fuc-data/tcga-laml/tcga_laml_annot.tsv' + >>> af = common.AnnFrame.from_file(annot_file, sample_col=0) + >>> vf.plot_snvclsp(af=af, + ... group_col='FAB_classification', + ... group_order=['M0', 'M1', 'M2']) + >>> plt.tight_layout() + """""" + mf = pymaf.MafFrame.from_vcf(self) + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + mf.plot_snvclsp( + af=af, group_col=group_col, group_order=group_order, + palette=palette, flip=flip, ax=ax, **kwargs + ) + + return ax + + def plot_snvclss( + self, color=None, colormap=None, width=0.8, legend=True, flip=False, + ax=None, figsize=None, **kwargs + ): + """""" + Create a bar plot showing the proportions of the six + :ref:`glossary:SNV classes` for individual samples. + + Under the hood, this method simply converts the VcfFrame to the + :class:`fuc.api.pymaf.MafFrame` class and then applies the + :meth:`fuc.api.pymaf.MafFrame.plot_snvclss` method. + + Parameters + ---------- + color : list, optional + List of color tuples. See the :ref:`tutorials:Control plot + colors` tutorial for details. + colormap : str or matplotlib colormap object, optional + Colormap to select colors from. See the :ref:`tutorials:Control + plot colors` tutorial for details. + width : float, default: 0.8 + The width of the bars. + legend : bool, default: True + Place legend on axis subplots. + flip : bool, default: False + If True, flip the x and y axes. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`pandas.DataFrame.plot.bar` or + :meth:`pandas.DataFrame.plot.barh`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + See Also + -------- + fuc.api.pymaf.MafFrame.plot_snvclss + Similar method for the :meth:`fuc.api.pymaf.MafFrame` class. + + Examples + -------- + + .. plot:: + + >>> import matplotlib.pyplot as plt + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> ax = mf.plot_snvclss(width=1, color=plt.get_cmap('Pastel1').colors) + >>> ax.legend(loc='upper right') + >>> plt.tight_layout() + """""" + mf = pymaf.MafFrame.from_vcf(self) + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + mf.plot_snvclss( + color=color, colormap=colormap, width=width, legend=legend, + flip=flip, af=af, **kwargs + ) + + return ax + + def update_chr_prefix(self, mode='remove'): + """""" + Add or remove the (annoying) 'chr' string from the CHROM column. + + Parameters + ---------- + mode : {'add', 'remove'}, default: 'remove' + Whether to add or remove the 'chr' string. + + Returns + ------- + VcfFrame + Updated VcfFrame. + + Examples + -------- + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr1', '2', '2'], + ... 'POS': [100, 101, 100, 101], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['G', 'T', 'T', 'C'], + ... 'ALT': ['A', 'C', 'C', 'G'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT'], + ... 'A': ['0/1', '0/1', '0/1', '0/1'] + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A + 0 chr1 100 . G A . . . GT 0/1 + 1 chr1 101 . T C . . . GT 0/1 + 2 2 100 . T C . . . GT 0/1 + 3 2 101 . C G . . . GT 0/1 + >>> vf.update_chr_prefix(mode='remove').df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A + 0 1 100 . G A . . . GT 0/1 + 1 1 101 . T C . . . GT 0/1 + 2 2 100 . T C . . . GT 0/1 + 3 2 101 . C G . . . GT 0/1 + >>> vf.update_chr_prefix(mode='add').df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A + 0 chr1 100 . G A . . . GT 0/1 + 1 chr1 101 . T C . . . GT 0/1 + 2 chr2 100 . T C . . . GT 0/1 + 3 chr2 101 . C G . . . GT 0/1 + """""" + if mode == 'remove': + def one_row(r): + r.CHROM = r.CHROM.replace('chr', '') + return r + elif mode == 'add': + def one_row(r): + if 'chr' not in r.CHROM: + r.CHROM = 'chr' + r.CHROM + return r + else: + raise ValueError(f'Incorrect mode: {mode}') + df = self.df.apply(one_row, axis=1) + return self.__class__(self.copy_meta(), df) + + def compare(self, other): + """""" + Compare to another VcfFrame and show the differences in genotype + calling. + + Parameters + ---------- + other : VcfFrame + VcfFrame to compare with. + + Returns + ------- + pandas.DataFrame + DataFrame comtaining genotype differences. + + Examples + -------- + + >>> from fuc import pyvcf + >>> data1 = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102, 103, 104], + ... 'ID': ['.', '.', '.', '.', '.'], + ... 'REF': ['G', 'CT', 'T', 'C', 'A'], + ... 'ALT': ['A', 'C', 'A', 'T', 'G,C'], + ... 'QUAL': ['.', '.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT', 'GT'], + ... 'A': ['0/1', '0/0', '0/0', '0/1', '0/0'], + ... 'B': ['1/1', '0/1', './.', '0/1', '0/0'], + ... 'C': ['0/1', '0/1', '1/1', './.', '1/2'], + ... } + >>> data2 = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chr1', 'chr1'], + ... 'POS': [100, 101, 102, 103, 104], + ... 'ID': ['.', '.', '.', '.', '.'], + ... 'REF': ['G', 'CT', 'T', 'C', 'A'], + ... 'ALT': ['A', 'C', 'A', 'T', 'G,C'], + ... 'QUAL': ['.', '.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.', '.'], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT', 'GT'], + ... 'A': ['./.', '0/0', '0/0', '0/1', '0/0'], + ... 'B': ['1/1', '0/1', './.', '1/1', '0/0'], + ... 'C': ['0/1', '0/1', '0/1', './.', '1/2'], + ... } + >>> vf1 = pyvcf.VcfFrame.from_dict([], data1) + >>> vf2 = pyvcf.VcfFrame.from_dict([], data2) + >>> vf1.compare(vf2) + Locus Sample Self Other + 0 chr1-100-G-A A 0/1 ./. + 1 chr1-102-T-A C 1/1 0/1 + 2 chr1-103-C-T B 0/1 1/1 + """""" + df1 = self.df.copy() + df2 = other.df.copy() + i1 = df1['CHROM'] + '-' + df1['POS'].astype(str) + '-' + df1['REF'] + '-' + df1['ALT'] + i2 = df2['CHROM'] + '-' + df2['POS'].astype(str) + '-' + df2['REF'] + '-' + df2['ALT'] + df1 = df1.set_index(i1) + df2 = df2.set_index(i2) + df1 = df1.iloc[:, 9:] + df2 = df2.iloc[:, 9:] + if df1.equals(df2): + return pd.DataFrame(columns=['Locus', 'Sample', 'Self', 'Other']) + df = df1.compare(df2, align_axis=0) + df = df.stack().to_frame().reset_index().pivot( + columns='level_1', index=['level_0', 'level_2'], values=0) + df = df.reset_index() + df.columns = ['Locus', 'Sample', 'Other', 'Self'] + df = df[['Locus', 'Sample', 'Self', 'Other']] + return df + + def diploidize(self): + """""" + Diploidize VcfFrame. + + Returns + ------- + VcfFrame + Diploidized VcfFrame. + + See Also + -------- + gt_diploidize + For given genotype, return its diploid form. + + Examples + -------- + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chrX', 'chrX'], + ... 'POS': [100, 101], + ... 'ID': ['.', '.'], + ... 'REF': ['G', 'T'], + ... 'ALT': ['A', 'C'], + ... 'QUAL': ['.', '.'], + ... 'FILTER': ['.', '.'], + ... 'INFO': ['.', '.'], + ... 'FORMAT': ['GT', 'GT'], + ... 'Male': ['0', '1'], + ... 'Female': ['0/0', '0/1'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Male Female + 0 chrX 100 . G A . . . GT 0 0/0 + 1 chrX 101 . T C . . . GT 1 0/1 + >>> vf.diploidize().df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Male Female + 0 chrX 100 . G A . . . GT 0/0 0/0 + 1 chrX 101 . T C . . . GT 0/1 0/1 + """""" + def one_row(r): + r[9:] = r[9:].apply(gt_diploidize) + return r + df = self.df.apply(one_row, axis=1) + return self.__class__(self.copy_meta(), df) + + def fetch(self, variant): + """""" + Fetch the VCF row that matches specified variant. + + Parameters + ---------- + variant : str + Target variant. + + Returns + ------- + pandas.Series + VCF row. + + Examples + -------- + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr2'], + ... 'POS': [100, 101], + ... 'ID': ['.', '.'], + ... 'REF': ['G', 'T'], + ... 'ALT': ['A', 'C'], + ... 'QUAL': ['.', '.'], + ... 'FILTER': ['.', '.'], + ... 'INFO': ['.', '.'], + ... 'FORMAT': ['GT', 'GT'], + ... 'A': ['0/1', '1/1'] + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.fetch('chr1-100-G-A') + CHROM chr1 + POS 100 + ID . + REF G + ALT A + QUAL . + FILTER . + INFO . + FORMAT GT + A 0/1 + Name: 0, dtype: object + """""" + def one_row(r): + return f'{r.CHROM}-{r.POS}-{r.REF}-{r.ALT}' == variant + i = self.df.apply(one_row, axis=1) + return self.df[i].squeeze() + + def pseudophase(self): + """""" + Pseudophase VcfFrame. + + Returns + ------- + VcfFrame + Pseudophased VcfFrame. + + Examples + -------- + + >>> from fuc import pyvcf + >>> data = { + ... 'CHROM': ['chr1', 'chr2'], + ... 'POS': [100, 101], + ... 'ID': ['.', '.'], + ... 'REF': ['G', 'T'], + ... 'ALT': ['A', 'C'], + ... 'QUAL': ['.', '.'], + ... 'FILTER': ['.', '.'], + ... 'INFO': ['.', '.'], + ... 'FORMAT': ['GT', 'GT'], + ... 'A': ['0/1', '1/1'] + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A + 0 chr1 100 . G A . . . GT 0/1 + 1 chr2 101 . T C . . . GT 1/1 + >>> vf.pseudophase().df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A + 0 chr1 100 . G A . . . GT 0|1 + 1 chr2 101 . T C . . . GT 1|1 + """""" + def one_row(r): + r[9:] = r[9:].apply(gt_pseudophase) + return r + df = self.df.apply(one_row, axis=1) + return self.__class__(self.copy_meta(), df) + + def get_af(self, sample, variant): + """""" + Get allele fraction for a pair of sample and variant. + + The method will return ``numpy.nan`` when: + + 1. variant is absent, or + 2. variant is present but there is no ``AF`` in the ``FORMAT`` column + + Parameters + ---------- + sample : str + Sample name. + variant : str + Variant name. + + Returns + ------- + float + Allele fraction. + + Examples + -------- + + >>> from fuc import pyvcf, common + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr1', 'chr1', 'chr1'], + ... 'POS': [100, 100, 101, 102, 103], + ... 'ID': ['.', '.', '.', '.', '.'], + ... 'REF': ['A', 'A', 'G', 'A', 'C'], + ... 'ALT': ['C', 'T', 'T', 'G', 'G,A'], + ... 'QUAL': ['.', '.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.', '.'], + ... 'INFO': ['.', '.', '.', '.', '.'], + ... 'FORMAT': ['GT:AD:AF', 'GT:AD:AF', 'GT:AD:AF', 'GT:AF', 'GT:AD:AF'], + ... 'A': ['0/1:12,15:0.444,0.556', '0/0:31,0:1.000,0.000', '0/0:32,1:0.970,0.030', '0/1:.', './.:.:.'], + ... 'B': ['0/0:29,0:1.000,0.000', '0/1:13,17:0.433,0.567', '0/1:14,15:0.483,0.517', './.:.', '1/2:0,11,17:0.000,0.393,0.607'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict([], data) + >>> vf.df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT A B + 0 chr1 100 . A C . . . GT:AD:AF 0/1:12,15:0.444,0.556 0/0:29,0:1.000,0.000 + 1 chr1 100 . A T . . . GT:AD:AF 0/0:31,0:1.000,0.000 0/1:13,17:0.433,0.567 + 2 chr1 101 . G T . . . GT:AD:AF 0/0:32,1:0.970,0.030 0/1:14,15:0.483,0.517 + 3 chr1 102 . A G . . . GT:AF 0/1:. ./.:. + 4 chr1 103 . C G,A . . . GT:AD:AF ./.:.:. 1/2:0,11,17:0.000,0.393,0.607 + >>> vf.get_af('A', 'chr1-100-A-C') + 0.556 + >>> vf.get_af('A', 'chr1-100-A-T') + 0.0 + >>> vf.get_af('B', 'chr1-100-A-T') + 0.567 + >>> vf.get_af('B', 'chr1-100-A-G') # does not exist + nan + >>> vf.get_af('B', 'chr1-102-A-G') # missing AF data + nan + >>> vf.get_af('B', 'chr1-103-C-A') # multiallelic locus + 0.607 + """""" + chrom, pos, ref, alt = common.parse_variant(variant) + + i = self.df.apply(lambda r: ((r.CHROM == chrom) & (r.POS == pos) & + (r.REF == ref) & (alt in r.ALT.split(','))), axis=1) + + if i.any(): + r = self.df[i] + else: + return np.nan + + try: + i = r.FORMAT.values[0].split(':').index('AF') + except ValueError: + return np.nan + + alts = r.ALT.values[0].split(',') + + j = r.ALT.values[0].split(',').index(alt) + + field = r[sample].values[0].split(':')[i] + + if field == '.': + af = np.nan + else: + af = float(field.split(',')[j+1]) + + return af +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/api/common.py",".py","41303","1361",""""""" +The common submodule is used by other fuc submodules such as pyvcf and +pybed. It also provides many day-to-day actions used in the field of +bioinformatics. +"""""" + +import pathlib +import re +import os +import sys +import warnings +import inspect +import copy +from argparse import RawTextHelpFormatter, SUPPRESS +from pathlib import Path +from difflib import SequenceMatcher +from urllib.request import urlretrieve + +from . import pyvcf + +import pysam +import pandas as pd +import numpy as np +import matplotlib.pyplot as plt +import matplotlib.patches as mpatches +import seaborn as sns + +FUC_PATH = pathlib.Path(__file__).parent.parent.parent.absolute() + +class Variant: + def __init__(self, chrom, pos, ref, alt): + self.chrom = chrom + self.pos = pos + self.ref = ref + self.alt = alt + + def __members(self): + return (self.chrom, self.pos, self.ref, self.alt) + + def __eq__(self, other): + if type(other) is type(self): + return self.__members() == other.__members() + else: + return False + + def __hash__(self): + return hash(self.__members()) + + def __repr__(self): + s = ', '.join([str(x) for x in self.__members()]) + return f'Variant({s})' + +class AnnFrame: + """""" + Class for storing sample annotation data. + + This class stores sample annotation data as :class:`pandas.DataFrame` + with sample names as index. + + Note that an AnnFrame can have a different set of samples than its + accompanying :class:`pymaf.MafFrame`, :class:`pyvcf.VcfFrame`, etc. + + Parameters + ---------- + df : pandas.DataFrame + DataFrame containing sample annotation data. The index must be + unique sample names. + + See Also + -------- + AnnFrame.from_dict + Construct AnnFrame from dict of array-like or dicts. + AnnFrame.from_file + Construct AnnFrame from a delimited text file. + + Examples + -------- + + >>> import pandas as pd + >>> from fuc import common + >>> data = { + ... 'SampleID': ['A', 'B', 'C', 'D'], + ... 'PatientID': ['P1', 'P1', 'P2', 'P2'], + ... 'Tissue': ['Normal', 'Tissue', 'Normal', 'Tumor'], + ... 'Age': [30, 30, 57, 57] + ... } + >>> df = pd.DataFrame(data) + >>> df = df.set_index('SampleID') + >>> af = common.AnnFrame(df) + >>> af.df + PatientID Tissue Age + SampleID + A P1 Normal 30 + B P1 Tissue 30 + C P2 Normal 57 + D P2 Tumor 57 + """""" + + def _check_df(self, df): + if type(df.index) == pd.RangeIndex: + raise ValueError(""Index cannot be 'pandas.RangeIndex'."") + if df.isin([np.inf, -np.inf]).any().any(): + raise ValueError('Found positive or negative infinity.') + if df.index.has_duplicates: + raise ValueError('Index has duplicates.') + return df + + def __init__(self, df): + self._df = self._check_df(df) + + @property + def df(self): + """"""pandas.DataFrame : DataFrame containing sample annotation data."""""" + return self._df + + @df.setter + def df(self, value): + self._df = self._check_df(value) + + @property + def samples(self): + """"""list : List of the sample names."""""" + return list(self.df.index.to_list()) + + @property + def shape(self): + """"""tuple : Dimensionality of AnnFrame (samples, annotations)."""""" + return self.df.shape + + @classmethod + def from_dict(cls, data, sample_col): + """""" + Construct AnnFrame from dict of array-like or dicts. + + The dictionary must contain a column that represents sample names. + + Parameters + ---------- + data : dict + Of the form {field : array-like} or {field : dict}. + sample_col : str or int + Column containing unique sample names, either given as string + name or column index. + + Returns + ------- + AnnFrame + AnnFrame object. + + See Also + -------- + AnnFrame + AnnFrame object creation using constructor. + AnnFrame.from_file + Construct AnnFrame from a delimited text file. + + Examples + -------- + + >>> from fuc import common + >>> data = { + ... 'SampleID': ['A', 'B', 'C', 'D'], + ... 'PatientID': ['P1', 'P1', 'P2', 'P2'], + ... 'Tissue': ['Normal', 'Tissue', 'Normal', 'Tumor'], + ... 'Age': [30, 30, 57, 57] + ... } + >>> af = common.AnnFrame.from_dict(data, sample_col='SampleID') # or sample_col=0 + >>> af.df + PatientID Tissue Age + SampleID + A P1 Normal 30 + B P1 Tissue 30 + C P2 Normal 57 + D P2 Tumor 57 + """""" + df = pd.DataFrame(data) + if isinstance(sample_col, int): + sample_col = list(data)[sample_col] + df = df.set_index(sample_col) + return cls(df) + + @classmethod + def from_file(cls, fn, sample_col, sep='\t'): + """""" + Construct AnnFrame from a delimited text file. + + The file must contain a column that represents sample names. + + Parameters + ---------- + fn : str + Text file (compressed or uncompressed). + sample_col : str or int + Column containing unique sample names, either given as string + name or column index. + sep : str, default: '\\\\t' + Delimiter to use. + + Returns + ------- + AnnFrame + AnnFrame object. + + See Also + -------- + AnnFrame + AnnFrame object creation using constructor. + AnnFrame.from_dict + Construct AnnFrame from dict of array-like or dicts. + + Examples + -------- + + >>> from fuc import common + >>> af = common.AnnFrame.from_file('sample-annot.tsv', sample_col='SampleID') + >>> af = common.AnnFrame.from_file('sample-annot.csv', sample_col=0, sep=',') + """""" + df = pd.read_table(fn, index_col=sample_col, sep=sep) + return cls(df) + + def plot_annot( + self, group_col, group_order=None, samples=None, colors='tab10', + sequential=False, xticklabels=True, ax=None, figsize=None + ): + """""" + Create a categorical heatmap for the selected column using unmatched + samples. + + See this :ref:`tutorial ` to + learn how to create customized oncoplots. + + Parameters + ---------- + group_col : str + AnnFrame column containing sample group information. If the + column has NaN values, they will be converted to 'N/A' string. + group_order : list, optional + List of sample group names (in that order too). You can use this + to subset samples belonging to specified groups only. You must + include all relevant groups when also using ``samples``. + samples : list, optional + Display only specified samples (in that order too). + colors : str or list, default: 'tab10' + Colormap name or list of colors. + sequential : bool, default: False + Whether the column is sequential data. + xticklabels : bool, default: True + If True, plot the sample names. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + list + Legend handles. + + Examples + -------- + Below is a simple example: + + .. plot:: + :context: close-figs + + >>> import matplotlib.pyplot as plt + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> annot_file = '~/fuc-data/tcga-laml/tcga_laml_annot.tsv' + >>> af = common.AnnFrame.from_file(annot_file, sample_col=0) + >>> ax, handles = af.plot_annot('FAB_classification', samples=af.samples[:10]) + >>> legend = ax.legend(handles=handles) + >>> ax.add_artist(legend) + >>> plt.tight_layout() + + We can display only selected groups: + + .. plot:: + :context: close-figs + + >>> ax, handles = af.plot_annot('FAB_classification', group_order=['M7', 'M6']) + >>> legend = ax.legend(handles=handles) + >>> ax.add_artist(legend) + >>> plt.tight_layout() + + We can also display sequenital data in the following way: + + .. plot:: + :context: close-figs + + >>> ax, handles = af.plot_annot('FAB_classification', + ... samples=af.samples[:10], + ... colors='viridis', + ... sequential=True) + >>> legend = ax.legend(handles=handles) + >>> ax.add_artist(legend) + >>> plt.tight_layout() + """""" + # Get the selected column. + s = self.df[group_col] + s = s.fillna('N/A') + + # Subset the samples, if necessary. + if samples is not None: + s = s.reindex(samples) + + # Establish mapping from groups to numbers. + if group_order is None: + group_order = sorted([x for x in s.unique() if x == x]) + else: + # Make sure all specified groups are valid. + for group in group_order: + groups = ', '.join([f""'{x}'"" for x in sorted(s.unique())]) + if group not in s.unique(): + raise ValueError(f""The group '{group}' does not exist. "" + f""The following groups are available: {groups}."") + + if len(group_order) < len(s.unique()): + if samples is None: + s = s[s.isin(group_order)] + else: + missing = ', '.join([f""'{x}'"" for x in s.unique() + if x not in group_order]) + raise ValueError(""The 'group_order' argumnet must "" + ""include all groups when used with the 'samples' "" + ""argument. Following groups are currently missing: "" + f""{missing}."") + + d = {k: v for v, k in enumerate(group_order)} + df = s.to_frame().applymap(lambda x: d[x]) + + # Determine the colors to use. + if isinstance(colors, str): + if sequential: + c = plt.get_cmap(colors).colors + l = list(np.linspace(0, len(c)-1, len(group_order))) + colors = [c[round(i)] for i in l] + else: + colors = list(plt.get_cmap(colors).colors[:len(group_order)]) + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + # Plot the heatmap. + sns.heatmap( + df.T, ax=ax, cmap=colors, xticklabels=xticklabels, cbar=False, + linewidths=0.5 + ) + ax.set_xlabel('') + ax.set_ylabel(group_col) + ax.set_yticks([]) + + # Get the legend handles. + handles = legend_handles(group_order, colors=colors) + + return ax, handles + + def plot_annot_matched( + self, patient_col, group_col, annot_col, patient_order=None, + group_order=None, annot_order=None, colors='tab10', sequential=False, + xticklabels=True, ax=None, figsize=None + ): + """""" + Create a categorical heatmap for the selected column using matched + samples. + + See this :ref:`tutorial ` to + learn how to create customized oncoplots. + + Parameters + ---------- + patient_col : str + AnnFrame column containing patient information. + group_col : str + AnnFrame column containing sample group information. + annot_col : str + Column to plot. + patient_order : list, optional + Plot only specified patients (in that order too). + group_order : list, optional + List of sample group names. + annot_order : list, optional + Plot only specified annotations (in that order too). + colors : str or list, default: 'tab10' + Colormap name or list of colors. + sequential : bool, default: False + Whether the column is sequential data. + xticklabels : bool, default: True + If True, plot the sample names. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + list + Legend handles. + """""" + + if annot_order is None: + annot_order = self.df[annot_col].unique() + + df = self.df.pivot(columns=group_col, index=patient_col, + values=annot_col).T + + if patient_order is not None: + df = df[patient_order] + + d = {k: v for v, k in enumerate(annot_order)} + df = df.applymap(lambda x: x if pd.isna(x) else d[x]) + + if group_order is not None: + df = df.loc[group_order] + + # Determine the colors to use. + if isinstance(colors, str): + if sequential: + c = plt.get_cmap(colors).colors + l = list(np.linspace(0, len(c)-1, len(group_order))) + colors = [c[round(i)] for i in l] + else: + colors = list(plt.get_cmap(colors).colors[:len(group_order)]) + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + # Plot the heatmap. + sns.heatmap( + df, cmap=colors, cbar=False, xticklabels=xticklabels, ax=ax + ) + ax.set_xlabel('') + ax.set_ylabel(annot_col) + ax.set_yticks([]) + + # Add vertical lines. + for i, sample in enumerate(df.columns, start=1): + ax.axvline(i, color='white') + + # Get the legend handles. + handles = legend_handles(annot_order, colors=colors) + + return ax, handles + + def sorted_samples(self, by, mf=None, keep_empty=False, nonsyn=False): + """""" + Return a sorted list of sample names. + + Parameters + ---------- + df : str or list + Column or list of columns to sort by. + """""" + df = self.df.copy() + + if nonsyn: + samples = mf.matrix_waterfall(keep_empty=keep_empty).columns + df = df.loc[samples] + + df = df.sort_values(by=by) + + return df.index.to_list() + + def subset(self, samples, exclude=False): + """""" + Subset AnnFrame for specified samples. + + Parameters + ---------- + samples : str or list + Sample name or list of names (the order matters). + exclude : bool, default: False + If True, exclude specified samples. + + Returns + ------- + AnnFrame + Subsetted AnnFrame. + + Examples + -------- + + >>> from fuc import common + >>> data = { + ... 'SampleID': ['A', 'B', 'C', 'D'], + ... 'PatientID': ['P1', 'P1', 'P2', 'P2'], + ... 'Tissue': ['Normal', 'Tumor', 'Normal', 'Tumor'], + ... 'Age': [30, 30, 57, 57] + ... } + >>> af = common.AnnFrame.from_dict(data, sample_col='SampleID') # or sample_col=0 + >>> af.df + PatientID Tissue Age + SampleID + A P1 Normal 30 + B P1 Tumor 30 + C P2 Normal 57 + D P2 Tumor 57 + + We can subset the AnnFrame for the normal samples A and C: + + >>> af.subset(['A', 'C']).df + PatientID Tissue Age + SampleID + A P1 Normal 30 + C P2 Normal 57 + + Alternatively, we can exclude those samples: + + >>> af.subset(['A', 'C'], exclude=True).df + PatientID Tissue Age + SampleID + B P1 Tumor 30 + D P2 Tumor 57 + """""" + if isinstance(samples, str): + samples = [samples] + if exclude: + samples = [x for x in self.samples if x not in samples] + return self.__class__(self.df.loc[samples]) + +def _script_name(): + """"""Return the current script's filename."""""" + fn = inspect.stack()[1].filename + return pathlib.Path(fn).stem.replace('_', '-') + +def _add_parser(subparsers, name, **kwargs): + """"""Return the pre-formatted parser."""""" + parser = subparsers.add_parser( + name, + add_help=False, + formatter_class=RawTextHelpFormatter, + **kwargs, + ) + parser._positionals.title = 'Positional arguments' + parser._optionals.title = 'Optional arguments' + parser.add_argument( + '-h', + '--help', + action='help', + default=SUPPRESS, + help='Show this help message and exit.', + ) + return parser + +def get_similarity(a, b): + """"""Return a value from 0 to 1 representing how similar two strings are."""""" + return SequenceMatcher(None, a, b).ratio() + +def is_similar(a, b, threshold=0.9): + """"""Return True if the similarity is equal to or greater than threshold."""""" + return get_similarity(a, b) >= threshold + +def get_most_similar(a, l): + """"""Return the most similar string in a list."""""" + s = [get_similarity(a, x) for x in l] + m = max(s) + i = [i for i, x in enumerate(s) if x == m][0] + return l[i] + +def sumstat(fp, fn, tp, tn): + """""" + Return various summary statistics from (FP, FN, TP, TN). + + This method will return the following statistics: + + +------------------------------------------------------------+-------------------------------------------------+ + | Terminology | Derivation | + +============================================================+=================================================+ + | sensitivity, recall, hit rate, or true positive rate (TPR) | :math:`TPR = TP / P = TP / (TP + FN) = 1 - FNR` | + +------------------------------------------------------------+-------------------------------------------------+ + | specificity, selectivity or true negative rate (TNR) | :math:`TNR = TN / N = TN / (TN + FP) = 1 - FPR` | + +------------------------------------------------------------+-------------------------------------------------+ + | precision or positive predictive value (PPV) | :math:`PPV = TP / (TP + FP) = 1 - FDR` | + +------------------------------------------------------------+-------------------------------------------------+ + | negative predictive value (NPV) | :math:`NPV = TN / (TN + FN) = 1 - FOR` | + +------------------------------------------------------------+-------------------------------------------------+ + | miss rate or false negative rate (FNR) | :math:`FNR = FN / P = FN / (FN + TP) = 1 - TPR` | + +------------------------------------------------------------+-------------------------------------------------+ + | fall-out or false positive rate (FPR) | :math:`FPR = FP / N = FP / (FP + TN) = 1 - TNR` | + +------------------------------------------------------------+-------------------------------------------------+ + | false discovery rate (FDR) | :math:`FDR = FP / (FP + TP) = 1 - PPV` | + +------------------------------------------------------------+-------------------------------------------------+ + | false omission rate (FOR) | :math:`FOR = FN / (FN + TN) = 1 - NPV` | + +------------------------------------------------------------+-------------------------------------------------+ + | accuracy (ACC) | :math:`ACC = (TP + TN)/(TP + TN + FP + FN)` | + +------------------------------------------------------------+-------------------------------------------------+ + + Parameters + ---------- + fp, fn, tp, tn : int + Input statistics. + + Returns + ------- + dict + Dictionary containing summary statistics. + + Examples + -------- + + This example is directly taken from the Wiki page `Sensitivity and specificity `__. + + >>> from fuc import common + >>> results = common.sumstat(180, 10, 20, 1820) + >>> for k, v in results.items(): + ... print(k, f'{v:.3f}') + ... + tpr 0.667 + tnr 0.910 + ppv 0.100 + npv 0.995 + fnr 0.333 + fpr 0.090 + fdr 0.900 + for 0.005 + acc 0.906 + """""" + data = { + 'tpr': tp / (tp + fn), # sensitivity, recall, hit rate + 'tnr': tn / (tn + fp), # specificity, selectivity + 'ppv': tp / (tp + fp), # precision + 'npv': tn / (tn + fn), + 'fnr': fn / (fn + tp), # miss rate + 'fpr': fp / (fp + tn), # fall-out rate + 'fdr': fp / (fp + tp), + 'for': fn / (fn + tn), + 'acc': (tp + tn) / (tp + tn + fp + fn), + } + return data + +def load_dataset(name, force=False): + """""" + Load an example dataset from the online repository (requires internet). + + Parameters + ---------- + name : str + Name of the dataset in https://github.com/sbslee/fuc-data. + force : bool, default: False + If True, overwrite the existing files. + """""" + home_dir = str(Path.home()) + '/fuc-data' + data_dir = f'{home_dir}/{name}' + if not os.path.exists(home_dir): + os.makedirs(home_dir) + if not os.path.exists(data_dir): + os.makedirs(data_dir) + datasets = { + 'tcga-laml': [ + 'tcga_cohort.txt.gz', + 'tcga_laml.maf.gz', + 'tcga_laml_annot.tsv', + 'tcga_laml.vcf', + 'tcga_laml_vep.vcf', + ], + 'brca': [ + 'brca.maf.gz', + 'brca.vcf', + ], + 'pyvcf': [ + 'plot_comparison.vcf', + 'normal-tumor.vcf', + 'normal-tumor-annot.tsv', + 'getrm-cyp2d6-vdr.vcf', + ], + 'cytoband': [ + 'cytoBandIdeo.txt.gz', + 'ucsc_genes.bed.gz', + ], + } + base_url = ('https://raw.githubusercontent.com/sbslee/fuc-data/main') + for f in datasets[name]: + file_url = f'{base_url}/{name}/{f}' + file_path = f'{data_dir}/{f}' + download = False + if force: + download = True + else: + if os.path.exists(file_path): + pass + else: + download = True + if download: + urlretrieve(file_url, file_path) + +def parse_region(region): + """""" + Parse specified genomic region. + + The method will return parsed region as a tuple with a shape of + ``(chrom, start, end)`` which has data types of ``(str, int, int)``. + + Note that only ``chrom`` is required when specifing a region. If + ``start`` and ``end`` are omitted, the method will return ``NaN`` in + their respective positions in the output tuple. + + Parameters + ---------- + region : str + Region ('chrom:start-end'). + + Returns + ------- + tuple + Parsed region. + + Examples + -------- + + >>> from fuc import common + >>> common.parse_region('chr1:100-150') + ('chr1', 100, 150) + >>> common.parse_region('chr1') + ('chr1', nan, nan) + >>> common.parse_region('chr1:100') + ('chr1', 100, nan) + >>> common.parse_region('chr1:100-') + ('chr1', 100, nan) + >>> common.parse_region('chr1:-100') + ('chr1', nan, 100) + """""" + chrom = region.split(':')[0] + + try: + start = region.split(':')[1].split('-')[0] + if not start: + start = np.nan + else: + start = int(start) + except IndexError: + start = np.nan + + try: + end = region.split(':')[1].split('-')[1] + if not end: + end = np.nan + else: + end = int(end) + except IndexError: + end = np.nan + + return (chrom, start, end) + +def parse_variant(variant): + """""" + Parse specified genomic variant. + + Generally speaking, the input string should consist of chromosome, + position, reference allele, and alternative allele separated by any one + or combination of the following delimiters: ``-``, ``:``, ``>`` (e.g. + '22-42127941-G-A'). The method will return parsed variant as a tuple with + a shape of ``(chrom, pos, ref, alt)`` which has data types of ``(str, + int, str, str)``. + + Note that it's possible to omit reference allele and alternative allele + from the input string to indicate position-only data (e.g. + '22-42127941'). In this case, the method will return empty string for + the alleles -- i.e. ``(str, int, '', '')`` if both are omitted and + ``(str, int, str, '')`` if only alternative allele is omitted. + + Parameters + ---------- + variant : str + Genomic variant. + + Returns + ------- + tuple + Parsed variant. + + Examples + -------- + + >>> from fuc import common + >>> common.parse_variant('22-42127941-G-A') + ('22', 42127941, 'G', 'A') + >>> common.parse_variant('22:42127941-G>A') + ('22', 42127941, 'G', 'A') + >>> common.parse_variant('22-42127941') + ('22', 42127941, '', '') + >>> common.parse_variant('22-42127941-G') + ('22', 42127941, 'G', '') + """""" + fields = re.split('-|:|>', variant) + chrom = fields[0] + pos = int(fields[1]) + + try: + ref = fields[2] + except IndexError: + ref = '' + + try: + alt = fields[3] + except IndexError: + alt = '' + + return (chrom, pos, ref, alt) + +def extract_sequence(fasta, region): + """""" + Extract the DNA sequence corresponding to a selected region from a FASTA + file. + + The method also allows users to retrieve the reference allele of a + variant in a genomic coordinate format, instead of providing a genomic + region. + + Parameters + ---------- + fasta : str + FASTA file. + region : str + Region ('chrom:start-end'). + + Returns + ------- + str + DNA sequence. Empty string if there is no matching sequence. + + Examples + -------- + + >>> from fuc import common + >>> fasta = 'resources_broad_hg38_v0_Homo_sapiens_assembly38.fasta' + >>> common.extract_sequence(fasta, 'chr1:15000-15005') + 'GATCCG' + >>> # rs1423852 is chr16-80874864-C-T + >>> common.extract_sequence(fasta, 'chr16:80874864-80874864') + 'C' + """""" + try: + sequence = ''.join(pysam.faidx(fasta, region).split('\n')[1:]) + except pysam.SamtoolsError as e: + warnings.warn(str(e)) + sequence = '' + return sequence + +def convert_file2list(fn): + """""" + Convert a text file to a list of filenames. + + Parameters + ---------- + fn : str + File containing one filename per line. + + Returns + ------- + list + List of filenames. + + Examples + -------- + + >>> from fuc import common + >>> common.convert_file2list('bam.list') + ['1.bam', '2.bam', '3.bam'] + """""" + l = [] + with open(fn) as f: + for line in f: + l.append(line.strip()) + return l + +def convert_num2cat(s, n=5, decimals=0): + """""" + Convert numeric values to categorical variables. + + Parameters + ---------- + pandas.Series + Series object containing numeric values. + n : int, default: 5 + Number of variables to output. + + Returns + ------- + pandas.Series + Series object containing categorical variables. + + Examples + -------- + + >>> import matplotlib.pyplot as plt + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> annot_file = '~/fuc-data/tcga-laml/tcga_laml_annot.tsv' + >>> af = common.AnnFrame.from_file(annot_file, sample_col=0) + >>> s = af.df.days_to_last_followup + >>> s[:10] + Tumor_Sample_Barcode + TCGA-AB-2802 365.0 + TCGA-AB-2803 792.0 + TCGA-AB-2804 2557.0 + TCGA-AB-2805 577.0 + TCGA-AB-2806 945.0 + TCGA-AB-2807 181.0 + TCGA-AB-2808 2861.0 + TCGA-AB-2809 62.0 + TCGA-AB-2810 31.0 + TCGA-AB-2811 243.0 + Name: days_to_last_followup, dtype: float64 + >>> s = common.convert_num2cat(s) + >>> s.unique() + array([ 572.2, 1144.4, 2861. , 2288.8, 1716.6, nan]) + >>> s[:10] + Tumor_Sample_Barcode + TCGA-AB-2802 572.2 + TCGA-AB-2803 1144.4 + TCGA-AB-2804 2861.0 + TCGA-AB-2805 1144.4 + TCGA-AB-2806 1144.4 + TCGA-AB-2807 572.2 + TCGA-AB-2808 2861.0 + TCGA-AB-2809 572.2 + TCGA-AB-2810 572.2 + TCGA-AB-2811 572.2 + Name: days_to_last_followup, dtype: float64 + """""" + boundaries = list(np.linspace(s.min(), s.max(), n+1, endpoint=True)) + intervals = list(zip(boundaries[:-1], boundaries[1:])) + + def f(x): + if pd.isna(x): + return x + for i, interval in enumerate(intervals): + a, b = interval + if a <= x <= b: + return b + + return s.apply(f).round(decimals=decimals) + +def legend_handles(labels, colors='tab10'): + """""" + Create custom legend handles. + + Parameters + ---------- + labels : list + List of labels. + colors : str or list, default: 'tab10' + Colormap name or list of colors. + + Returns + ------- + list + List of legend handles. + + Examples + -------- + + .. plot:: + + >>> import matplotlib.pyplot as plt + >>> from fuc import common + >>> fig, ax = plt.subplots() + >>> handles1 = common.legend_handles(['A', 'B'], colors='tab10') + >>> handles2 = common.legend_handles(['C', 'D'], colors=['yellow', 'green']) + >>> legend1 = ax.legend(handles=handles1, loc='center left') + >>> legend2 = ax.legend(handles=handles2) + >>> ax.add_artist(legend1) + >>> ax.add_artist(legend2) + >>> plt.tight_layout() + """""" + if isinstance(colors, str): + colors = plt.get_cmap(colors).colors + elif isinstance(colors, list): + pass + else: + raise TypeError(f'Incorrect type of colors: {type(colors)}') + + handles = [] + + for i, label in enumerate(labels): + handles.append(mpatches.Patch(color=colors[i], label=label)) + + return handles + +def plot_exons( + starts, ends, name=None, offset=1, fontsize=None, color='black', y=0, + height=1, ax=None, figsize=None +): + """""" + Create a gene model where exons are drawn as boxes. + + Parameters + ---------- + starts : list + List of exon start positions. + ends : list + List of exon end positions. + name : str, optional + Gene name. Use ``name='$text$'`` to italicize the text. + offset : float, default: 1 + How far gene name should be plotted from the gene model. + color : str, default: 'black' + Box color. + y : float, default: 0 + Y position of the backbone. + height : float, default: 1 + Height of the gene model. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + Examples + -------- + + .. plot:: + + >>> import matplotlib.pyplot as plt + >>> from fuc import common + >>> cyp2d6_starts = [42522500, 42522852, 42523448, 42523843, 42524175, 42524785, 42525034, 42525739, 42526613] + >>> cyp2d6_ends = [42522754, 42522994, 42523636, 42523985, 42524352, 42524946, 42525187, 42525911, 42526883] + >>> ax = common.plot_exons(cyp2d6_starts, cyp2d6_ends, name='CYP2D6', fontsize=20) + >>> ax.set_ylim([-2, 2]) + >>> plt.tight_layout() + """""" + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + ax.hlines( + y=y, xmin=starts[0], xmax=ends[-1], color=color + ) + + for i in range(len(starts)): + ax.add_patch(mpatches.Rectangle( + xy=(starts[i], y - height/2), + width=ends[i] - starts[i], + height=height, + color=""black"" + )) + + if name is not None: + ax.text( + x=(starts[0]+ends[-1]) / 2, + y=y-offset, + s=name, + horizontalalignment='center', + fontsize=fontsize, + ) + + return ax + +def conda_env(): + """"""str : Name of the current conda environment."""""" + return sys.executable.split('/')[-3] + +def color_print(s, color='green', bold=False): + """"""Print colored text."""""" + colors = { + 'red' : '31', + 'green': '32', + } + + c = colors[color] + + if bold: + b = 1 + else: + b = 0 + + print(f'\x1b[{b};{c};{c}m' + s + '\x1b[0m') + +def rename(original, names, indicies=None): + """""" + Rename sample names flexibly. + + Parameters + ---------- + original : list + List of original names. + names : dict or list + Dict of old names to new names or list of new names. + indicies : list or tuple, optional + List of 0-based sample indicies. Alternatively, a tuple + (int, int) can be used to specify an index range. + + Returns + ------- + list + List of updated names. + + Examples + -------- + + >>> from fuc import common + >>> original = ['A', 'B', 'C', 'D'] + >>> common.rename(original, ['1', '2', '3', '4']) + ['1', '2', '3', '4'] + >>> common.rename(original, {'B': '2', 'C': '3'}) + ['A', '2', '3', 'D'] + >>> common.rename(original, ['2', '4'], indicies=[1, 3]) + ['A', '2', 'C', '4'] + >>> common.rename(original, ['2', '3'], indicies=(1, 3)) + ['A', '2', '3', 'D'] + """""" + samples = copy.deepcopy(original) + + if not isinstance(names, list) and not isinstance(names, dict): + raise TypeError(""Argument 'names' must be dict or list."") + + if len(names) > len(samples): + raise ValueError(""There are too many names."") + + if isinstance(names, list) and indicies is not None: + if isinstance(indicies, tuple): + if len(indicies) != 2: + raise ValueError(""Index range must be two integers."") + l = len(range(indicies[0], indicies[1])) + elif isinstance(indicies, list): + l = len(indicies) + else: + raise TypeError(""Argument 'indicies' must be list or tuple."") + + if len(names) != l: + raise ValueError(""Names and indicies have different lengths."") + + if isinstance(names, list): + if len(names) == len(samples): + names = dict(zip(samples, names)) + else: + if indicies is None: + message = (""There are too few names. If this was "" + ""intended, use the 'indicies' argument."") + raise ValueError(message) + elif isinstance(indicies, tuple): + names = dict(zip(samples[indicies[0]:indicies[1]], names)) + else: + names = dict(zip([samples[i] for i in indicies], names)) + + for old, new in names.items(): + i = samples.index(old) + samples[i] = new + + if len(samples) > len(set(samples)): + raise ValueError('There are more than one duplicate names.') + + return samples + +def sort_variants(variants): + """""" + Return sorted list of variants. + + Parameters + ---------- + variants : list + List of variants. + + Returns + ------- + list + Sorted list. + + Examples + -------- + + >>> from fuc import common + >>> variants = ['5-200-G-T', '5:100:T:C', '1:100:A>C', '10-100-G-C'] + >>> sorted(variants) # Lexicographic sorting (not what we want) + ['10-100-G-C', '1:100:A>C', '5-200-G-T', '5:100:T:C'] + >>> common.sort_variants(variants) + ['1:100:A>C', '5:100:T:C', '5-200-G-T', '10-100-G-C'] + """""" + def func(x): + chrom, pos, ref, alt = parse_variant(x) + if chrom in pyvcf.CONTIGS: + chrom = pyvcf.CONTIGS.index(chrom) + return (chrom, pos, ref, alt) + return sorted(variants, key=func) + +def sort_regions(regions): + """""" + Return sorted list of regions. + + Parameters + ---------- + regions : list + List of regions. + + Returns + ------- + list + Sorted list. + + Examples + -------- + + >>> from fuc import common + >>> regions = ['chr22:1000-1500', 'chr16:100-200', 'chr22:200-300', 'chr16_KI270854v1_alt', 'chr3_GL000221v1_random', 'HLA-A*02:10'] + >>> sorted(regions) # Lexicographic sorting (not what we want) + ['HLA-A*02:10', 'chr16:100-200', 'chr16_KI270854v1_alt', 'chr22:1000-1500', 'chr22:200-300', 'chr3_GL000221v1_random'] + >>> common.sort_regions(regions) + ['chr16:100-200', 'chr22:200-300', 'chr22:1000-1500', 'chr16_KI270854v1_alt', 'chr3_GL000221v1_random', 'HLA-A*02:10'] + """""" + def func(x): + chrom, start, end = parse_region(x) + if chrom in pyvcf.CONTIGS: + chrom = pyvcf.CONTIGS.index(chrom) + alt = '' + else: + chrom = len(pyvcf.CONTIGS) + alt = chrom + return (chrom, alt, start, end) + return sorted(regions, key=func) + +def update_chr_prefix(regions, mode='remove'): + """""" + Add or remove the (annoying) 'chr' string from specified regions. + + The method will automatically detect regions that don't need to be + updated and will return them unchanged. + + Parameters + ---------- + regions : str or list + One or more regions to be updated. + mode : {'add', 'remove'}, default: 'remove' + Whether to add or remove the 'chr' string. + + Returns + ------- + VcfFrame + str or list. + + Example + ------- + + >>> from fuc import common + >>> common.update_chr_prefix(['chr1:100-200', '2:300-400'], mode='remove') + ['1:100-200', '2:300-400'] + >>> common.update_chr_prefix(['chr1:100-200', '2:300-400'], mode='add') + ['chr1:100-200', 'chr2:300-400'] + >>> common.update_chr_prefix('chr1:100-200', mode='remove') + '1:100-200' + >>> common.update_chr_prefix('chr1:100-200', mode='add') + 'chr1:100-200' + >>> common.update_chr_prefix('2:300-400', mode='add') + 'chr2:300-400' + >>> common.update_chr_prefix('2:300-400', mode='remove') + '2:300-400' + """""" + def remove(x): + return x.replace('chr', '') + + def add(x): + if 'chr' not in x: + x = 'chr' + x + return x + + modes = {'remove': remove, 'add': add} + + if isinstance(regions, str): + return modes[mode](regions) + + return [modes[mode](x) for x in regions] + +def parse_list_or_file(obj, extensions=['txt', 'tsv', 'csv', 'list']): + """""" + Parse the input variable and then return a list of items. + + This method is useful when parsing a command line argument that accepts + either a list of items or a text file containing one item per line. + + Parameters + ---------- + obj : str or list + Object to be tested. Must be non-empty. + extensions : list, default: ['txt', 'tsv', 'csv', 'list'] + Recognized file extensions. + + Returns + ------- + list + List of items. + + Examples + -------- + + >>> from fuc import common + >>> common.parse_list_or_file(['A', 'B', 'C']) + ['A', 'B', 'C'] + >>> common.parse_list_or_file('A') + ['A'] + >>> common.parse_list_or_file('example.txt') + ['A', 'B', 'C'] + >>> common.parse_list_or_file(['example.txt']) + ['A', 'B', 'C'] + """""" + if not isinstance(obj, str) and not isinstance(obj, list): + raise TypeError( + f'Input must be str or list, not {type(obj).__name__}') + + if not obj: + raise ValueError('Input is empty') + + if isinstance(obj, str): + obj = [obj] + + if len(obj) > 1: + return obj + + for extension in extensions: + if obj[0].endswith(f'.{extension}'): + return convert_file2list(obj[0]) + + return obj + +def reverse_complement(seq, complement=True, reverse=False): + """""" + Given a DNA sequence, generate its reverse, complement, or + reverse-complement. + + Parameters + ---------- + seq : str + DNA sequence. + complement : bool, default: True + Whether to return the complment. + reverse : bool, default: False + Whether to return the reverse. + + Returns + ------- + str + Updated sequence. + + Examples + -------- + + >>> from fuc import common + >>> common.reverse_complement('AGC') + 'TCG' + >>> common.reverse_complement('AGC', reverse=True) + 'GCT' + >>> common.reverse_complement('AGC', reverse=True, complement=False) + 'GCT' + >>> common.reverse_complement('agC', reverse=True) + 'Gct' + """""" + new_seq = seq[:] + complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', + 'a': 't', 'c': 'g', 'g': 'c', 't': 'a'} + if complement: + new_seq = ''.join([complement[x] for x in new_seq]) + if reverse: + new_seq = new_seq[::-1] + return new_seq +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/api/pygff.py",".py","7541","173",""""""" +The pygff submodule is designed for working with GFF/GTF files. It implements +``pygff.GffFrame`` which stores GFF/GTF data as ``pandas.DataFrame`` to allow +fast computation and easy manipulation. The submodule strictly adheres to the +standard `GFF specification +`_. + +A GFF/GTF file contains nine columns as follows: + ++-----+------------+--------------------------+-----------------------------------------------------------------------------------------------------------------------+ +| No. | Name | Description | Examples | ++=====+============+==========================+=======================================================================================================================+ +| 1 | Seqid | Landmark ID | 'NC_000001.10', 'NC_012920.1' | ++-----+------------+--------------------------+-----------------------------------------------------------------------------------------------------------------------+ +| 2 | Source | Feature source | 'RefSeq', 'BestRefSeq', 'Genescan', 'Genebank' | ++-----+------------+--------------------------+-----------------------------------------------------------------------------------------------------------------------+ +| 3 | Type | Feature type | 'transcript', 'exon', 'gene' | ++-----+------------+--------------------------+-----------------------------------------------------------------------------------------------------------------------+ +| 4 | Start | Start coordinate | 11874, 14409 | ++-----+------------+--------------------------+-----------------------------------------------------------------------------------------------------------------------+ +| 5 | End | End coordinate | 11874, 14409 | ++-----+------------+--------------------------+-----------------------------------------------------------------------------------------------------------------------+ +| 6 | Score | Feature score | '.', '1730.55', '1070' | ++-----+------------+--------------------------+-----------------------------------------------------------------------------------------------------------------------+ +| 7 | Strand | Feature strand | '.', '-', '+', '?' | ++-----+------------+--------------------------+-----------------------------------------------------------------------------------------------------------------------+ +| 8 | Phase | CDS phase | '.', '0', '1', '2' | ++-----+------------+--------------------------+-----------------------------------------------------------------------------------------------------------------------+ +| 9 | Attributes | ';'-separated attributes | 'ID=NC_000001.10:1..249250621;Dbxref=taxon:9606;Name=1;chromosome=1;gbkey=Src;genome=chromosome;mol_type=genomic DNA' | ++-----+------------+--------------------------+-----------------------------------------------------------------------------------------------------------------------+ +"""""" + +import gzip + +import pandas as pd + +class GffFrame: + """""" + Class for storing GFF/GTF data. + + Parameters + ---------- + meta : list + List of metadata lines. + df : pandas.DataFrame + DataFrame containing GFF/GTF data. + fasta : str + FASTA sequence lines. + """""" + def __init__(self, meta, df, fasta): + self._meta = meta + self._df = df.reset_index(drop=True) + self._fasta = fasta + + @property + def meta(self): + """"""list : List of metadata lines."""""" + return self._meta + + @meta.setter + def meta(self, value): + self._meta = value + + @property + def df(self): + """"""pandas.DataFrame : DataFrame containing GFF/GTF data."""""" + return self._df + + @df.setter + def df(self, value): + self._df = value.reset_index(drop=True) + + @property + def fasta(self): + """"""dict : FASTA sequence lines."""""" + return self._fasta + + @fasta.setter + def fasta(self, value): + self._fasta = value + + @classmethod + def from_file(cls, fn): + """""" + Construct GffFrame from a GFF/GTF file. + + Parameters + ---------- + fn : str + GFF/GTF file (compressed or uncompressed). + + Returns + ------- + GffFrame + GffFrame object. + """""" + if fn.startswith('~'): + fn = os.path.expanduser(fn) + + if fn.endswith('.gz'): + f = gzip.open(fn, 'rt') + else: + f = open(fn) + + meta = [] + data = [] + fasta = {} + + fasta_mode = False + current_fasta = None + + for line in f: + if '##FASTA' in line: + fasta_mode = True + elif fasta_mode and line.startswith('>'): + name = line.strip().replace('>', '') + fasta[name] = [] + current_fasta = name + elif fasta_mode: + fasta[current_fasta].append(line.strip()) + elif line.startswith('#'): + meta.append(line.strip()) + else: + fields = line.strip().split('\t') + data.append(fields) + + f.close() + + columns = [ + 'Seqid', 'Source', 'Type', 'Start', 'End', + 'Score', 'Strand', 'Phase', 'Attributes' + ] + + df = pd.DataFrame(data, columns=columns) + df.Start = df.Start.astype(int) + df.End = df.End.astype(int) + + return cls(meta, df, fasta) + + def protein_length(self, gene, name=None): + """""" + Return the protein length of a gene. + + Parameters + ---------- + gene : str + Name of the gene. + name : str, optional + Protein sequence ID (e.g. 'NP_005219.2'). Required when the gene + has multiple protein sequences available. + + Returns + ------- + int + Protein length. + """""" + df = self.df[self.df.Type == 'CDS'].query( + f""Attributes.str.contains('{gene}')"") + def one_row(r): + l = r.Attributes.split(';') + l = [x for x in l if x.startswith('Name=')] + name = l[0].replace('Name=', '') + return name + df['Protein_ID'] = df.apply(one_row, axis=1) + ids = df.Protein_ID.unique() + if name is None and len(ids) != 1: + raise ValueError(f'Multiple protein sequences available: {ids}') + elif name is None and len(ids) == 1: + name = ids[0] + df = df[df.Protein_ID == name] + length = (df.End - df.Start).sum() + df.shape[0] - 3 + return int(length / 3) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/api/pyfq.py",".py","1916","74",""""""" +The pyfq submodule is designed for working with FASTQ files. It implements +``pyfq.FqFrame`` which stores FASTQ data as ``pandas.DataFrame`` to allow +fast computation and easy manipulation. +"""""" + +import gzip +import pandas as pd + +class FqFrame: + """"""Class for storing FASTQ data."""""" + def __init__(self, df): + self.df = df + + @property + def shape(self): + """"""int : Number of sequence reads in the FqFrame."""""" + return self.df.shape + + def to_file(self, file_path): + """"""Write the FqFrame to a FASTQ file."""""" + with open(file_path, 'w') as f: + for line in self.df.stack().to_list(): + f.write(line + '\n') + + def readlen(self): + """"""Return a dictionary of read lengths and their counts."""""" + return self.df.apply(lambda r: len(r.SEQ), axis=1 + ).value_counts().to_dict() + + @classmethod + def from_file(cls, fn): + """""" + Construct FqFrame from a FASTQ file. + + Parameters + ---------- + fn : str + FASTQ file path (compressed or uncompressed). + + Returns + ------- + FqFrame + FqFrame. + + See Also + -------- + FqFrame + FqFrame object creation using constructor. + """""" + if fn.endswith('.gz'): + f = gzip.open(fn, 'rt') + else: + f = open(fn) + data = {'ID': [], 'SEQ': [], 'EXT': [], 'QUAL': []} + n = 0 + for line in f: + x = line.strip() + if n == 0: + data['ID'].append(x) + n += 1 + elif n == 1: + data['SEQ'].append(x) + n += 1 + elif n == 2: + data['EXT'].append(x) + n += 1 + else: + data['QUAL'].append(x) + n = 0 + df = pd.DataFrame.from_dict(data) + f.close() + return cls(df) +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/api/__init__.py",".py","138","7","from pathlib import Path + +__all__ = [f.stem for f in list(Path(__file__).parent.glob('*.py')) + if '__' not in f.stem] + +del Path +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/api/pychip.py",".py","9101","287",""""""" +The pychip submodule is designed for working with annotation or manifest +files from the Axiom (Thermo Fisher Scientific) and Infinium (Illumina) +array platforms. +"""""" + +import re +import pandas as pd + +from . import common + +class AxiomFrame: + """""" + Class for storing Axiom annotation data. + + Parameters + ---------- + meta : list + List of metadata lines. + df : pandas.DataFrame + DataFrame containing annotation data. + """""" + def __init__(self, meta, df): + self._meta = meta + self._df = df.reset_index(drop=True) + + @property + def meta(self): + """"""list : List of metadata lines."""""" + return self._meta + + @meta.setter + def meta(self, value): + self._meta = value + + @property + def df(self): + """"""pandas.DataFrame : DataFrame containing annotation data."""""" + return self._df + + @df.setter + def df(self, value): + self._df = value.reset_index(drop=True) + + @classmethod + def from_file(cls, fn): + """""" + Construct AxiomFrame from a CSV file. + + Parameters + ---------- + fn : str + CSV file (compressed or uncompressed). + + Returns + ------- + AxiomFrame + AxiomFrame object. + """""" + if fn.startswith('~'): + fn = os.path.expanduser(fn) + + if fn.endswith('.gz'): + f = gzip.open(fn, 'rt') + else: + f = open(fn) + + meta = [] + n = 0 + for line in f: + if line.startswith('#'): + meta.append(line) + n += 1 + f.close() + + df = pd.read_csv(fn, skiprows=n) + + return cls(meta, df) + + def to_vep(self): + """""" + Convert AxiomFrame to the Ensembl VEP format. + + Returns + ------- + pandas.DataFrame + Variants in Ensembl VEP format. + """""" + df = self.df[self.df.Chromosome != '---'] + df['Physical Position'] = df['Physical Position'].astype(int) + df['Position End'] = df['Position End'].astype(int) + def one_row(r): + result = [] + nucleotides = ['A', 'C', 'G', 'T'] + chrom = r['Chromosome'] + ref = r['Ref Allele'] + strand = r['Strand'] + start = r['Physical Position'] + end = r['Position End'] + for alt in r['Alt Allele'].split(' // '): + if ref in nucleotides and alt in nucleotides: # SNV + pass + elif alt == '-': # DEL I + pass + elif len(alt) == len(ref): # MNV + pass + elif len(alt) < len(ref) and ref.startswith(alt): # DEL II + start += len(alt) + ref = ref[len(alt):] + alt = '-' + elif ref == '-': # INS I + start += 1 + end = start - 1 + elif len(alt) > len(ref) and alt.startswith(ref): # INS II + diff = len(alt) - len(ref) + start += diff + end = start - 1 + ref = '-' + alt = alt[diff:] + else: + pass + line = [chrom, start, end, f'{ref}/{alt}', strand] + result.append('|'.join([str(x) for x in line])) + return ','.join(result) + s = df.apply(one_row, axis=1) + s = ','.join(s) + data = [x.split('|') for x in s.split(',')] + df = pd.DataFrame(data).drop_duplicates() + df.iloc[:, 1] = df.iloc[:, 1].astype(int) + df.iloc[:, 2] = df.iloc[:, 2].astype(int) + df = df.sort_values(by=[0, 1]) + return df + +class InfiniumFrame: + """""" + Class for storing Infinium manifest data. + + Parameters + ---------- + df : pandas.DataFrame + DataFrame containing manifest data. + """""" + def __init__(self, df): + self._df = df.reset_index(drop=True) + + @property + def df(self): + """"""pandas.DataFrame : DataFrame containing manifest data."""""" + return self._df + + @df.setter + def df(self, value): + self._df = value.reset_index(drop=True) + + @classmethod + def from_file(cls, fn): + """""" + Construct InfiniumFrame from a CSV file. + + Parameters + ---------- + fn : str + CSV file (compressed or uncompressed). + + Returns + ------- + InfiniumFrame + InfiniumFrame object. + """""" + if fn.startswith('~'): + fn = os.path.expanduser(fn) + + if fn.endswith('.gz'): + f = gzip.open(fn, 'rt') + else: + f = open(fn) + + lines = f.readlines() + f.close() + + for i, line in enumerate(lines): + if line.startswith('[Assay]'): + start = i + headers = lines[i+1].strip().split(',') + elif line.startswith('[Controls]'): + end = i + + lines = lines[start+2:end] + lines = [x.strip().split(',') for x in lines] + + df = pd.DataFrame(lines, columns=headers) + + return cls(df) + + def to_vep(self, fasta): + """""" + Convert InfiniumFrame to the Ensembl VEP format. + + Returns + ------- + pandas.DataFrame + Variants in Ensembl VEP format. + + Parameters + ---------- + region : str + Region ('chrom:start-end'). + """""" + nucleotides = ['A', 'C', 'G', 'T'] + n = 20 + k = 100 + df = self.df[(self.df.Chr != 'XY') & (self.df.Chr != '0')] + df.MapInfo = df.MapInfo.astype(int) + df = df.head(5000) + + def compare_seq(seq1, seq2): + if len(seq1) != len(seq2): + return False + for i in range(len(seq1)): + if seq1[i] != seq2[i]: + if seq1[i] == 'N' or seq2[i] == 'N': + continue + else: + return False + return True + + def one_row(r): + if r.Chr == 'MT': + chrom = 'chrM' + else: + chrom = f'chr{r.Chr}' + pos = r.MapInfo + matches = re.findall(r'\[([^\]]+)\]', r.SourceSeq) + if not matches: + raise ValueError(f'Something went wrong: {r}') + a1, a2 = matches[0].split('/') + left_seq = r.SourceSeq.split('[')[0][-n:].upper() + right_seq = r.SourceSeq.split(']')[1][:n].upper() + locus = f'{chrom}:{pos}-{pos}' + if a1 in nucleotides and a2 in nucleotides: # SNV + ref = common.extract_sequence(fasta, locus) + if ref == a1: + pass + elif ref == a2: + a1, a2 = a2, a1 + elif ref == common.reverse_complement(a1): + a1, a2 = ref, common.reverse_complement(a2) + elif ref == common.reverse_complement(a2): + a1, a2 = ref, common.reverse_complement(a1) + else: + raise ValueError(f'Reference allele not found: {[locus, a1, a2, ref]}') + elif a1 == '-' or a2 == '-': + affected = a1 if a2 == '-' else a2 + c = len(affected) + ref_seq = common.extract_sequence(fasta, f'{chrom}:{pos-k}-{pos+k}') + left_query = ref_seq[:k][-n:] + right_query = ref_seq[k+c:][:n] + if compare_seq(left_seq, left_query) and compare_seq(right_seq, right_query): + print(locus, left_seq, 'DEL I') + else: + left_query = ref_seq[:k+c+1][-n:] + right_query = ref_seq[k+c+1:][:n] + if compare_seq(left_seq, left_query) and compare_seq(right_seq, right_query): + print(locus, left_seq, 'INS') + else: + left_query = ref_seq[:k][-n:] + right_query = ref_seq[k+c+1:][:n] + if left_query in r.SourceSeq.split('[')[0]: + repeats = r.SourceSeq.split('[')[0].split(left_query)[1] + left_query += repeats + left_query = left_query[len(repeats):] + right_query = ref_seq[k+c+len(repeats):][:n] + if compare_seq(left_seq, left_query) and compare_seq(right_seq, right_query): + print(locus, left_seq, 'DEL II') + else: + print(locus, left_seq, left_query, left_seq == left_query) + print(locus, right_seq, right_query, right_seq == right_query) + print() + else: + raise ValueError(f'Unsupported format: {locus}') + data = pd.Series([r.Chr, r.MapInfo, r.MapInfo, f'{a1}/{a2}', '+']) + return data + df = df.apply(one_row, axis=1) + df = df.sort_values(by=[0, 1]) + df = df.drop_duplicates() + return df +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/api/pybed.py",".py","15488","508",""""""" +The pybed submodule is designed for working with BED files. It +implements ``pybed.BedFrame`` which stores BED data as ``pandas.DataFrame`` +via the `pyranges `_ package to +allow fast computation and easy manipulation. The submodule strictly adheres +to the standard `BED specification +`_. + +BED lines can have the following fields (the first three are required): + ++-----+-------------+-----------------------------------+--------------+ +| No. | Name | Description | Examples | ++=====+=============+===================================+==============+ +| 1 | Chromosome | Chromosome | 'chr2', '2' | ++-----+-------------+-----------------------------------+--------------+ +| 2 | Start | Start position | 10041, 23042 | ++-----+-------------+-----------------------------------+--------------+ +| 3 | End | End position | 10041, 23042 | ++-----+-------------+-----------------------------------+--------------+ +| 4 | Name | Feature name | 'TP53' | ++-----+-------------+-----------------------------------+--------------+ +| 5 | Score | Score for color density (0, 1000) | 342, 544 | ++-----+-------------+-----------------------------------+--------------+ +| 6 | Strand | '+' or '-' ('.' for no strand) | '+', '-' | ++-----+-------------+-----------------------------------+--------------+ +| 7 | ThickStart | Start position for thick drawing | 10041, 23042 | ++-----+-------------+-----------------------------------+--------------+ +| 8 | ThickEnd | End position for thick drawing | 10041, 23042 | ++-----+-------------+-----------------------------------+--------------+ +| 9 | ItemRGB | RGB value | '255,0,0' | ++-----+-------------+-----------------------------------+--------------+ +| 10 | BlockCount | Number of blocks (e.g. exons) | 12, 8 | ++-----+-------------+-----------------------------------+--------------+ +| 11 | BlockSizes | ','-separated block sizes | '224,423' | ++-----+-------------+-----------------------------------+--------------+ +| 12 | BlockStarts | ','-separated block starts | '2345,5245' | ++-----+-------------+-----------------------------------+--------------+ +"""""" + +import pandas as pd +import pyranges as pr +from copy import deepcopy +from . import common + +HEADERS = [ + 'Chromosome', 'Start', 'End', 'Name', 'Score', 'Strand', 'ThickStart', + 'ThickEnd', 'ItemRGB', 'BlockCount', 'BlockSizes', 'BlockStarts' +] + +class BedFrame: + """""" + Class for storing BED data. + + Parameters + ---------- + meta : list + Metadata lines. + gr : pyranges.PyRanges + PyRanges object containing BED data. + + See Also + -------- + BedFrame.from_dict + Construct BedFrame from a dict of array-like or dicts. + BedFrame.from_file + Construct BedFrame from a BED file. + BedFrame.from_frame + Construct BedFrame from a dataframe. + BedFrame.from_region + Construct BedFrame from a list of regions. + + Examples + -------- + + >>> import pandas as pd + >>> import pyranges as pr + >>> from fuc import pybed + >>> data = { + ... 'Chromosome': ['chr1', 'chr2', 'chr3'], + ... 'Start': [100, 400, 100], + ... 'End': [200, 500, 200] + ... } + >>> df = pd.DataFrame(data) + >>> gr = pr.PyRanges(df) + >>> bf = pybed.BedFrame([], gr) + >>> bf.gr.df + Chromosome Start End + 0 chr1 100 200 + 1 chr2 400 500 + 2 chr3 100 200 + """""" + def __init__(self, meta, gr): + self._meta = meta + self._gr = gr + + @property + def meta(self): + """"""list : Metadata lines."""""" + return self._meta + + @meta.setter + def meta(self, value): + self._meta = value + + @property + def gr(self): + """"""pyranges.PyRanges : Two-dimensional representation of genomic + intervals and their annotations."""""" + return self._gr + + @gr.setter + def gr(self, value): + self._gr = value + + @property + def contigs(self): + """"""list : List of contig names."""""" + return self.gr.chromosomes + + @property + def shape(self): + """"""tuple : Dimensionality of BedFrame (intervals, columns)."""""" + return self.gr.df.shape + + @property + def has_chr_prefix(self): + """"""bool : Whether the (annoying) 'chr' string is found."""""" + for contig in self.contigs: + if 'chr' in contig: + return True + return False + + def copy_meta(self): + """"""Return a copy of the metadata."""""" + return deepcopy(self.meta) + + def to_file(self, fn): + """"""Write the BedFrame to a BED file."""""" + with open(fn, 'w') as f: + if self.meta: + f.write('\n'.join(self.meta) + '\n') + self.gr.df.to_csv(f, sep='\t', index=False, header=False) + + def to_string(self): + """"""Render the BedFrame to a console-friendly tabular output."""""" + s = '' + if self.meta: + s += '\n'.join(self.meta) + '\n' + s += self.gr.df.to_csv(header=False, index=False, sep='\t') + return s + + def intersect(self, other): + """"""Find intersection between the BedFrames."""""" + bf = self.__class__(deepcopy(self.meta), self.gr.intersect(other.gr)) + return bf + + @classmethod + def from_dict(cls, meta, data): + """""" + Construct BedFrame from a dict of array-like or dicts. + + Parameters + ---------- + meta : list + Metadata lines. + data : dict + Of the form {field : array-like} or {field : dict}. + + Returns + ------- + BedFrame + BedFrame object. + + See Also + -------- + BedFrame + BedFrame object creation using constructor. + BedFrame.from_file + Construct BedFrame from a BED file. + BedFrame.from_frame + Construct BedFrame from a dataframe. + BedFrame.from_region + Construct BedFrame from a list of regions. + + Examples + -------- + + >>> from fuc import pybed + >>> data = { + ... 'Chromosome': ['chr1', 'chr2', 'chr3'], + ... 'Start': [100, 400, 100], + ... 'End': [200, 500, 200] + ... } + >>> bf = pybed.BedFrame.from_dict([], data) + >>> bf.gr.df + Chromosome Start End + 0 chr1 100 200 + 1 chr2 400 500 + 2 chr3 100 200 + """""" + return cls(meta, pr.PyRanges(pd.DataFrame(data))) + + @classmethod + def from_file(cls, fn): + """""" + Construct BedFrame from a BED file. + + Parameters + ---------- + fn : str + BED file path. + + Returns + ------- + BedFrame + BedFrame object. + + See Also + -------- + BedFrame + BedFrame object creation using constructor. + BedFrame.from_dict + Construct BedFrame from a dict of array-like or dicts. + BedFrame.from_frame + Construct BedFrame from a dataframe. + BedFrame.from_region + Construct BedFrame from a list of regions. + + Examples + -------- + + >>> from fuc import pybed + >>> bf = pybed.BedFrame.from_file('example.bed') + """""" + meta = [] + skip_rows = 0 + with open(fn, 'r') as f: + for line in f: + if 'browser' in line or 'track' in line: + meta.append(line.strip()) + skip_rows += 1 + else: + headers = HEADERS[:len(line.strip().split())] + break + df = pd.read_table(fn, header=None, names=headers, skiprows=skip_rows) + return cls(meta, pr.PyRanges(df)) + + @classmethod + def from_frame(cls, meta, data): + """""" + Construct BedFrame from a dataframe. + + Parameters + ---------- + meta : list + Metadata lines. + data : pandas.DataFrame + DataFrame containing BED data. + + Returns + ------- + BedFrame + BedFrame object. + + See Also + -------- + BedFrame + BedFrame object creation using constructor. + BedFrame.from_dict + Construct BedFrame from a dict of array-like or dicts. + BedFrame.from_file + Construct BedFrame from a BED file. + BedFrame.from_region + Construct BedFrame from a list of regions. + + Examples + -------- + + >>> import pandas as pd + >>> from fuc import pybed + >>> data = { + ... 'Chromosome': ['chr1', 'chr2', 'chr3'], + ... 'Start': [100, 400, 100], + ... 'End': [200, 500, 200] + ... } + >>> df = pd.DataFrame(data) + >>> bf = pybed.BedFrame.from_frame([], df) + >>> bf.gr.df + Chromosome Start End + 0 chr1 100 200 + 1 chr2 400 500 + 2 chr3 100 200 + """""" + return cls(meta, pr.PyRanges(data)) + + @classmethod + def from_regions(cls, meta, regions): + """""" + Construct BedFrame from a list of regions. + + Parameters + ---------- + meta : list + Metadata lines. + regions : str or list + Region or list of regions. + + Returns + ------- + BedFrame + BedFrame object. + + See Also + -------- + BedFrame + BedFrame object creation using constructor. + BedFrame.from_dict + Construct BedFrame from a dict of array-like or dicts. + BedFrame.from_file + Construct BedFrame from a BED file. + BedFrame.from_frame + Construct BedFrame from a dataframe. + + Examples + -------- + + >>> from fuc import pybed + >>> data = ['chr1:100-200', 'chr2:100-200', 'chr3:100-200'] + >>> bf = pybed.BedFrame.from_regions([], data) + >>> bf.gr.df + Chromosome Start End + 0 chr1 100 200 + 1 chr2 100 200 + 2 chr3 100 200 + """""" + if isinstance(regions, str): + regions = [regions] + chroms = [] + starts = [] + ends = [] + for region in regions: + chrom, start, end = common.parse_region(region) + chroms.append(chrom) + starts.append(start) + ends.append(end) + data = {'Chromosome': chroms, 'Start': starts, 'End': ends} + return cls.from_dict([], data) + + def update_chr_prefix(self, mode='remove'): + """""" + Add or remove the (annoying) 'chr' string from the Chromosome column. + + Parameters + ---------- + mode : {'add', 'remove'}, default: 'remove' + Whether to add or remove the 'chr' string. + + Returns + ------- + BedFrame + Updated BedFrame. + + Examples + -------- + + >>> from fuc import pybed + >>> data = { + ... 'Chromosome': ['1', '1', 'chr2', 'chr2'], + ... 'Start': [100, 400, 100, 200], + ... 'End': [200, 500, 200, 300] + ... } + >>> bf = pybed.BedFrame.from_dict([], data) + >>> bf.gr.df + Chromosome Start End + 0 1 100 200 + 1 1 400 500 + 2 chr2 100 200 + 3 chr2 200 300 + >>> bf.update_chr_prefix(mode='remove').gr.df + Chromosome Start End + 0 1 100 200 + 1 1 400 500 + 2 2 100 200 + 3 2 200 300 + >>> bf.update_chr_prefix(mode='add').gr.df + Chromosome Start End + 0 chr1 100 200 + 1 chr1 400 500 + 2 chr2 100 200 + 3 chr2 200 300 + """""" + if mode == 'remove': + def one_row(r): + r.Chromosome = r.Chromosome.replace('chr', '') + return r + elif mode == 'add': + def one_row(r): + if 'chr' not in r.Chromosome: + r.Chromosome = 'chr' + r.Chromosome + return r + else: + raise ValueError(f'Incorrect mode: {mode}') + df = self.gr.df.apply(one_row, axis=1) + return self.__class__([], pr.PyRanges(df)) + + def sort(self): + """""" + Sort the BedFrame by chromosome and position. + + Returns + ------- + BedFrame + Sorted BedFrame. + + Examples + -------- + + >>> from fuc import pybed + >>> data = { + ... 'Chromosome': ['chr1', 'chr3', 'chr1'], + ... 'Start': [400, 100, 100], + ... 'End': [500, 200, 200] + ... } + >>> bf = pybed.BedFrame.from_dict([], data) + >>> bf.gr.df + Chromosome Start End + 0 chr1 400 500 + 1 chr1 100 200 + 2 chr3 100 200 + >>> bf.sort().gr.df + Chromosome Start End + 0 chr1 100 200 + 1 chr1 400 500 + 2 chr3 100 200 + """""" + return self.__class__(self.copy_meta(), self.gr.sort()) + + def merge(self): + """""" + Merge overlapping intervals within BedFrame. + + Returns + ------- + BedFrame + Merged BedFrame. + + Examples + -------- + + >>> from fuc import pybed + >>> data = { + ... 'Chromosome': ['chr1', 'chr1', 'chr2', 'chr2', 'chr3', 'chr3'], + ... 'Start': [10, 30, 15, 25, 50, 61], + ... 'End': [40, 50, 25, 35, 60, 80] + ... } + >>> bf = pybed.BedFrame.from_dict([], data) + >>> bf.gr.df + Chromosome Start End + 0 chr1 10 40 + 1 chr1 30 50 + 2 chr2 15 25 + 3 chr2 25 35 + 4 chr3 50 60 + 5 chr3 61 80 + >>> bf.merge().gr.df + Chromosome Start End + 0 chr1 10 50 + 1 chr2 15 35 + 2 chr3 50 60 + 3 chr3 61 80 + """""" + return self.__class__(self.copy_meta(), self.gr.merge()) + + def to_regions(self, merge=True): + """""" + Return a list of regions from BedFrame. + + Parameters + ---------- + merge : bool, default: True + Whether to merge overlapping intervals. + + Returns + ------- + list + List of regions. + + Examples + -------- + >>> from fuc import pybed + >>> data = { + ... 'Chromosome': ['chr1', 'chr1', 'chr2', 'chr2', 'chr3', 'chr3'], + ... 'Start': [10, 30, 15, 25, 50, 61], + ... 'End': [40, 50, 25, 35, 60, 80] + ... } + >>> bf = pybed.BedFrame.from_dict([], data) + >>> bf.to_regions() + ['chr1:10-50', 'chr2:15-35', 'chr3:50-60', 'chr3:61-80'] + >>> bf.to_regions(merge=False) + ['chr1:10-40', 'chr1:30-50', 'chr2:15-25', 'chr2:25-35', 'chr3:50-60', 'chr3:61-80'] + """""" + if merge: + bf = self.merge() + else: + bf = self + s = bf.gr.df.apply(lambda r: f'{r.Chromosome}:{r.Start}-{r.End}', axis=1) + return s.to_list() +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/api/pykallisto.py",".py","7880","211",""""""" +The pykallisto submodule is designed for working with RNAseq quantification +data from Kallisto. It implements ``pykallisto.KallistoFrame`` which stores +Kallisto's output data as ``pandas.DataFrame`` to allow fast computation and +easy manipulation. The ``pykallisto.KallistoFrame`` class also contains many +useful plotting methods such as ``KallistoFrame.plot_differential_abundance``. +"""""" + +import pandas as pd +import numpy as np +import seaborn as sns +import matplotlib.pyplot as plt + +class KallistoFrame: + """""" + Class for working with RNAseq quantification data from Kallisto. + + Parameters + ---------- + metadata : pandas.DataFrame + List of metadata lines. + tx2gene : pandas.DataFrame + DataFrame containing transcript to gene mapping data. + aggregation_column : str + Column name in ``tx2gene`` to aggregate transcripts to the gene level. + filter_func : func, optional + Filtering function to be applied to each row (i.e. transcript). By + default, the :meth:`pykallisto.basic_filter` method will be used. + filter_target_id : list, optional + Transcripts to filter using methods that can't be implemented using + ``filter_func``. If provided, this will override ``filter_func``. + filter_off : bool, default: False + If True, do not apply any filtering. Useful for generating a simple + count or tpm matrix. + """""" + + def _import_data( + self, metadata, filter_func=None, filter_target_id=None, + filter_off=False + ): + dfs = {} + for i, r in metadata.iterrows(): + df = pd.read_table(r['path'] + '/abundance.tsv', index_col=0) + dfs[i] = df + df_tx_count = pd.concat([v['est_counts'] for k, v in dfs.items()], axis=1) + df_tx_count.columns = metadata.index + df_tx_tpm = pd.concat([v['tpm'] for k, v in dfs.items()], axis=1) + df_tx_tpm.columns = metadata.index + + if filter_off: + filtered_ids = None + else: + if filter_target_id is None: + if filter_func is None: + filter_func = basic_filter + filtered_ids = df_tx_count.apply(filter_func, axis=1) + else: + filtered_ids = pd.Series(df_tx_count.index.isin(filter_target_id), + index=df_tx_count.index) + + return df_tx_count, df_tx_tpm, filtered_ids + + def __init__( + self, metadata, tx2gene, aggregation_column, filter_func=None, + filter_target_id=None, filter_off=False + ): + self.metadata = metadata + self.tx2gene = tx2gene + self.aggregation_column = aggregation_column + results = self._import_data(metadata, filter_func, + filter_target_id, filter_off) + self.df_tx_count = results[0] + self.df_tx_tpm = results[1] + self.filtered_ids = results[2] + self.df_gene_count = None + self.df_gene_tpm = None + + def aggregate(self, filter=True): + """""" + Aggregate transcript-level data to obtain gene-level data. + + Running this method will set the attributes + ``KallistoFrame.df_gene_count`` and ``KallistoFrame.df_gene_tpm``. + + Parameters + ---------- + filter : bool, default: True + If true, use filtered transcripts only. Otherwise, use all. + """""" + for unit in ['count', 'tpm']: + tx_df = getattr(self, f'df_tx_{unit}') + gene_s = self.tx2gene[self.aggregation_column] + df = pd.concat([tx_df, gene_s], axis=1) + if filter: + if self.filtered_ids is not None: + df = df[self.filtered_ids] + df = df.groupby(['gene_symbol']).sum() + setattr(self, f'df_gene_{unit}', df) + + def plot_differential_abundance( + self, gene, group, aggregate=True, filter=True, name='target_id', + unit='tpm', ax=None, figsize=None + ): + """""" + Plot differential abundance results for single gene. + + Parameters + ---------- + gene : str + Gene to compare. + group : str + Column in ``KallistoFrame.metadata`` specifying group information. + aggregate : bool, default: True + If true, display gene-level data (the + :meth:`KallistoFrame.aggregate` method must be run beforehand). + Otherwise, display transcript-level data. + filter : bool, default: True + If true, use filtered transcripts only. Otherwise, use all. + Ignored when ``aggregate=True``. + name : str, default: 'target_id' + Column in ``KallistoFrame.tx2gene`` specifying transcript name to + be displayed in the legend. Ignored when ``aggregate=True``. + unit : {'tpm', 'count'}, default: 'tpm' + Abundance unit to display. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + """""" + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + if aggregate: + s1 = getattr(self, f'df_gene_{unit}').loc[gene] + s1.name = unit + s2 = self.metadata[group] + df = pd.concat([s1, s2], axis=1) + sns.boxplot(x=group, y=unit, data=df, ax=ax) + else: + df = getattr(self, f'df_tx_{unit}') + if filter: + if self.filtered_ids is not None: + df = df[self.filtered_ids] + s = self.tx2gene[self.tx2gene[self.aggregation_column] == gene] + df = df[df.index.isin(s.index.to_list())] + if name != 'target_id': + df = df.merge(self.tx2gene[name], left_on='target_id', + right_index=True) + df = df.set_index(name) + df = df.T.melt(ignore_index=False, value_name=unit) + df = df.merge(self.metadata[group], left_index=True, + right_index=True) + sns.boxplot(x=group, y=unit, data=df, hue=name, ax=ax) + + return ax + + def compute_fold_change(self, group, genes, unit='tpm', flip=False): + """""" + Compute fold change of gene expression between two groups. + + Parameters + ---------- + group : str + Column in ``KallistoFrame.metadata`` specifying group information. + gene : list + Genes to compare. + unit : {'tpm', 'count'}, default: 'tpm' + Abundance unit to display. + flip : bool, default: False + If true, flip the denominator and numerator. + """""" + df = getattr(self, f'df_gene_{unit}') + df = df[df.index.isin(genes)].T + df = df.merge(self.metadata[group], left_index=True, right_index=True) + df = df.groupby(group).mean().T + a, b = df.columns + if flip: + a, b = b, a + s = np.log2(df[b] / df[a]) + print(f'# Fold change = log2( {b} / {a} )') + return s[genes] + +def basic_filter(row, min_reads=5, min_prop=0.47): + """""" + A basic filter to be used. + + By default, the method will filter out rows (i.e. transcripts) that do + not have at least 5 estimated counts in at least 47% of the samples. Note + that this is equivalent to the :meth:`sleuth.basic_filter` method. + + Parameters + ---------- + row : pandas.Series + This is a vector of numerics that will be passed in. + min_reads : int, default: 5 + The minimum number of estimated counts. + min_prop : float, default: 0.47 + The minimum proportion of samples. + + Returns + ------- + pd.Series + A pandas series of boolean. + """""" + return (row >= min_reads).mean() >= min_prop +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/api/pysnpeff.py",".py","3161","102",""""""" +The pysnpeff submodule is designed for parsing VCF annotation data from +the `SnpEff `_ program. It should be +used with ``pyvcf.VcfFrame``. + +One VCF record can have several SnpEff annotations if, for example, +the record is a multiallelic site or the variant is shared by +multiple genes. When more than one annotations are reported, SnpEff +will sort them by their importance. For more details, visit the `official +website `_. + +For each annotation, SnpEff provides the following data: + +1. Allele - ALT allele. +2. Annotation - Sequence Ontology terms concatenated using '&'. +3. Annotation_Impact - HIGH, MODERATE, LOW, or MODIFIER. +4. Gene_Name - Common gene name (HGNC). +5. Gene_ID - Gene ID. +6. Feature_Type - Which type of feature is in the next field. +7. Feature_ID - Transcript ID, Motif ID, miRNA, ChipSeq peak, etc. +8. Transcript_BioType - Coding or noncoding. +9. Rank - Exon or Intron rank / total number of exons or introns. +10. HGVS.c - Variant using HGVS notation (DNA level). +11. HGVS.p - Variant using HGVS notation (Protein level). +12. cDNA.pos / cDNA.length - Position in cDNA and trancript's cDNA length. +13. CDS.pos / CDS.length - Position and number of coding bases. +14. AA.pos / AA.length - Position and number of AA. +15. Distance - All items in this field are options. +16. ERRORS / WARNINGS - Messages that can affect annotation accuracy. +17. INFO - Additional information. +"""""" + +def row_firstann(r): + """""" + Return the first SnpEff annotation for the row."""""" + ann = [x for x in r.INFO.split(';') if 'ANN=' in x] + if not ann: + return '' + ann = ann[0].replace('ANN=', '').split(',')[0] + return ann + +def filter_ann(vf, targets, include=True): + """""" + Filter out rows based on the SnpEff annotations. + + Parameters + ---------- + vf : fuc.api.pyvcf.VcfFrame + Input VcfFrame. + targets : list + List of annotations (e.g. ['missense_variant', 'stop_gained']). + include : bool, default: False + If True, include only such rows instead of excluding them. + + Returns + ------- + vf : VcfFrame + Filtered VcfFrame. + """""" + def func(r): + ann = row_firstann(r) + if not ann: + return False + ann = ann.split('|')[1] + has_ann = ann in targets + if include: + return has_ann + else: + return not has_ann + i = vf.df.apply(func, axis=1) + df = vf.df[i].reset_index(drop=True) + vf = vf.__class__(vf.copy_meta(), df) + return vf + +def parseann(vf, idx, sep=' | '): + """""" + Parse SnpEff annotations. + + Parameters + ---------- + vf : fuc.api.pyvcf.VcfFrame + Input VcfFrame. + i : list + List of annotation indicies. + sep : str, default: ' | ' + Separator for joining requested annotations. + + Returns + ------- + s : pandas.Series + Parsed annotations. + """""" + def func(r): + ann = row_firstann(r) + if not ann: + return '.' + ann = ann.split('|') + ann = sep.join([ann[i] for i in idx]) + return ann + s = vf.df.apply(func, axis=1) + return s +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/api/pycov.py",".py","41354","1309",""""""" +The pycov submodule is designed for working with depth of coverage data +from sequence alingment files (SAM/BAM/CRAM). It implements +``pycov.CovFrame`` which stores read depth data as ``pandas.DataFrame`` via +the `pysam `_ package to +allow fast computation and easy manipulation. The ``pycov.CovFrame`` class +also contains many useful plotting methods such as ``CovFrame.plot_region`` +and ``CovFrame.plot_uniformity``. +"""""" +from io import StringIO, IOBase +import warnings +import gzip +from pathlib import Path + +from . import common, pybam, pybed + +import pysam +import numpy as np +import pandas as pd +import seaborn as sns +import matplotlib.pyplot as plt + +def concat(cfs, axis=0): + """""" + Concatenate CovFrame objects along a particular axis. + + Parameters + ---------- + cfs : list + List of CovFrame objects. + axis : {0/'index', 1/'columns'}, default: 0 + The axis to concatenate along. + + Returns + ------- + CovFrame + Concatenated CovFrame. + """""" + if axis: + df = pd.concat([x.df.set_index(['Chromosome', 'Position']) + for x in cfs], axis=axis).reset_index() + else: + df = pd.concat([x.df for x in cfs], axis=axis) + return CovFrame(df) + +def simulate(mode='wgs', loc=30, scale=5, size=1000): + """""" + Simulate read depth data for single sample. + + Generated read depth will be integer and non-negative. + + Parameters + ---------- + mode : {'wgs'}, default: 'wgs' + Additional modes will be made available in future releases. + loc : float, default: 30 + Mean (""centre"") of the distribution. + scale : float, default: 5 + Standard deviation (spread or ""width"") of the distribution. Must be + non-negative. + size : int, default: 1000 + Number of base pairs to return. + + Returns + ------- + numpy.ndarray + Numpy array object. + + Examples + -------- + + >>> from fuc import pycov + >>> pycov.simulate(size=10) + array([25, 32, 30, 31, 26, 25, 33, 29, 28, 35]) + """""" + a = np.random.normal(loc=loc, scale=scale, size=size) + + # Read depth must be integer. + a = a.astype(int) + + # Read dpeth must be non-negative. + a = np.absolute(a) + + return a + +def merge( + cfs, how='inner' +): + """""" + Merge CovFrame objects. + + Parameters + ---------- + cfs : list + List of CovFrames to be merged. Note that the 'chr' prefix in contig + names (e.g. 'chr1' vs. '1') will be automatically added or removed as + necessary to match the contig names of the first CovFrame. + how : str, default: 'inner' + Type of merge as defined in :meth:`pandas.merge`. + + Returns + ------- + CovFrame + Merged CovFrame. + + See Also + -------- + CovFrame.merge + Merge self with another CovFrame. + + Examples + -------- + Assume we have the following data: + + >>> import numpy as np + >>> from fuc import pycov + >>> data1 = { + ... 'Chromosome': ['chr1'] * 5, + ... 'Position': np.arange(100, 105), + ... 'A': pycov.simulate(loc=35, scale=5, size=5), + ... 'B': pycov.simulate(loc=25, scale=7, size=5), + ... } + >>> data2 = { + ... 'Chromosome': ['1'] * 5, + ... 'Position': np.arange(102, 107), + ... 'C': pycov.simulate(loc=35, scale=5, size=5), + ... } + >>> cf1 = pycov.CovFrame.from_dict(data1) + >>> cf2 = pycov.CovFrame.from_dict(data2) + >>> cf1.df + Chromosome Position A B + 0 chr1 100 33 17 + 1 chr1 101 36 20 + 2 chr1 102 39 39 + 3 chr1 103 31 19 + 4 chr1 104 31 10 + >>> cf2.df + Chromosome Position C + 0 1 102 41 + 1 1 103 37 + 2 1 104 35 + 3 1 105 33 + 4 1 106 39 + + We can merge the two VcfFrames with `how='inner'` (default): + + >>> pycov.merge([cf1, cf2]).df + Chromosome Position A B C + 0 chr1 102 39 39 41 + 1 chr1 103 31 19 37 + 2 chr1 104 31 10 35 + + We can also merge with `how='outer'`: + + >>> pycov.merge([cf1, cf2], how='outer').df + Chromosome Position A B C + 0 chr1 100 33.0 17.0 NaN + 1 chr1 101 36.0 20.0 NaN + 2 chr1 102 39.0 39.0 41.0 + 3 chr1 103 31.0 19.0 37.0 + 4 chr1 104 31.0 10.0 35.0 + 5 chr1 105 NaN NaN 33.0 + 6 chr1 106 NaN NaN 39.0 + """""" + merged_cf = cfs[0] + for cf in cfs[1:]: + merged_cf = merged_cf.merge(cf, how=how) + return merged_cf + +class CovFrame: + """""" + Class for storing read depth data from one or more SAM/BAM/CRAM files. + + Parameters + ---------- + df : pandas.DataFrame + DataFrame containing read depth data. + + See Also + -------- + CovFrame.from_bam + Construct CovFrame from BAM files. + CovFrame.from_dict + Construct CovFrame from dict of array-like or dicts. + CovFrame.from_file + Construct CovFrame from a text file containing read depth data. + + Examples + -------- + + >>> import numpy as np + >>> import pandas as pd + >>> from fuc import pycov + >>> data = { + ... 'Chromosome': ['chr1'] * 1000, + ... 'Position': np.arange(1000, 2000), + ... 'A': pycov.simulate(loc=35, scale=5), + ... 'B': pycov.simulate(loc=25, scale=7), + ... } + >>> df = pd.DataFrame(data) + >>> cf = pycov.CovFrame(df) + >>> cf.df.head() + Chromosome Position A B + 0 chr1 1000 22 23 + 1 chr1 1001 34 30 + 2 chr1 1002 33 27 + 3 chr1 1003 32 21 + 4 chr1 1004 32 15 + """""" + def _check_df(self, df): + df = df.reset_index(drop=True) + df.Chromosome = df.Chromosome.astype(str) + return df + + def __init__(self, df): + self._df = self._check_df(df) + + @property + def df(self): + """"""pandas.DataFrame : DataFrame containing read depth data."""""" + return self._df + + @df.setter + def df(self, value): + self._df = self._check_df(value) + + @property + def contigs(self): + """"""list : List of contig names."""""" + return list(self.df.Chromosome.unique()) + + @property + def has_chr_prefix(self): + """"""bool : Whether the (annoying) 'chr' string is found."""""" + for contig in self.contigs: + if 'chr' in contig: + return True + return False + + @property + def samples(self): + """"""list : List of the sample names."""""" + return self.df.columns[2:].to_list() + + @property + def shape(self): + """"""tuple : Dimensionality of CovFrame (positions, samples)."""""" + return (self.df.shape[0], len(self.samples)) + + @classmethod + def from_bam( + cls, bams, regions=None, zero=False, map_qual=None, names=None + ): + """""" + Construct CovFrame from BAM files. + + Under the hood, the method computes read depth using the + :command:`samtools depth` command. + + Parameters + ---------- + bams : str or list + One or more input BAM files. Alternatively, you can provide a + text file (.txt, .tsv, .csv, or .list) containing one BAM file + per line. + regions : str, list, or pybed.BedFrame, optional + By default (``regions=None``), the method counts all reads in BAM + files, which can be excruciatingly slow for large files (e.g. + whole genome sequencing). Therefore, use this argument to only + output positions in given regions. Each region must have the + format chrom:start-end and be a half-open interval with (start, + end]. This means, for example, chr1:100-103 will extract + positions 101, 102, and 103. Alternatively, you can provide a BED + file (compressed or uncompressed) or a :class:`pybed.BedFrame` + object to specify regions. Note that the 'chr' prefix in contig + names (e.g. 'chr1' vs. '1') will be automatically added or + removed as necessary to match the input BAM's contig names. + zero : bool, default: False + If True, output all positions including those with zero depth. + map_qual: int, optional + Only count reads with mapping quality greater than or equal to + this number. + names : list, optional + By default (``names=None``), sample name is extracted using SM + tag in BAM files. If the tag is missing, the method will set the + filename as sample name. Use this argument to manually provide + sample names. + + Returns + ------- + CovFrame + CovFrame object. + + See Also + -------- + CovFrame + CovFrame object creation using constructor. + CovFrame.from_dict + Construct CovFrame from dict of array-like or dicts. + CovFrame.from_file + Construct CovFrame from a text file containing read depth data. + + Examples + -------- + + >>> from fuc import pycov + >>> cf = pycov.CovFrame.from_bam(bam) + >>> cf = pycov.CovFrame.from_bam([bam1, bam2]) + >>> cf = pycov.CovFrame.from_bam(bam, region='19:41497204-41524301') + """""" + # Parse input BAM files. + bams = common.parse_list_or_file(bams) + + # Check the 'chr' prefix. + if all([pybam.has_chr_prefix(x) for x in bams]): + chr_prefix = 'chr' + else: + chr_prefix = '' + + # Run the 'samtools depth' command. + args = [] + if zero: + args += ['-a'] + if map_qual is not None: + args += ['-Q', str(map_qual)] + results = '' + if regions is None: + results += pysam.depth(*(bams + args)) + else: + if isinstance(regions, str): + regions = [regions] + elif isinstance(regions, list): + pass + elif isinstance(regions, pybed.BedFrame): + regions = bf.to_regions() + else: + raise TypeError(""Incorrect type of argument 'regions'"") + if '.bed' in regions[0]: + bf = pybed.BedFrame.from_file(regions[0]) + regions = bf.to_regions() + else: + regions = common.sort_regions(regions) + for region in regions: + region = chr_prefix + region.replace('chr', '') + results += pysam.depth(*(bams + args + ['-r', region])) + + headers = ['Chromosome', 'Position'] + dtype = {'Chromosome': str,'Position': int} + + for i, bam in enumerate(bams): + if names: + name = names[i] + else: + samples = pybam.tag_sm(bam) + if not samples: + basename = Path(bam).stem + message = ( + f'SM tags were not found for {bam}, will use ' + f'file name as sample name ({basename})' + ) + samples = [basename] + warnings.warn(message) + if len(samples) > 1: + m = f'multiple sample names detected: {bam}' + raise ValueError(m) + name = samples[0] + headers.append(name) + dtype[name] = int + + df = pd.read_csv( + StringIO(results), sep='\t', header=None, + names=headers, dtype=dtype + ) + + return cls(df) + + @classmethod + def from_dict(cls, data): + """""" + Construct CovFrame from dict of array-like or dicts. + + Parameters + ---------- + data : dict + Of the form {field : array-like} or {field : dict}. + + Returns + ------- + CovFrame + CovFrame object. + + See Also + -------- + CovFrame + CovFrame object creation using constructor. + CovFrame.from_bam + Construct CovFrame from BAM files. + CovFrame.from_file + Construct CovFrame from a text file containing read depth data. + + Examples + -------- + + >>> import numpy as np + >>> from fuc import pycov + >>> data = { + ... 'Chromosome': ['chr1'] * 1000, + ... 'Position': np.arange(1000, 2000), + ... 'A': pycov.simulate(loc=35, scale=5), + ... 'B': pycov.simulate(loc=25, scale=7), + ... } + >>> cf = pycov.CovFrame.from_dict(data) + >>> cf.df.head() + Chromosome Position A B + 0 chr1 1000 36 22 + 1 chr1 1001 39 35 + 2 chr1 1002 33 19 + 3 chr1 1003 36 20 + 4 chr1 1004 31 24 + """""" + return cls(pd.DataFrame(data)) + + @classmethod + def from_file(cls, fn, compression=False): + """""" + Construct CovFrame from a TSV file containing read depth data. + + Parameters + ---------- + fn : str or file-like object + TSV file (compressed or uncompressed). By file-like object, we + refer to objects with a :meth:`read()` method, such as a file + handle. + compression : bool, default: False + If True, use GZIP decompression regardless of filename. + + Returns + ------- + CovFrame + CovFrame object. + + See Also + -------- + CovFrame + CovFrame object creation using constructor. + CovFrame.from_bam + Construct CovFrame from BAM files. + CovFrame.from_dict + Construct CovFrame from dict of array-like or dicts. + + Examples + -------- + + >>> from fuc import pycov + >>> cf = pycov.CovFrame.from_file('unzipped.tsv') + >>> cf = pycov.CovFrame.from_file('zipped.tsv.gz') + >>> cf = pycov.CovFrame.from_file('zipped.tsv', compression=True) + """""" + if isinstance(fn, IOBase): + return cls(pd.read_table(fn)) + + if fn.endswith('.gz') or compression: + f = gzip.open(fn, 'rt') + else: + f = open(fn) + + headers = f.readline().strip().split('\t') + + f.close() + + if 'Chromosome' not in headers: + raise ValueError(""Input file is missing 'Chromosome' column"") + + if 'Position' not in headers: + raise ValueError(""Input file is missing 'Position' column"") + + dtype = {} + + for header in headers: + if header == 'Chromosome': + dtype[header] = str + elif header == 'Position': + dtype[header] = float + else: + dtype[header] = float + + return cls(pd.read_table(fn, dtype=dtype)) + + def plot_region( + self, sample, region=None, samples=None, label=None, ax=None, figsize=None, + **kwargs + ): + """""" + Create read depth profile for specified region. + + Region can be omitted if there is only one contig in the CovFrame. + + Parameters + ---------- + region : str, optional + Target region ('chrom:start-end'). + label : str, optional + Label to use for the data points. + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`seaborn.lineplot`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + Examples + -------- + Below is a simple example: + + .. plot:: + :context: close-figs + + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> from fuc import pycov + >>> data = { + ... 'Chromosome': ['chr1'] * 1000, + ... 'Position': np.arange(1000, 2000), + ... 'A': pycov.simulate(loc=35, scale=5), + ... 'B': pycov.simulate(loc=25, scale=7), + ... } + >>> cf = pycov.CovFrame.from_dict(data) + >>> ax = cf.plot_region('A') + >>> plt.tight_layout() + + We can draw multiple profiles in one plot: + + .. plot:: + :context: close-figs + + >>> ax = cf.plot_region('A', label='A') + >>> cf.plot_region('B', label='B', ax=ax) + >>> ax.legend() + >>> plt.tight_layout() + """""" + if self.df.empty: + raise ValueError('CovFrame is empty') + + if region is None: + if len(self.contigs) == 1: + cf = self.copy() + else: + raise ValueError('Multiple contigs found') + else: + cf = self.slice(region) + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + sns.lineplot( + data=cf.df, x='Position', y=sample, ax=ax, label=label, **kwargs + ) + + ax.set_ylabel('Depth') + + return ax + + def slice(self, region): + """""" + Slice the CovFrame for the region. + + Parameters + ---------- + region : str + Region (‘chrom:start-end’). + + Returns + ------- + CovFrame + Sliced CovFrame. + + Examples + -------- + + >>> import numpy as np + >>> from fuc import pycov + >>> data = { + ... 'Chromosome': ['chr1']*500 + ['chr2']*500, + ... 'Position': np.arange(1000, 2000), + ... 'A': pycov.simulate(loc=35, scale=5), + ... 'B': pycov.simulate(loc=25, scale=7), + ... } + >>> cf = pycov.CovFrame.from_dict(data) + >>> cf.slice('chr2').df.head() + Chromosome Position A B + 0 chr2 1500 37 34 + 1 chr2 1501 28 12 + 2 chr2 1502 35 29 + 3 chr2 1503 34 34 + 4 chr2 1504 32 21 + >>> cf.slice('chr2:1500-1504').df + Chromosome Position A B + 0 chr2 1500 37 34 + 1 chr2 1501 28 12 + 2 chr2 1502 35 29 + 3 chr2 1503 34 34 + 4 chr2 1504 32 21 + >>> cf.slice('chr2:-1504').df + Chromosome Position A B + 0 chr2 1500 37 34 + 1 chr2 1501 28 12 + 2 chr2 1502 35 29 + 3 chr2 1503 34 34 + 4 chr2 1504 32 21 + """""" + chrom, start, end = common.parse_region(region) + df = self.df[self.df.Chromosome == chrom] + if not pd.isna(start): + df = df[df.Position >= start] + if not pd.isna(end): + df = df[df.Position <= end] + return self.__class__(df) + + def to_string(self): + """""" + Render the CovFrame to a console-friendly tabular output. + + Returns + ------- + str + String representation of the CovFrame. + """""" + return self.df.to_csv(index=False, sep='\t') + + def matrix_uniformity( + self, frac=0.1, n=20, m=None + ): + """""" + Compute a matrix of fraction of sampled bases >= coverage with a + shape of (coverages, samples). + + Parameters + ---------- + frac : float, default: 0.1 + Fraction of data to be sampled (to speed up the process). + n : int or list, default: 20 + Number of evenly spaced points to generate for the x-axis. + Alternatively, positions can be manually specified by providing + a list. + m : float, optional + Maximum point in the x-axis. By default, it will be the maximum + depth in the entire dataset. + + Returns + ------- + pandas.DataFrame + Matrix of fraction of sampled bases >= coverage. + + Examples + -------- + + >>> import numpy as np + >>> from fuc import pycov + >>> data = { + ... 'Chromosome': ['chr1'] * 1000, + ... 'Position': np.arange(1000, 2000), + ... 'A': pycov.simulate(loc=35, scale=5), + ... 'B': pycov.simulate(loc=25, scale=7), + ... } + >>> cf = pycov.CovFrame.from_dict(data) + >>> cf.matrix_uniformity() + A B + Coverage + 1.000000 1.00 1.00 + 3.368421 1.00 1.00 + 5.736842 1.00 1.00 + 8.105263 1.00 1.00 + 10.473684 1.00 1.00 + 12.842105 1.00 0.98 + 15.210526 1.00 0.93 + 17.578947 1.00 0.87 + 19.947368 1.00 0.77 + 22.315789 1.00 0.64 + 24.684211 1.00 0.50 + 27.052632 0.97 0.35 + 29.421053 0.84 0.25 + 31.789474 0.70 0.16 + 34.157895 0.51 0.07 + 36.526316 0.37 0.07 + 38.894737 0.21 0.03 + 41.263158 0.09 0.02 + 43.631579 0.04 0.00 + 46.000000 0.02 0.00 + """""" + # Sample positions to speed up the process. + df = self.df.sample(frac=frac) + + # Determine x-axis points. + if isinstance(n, list): + coverages = n + else: + if m is None: + m = df.iloc[:, 2:].max().max() + coverages = np.linspace(1, m, n, endpoint=True) + + data = {'Coverage': coverages} + + for sample in self.samples: + fractions = [] + for coverage in coverages: + count = sum(df[sample] >= coverage) + fractions.append(count / df.shape[0]) + data[sample] = fractions + + df = pd.DataFrame(data) + df = df.set_index(""Coverage"") + + return df + + def plot_uniformity( + self, mode='aggregated', frac=0.1, n=20, m=None, marker=None, + ax=None, figsize=None, **kwargs + ): + """""" + Create a line plot visualizing the uniformity in read depth. + + Parameters + ---------- + mode : {'aggregated', 'individual'}, default: 'aggregated' + Determines how to display the lines: + + - 'aggregated': Aggregate over repeated values to show the mean + and 95% confidence interval. + - 'individual': Show data for individual samples. + + frac : float, default: 0.1 + Fraction of data to be sampled (to speed up the process). + n : int or list, default: 20 + Number of evenly spaced points to generate for the x-axis. + Alternatively, positions can be manually specified by providing + a list. + m : float, optional + Maximum point in the x-axis. By default, it will be the maximum + depth in the entire dataset. + marker : str, optional + Marker style string (e.g. 'o'). + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`seaborn.lineplot`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + Examples + -------- + By default (``mode='aggregated'``), the method will aggregate over + repeated values: + + .. plot:: + :context: close-figs + + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> from fuc import pycov + >>> data = { + ... 'Chromosome': ['chr1'] * 1000, + ... 'Position': np.arange(1000, 2000), + ... 'A': pycov.simulate(loc=35, scale=5), + ... 'B': pycov.simulate(loc=25, scale=7), + ... } + >>> cf = pycov.CovFrame.from_dict(data) + >>> cf.plot_uniformity(mode='aggregated') + >>> plt.tight_layout() + + We can display data for individual samples: + + .. plot:: + :context: close-figs + + >>> cf.plot_uniformity(mode='individual') + >>> plt.tight_layout() + """""" + df = self.matrix_uniformity(frac=frac, n=n, m=m) + df = df.reset_index() + df = df.melt(id_vars=['Coverage'], var_name='Sample', + value_name='Fraction') + + # Determines how to display the lines. + if mode == 'aggregated': + hue = None + else: + hue = 'Sample' + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + sns.lineplot( + x='Coverage', y='Fraction', data=df, hue=hue, marker=marker, + ax=ax, **kwargs + ) + + ax.set_xlabel('Coverage') + ax.set_ylabel('Fraction of sampled bases >= coverage') + + return ax + + def plot_distribution( + self, mode='aggregated', frac=0.1, ax=None, figsize=None, **kwargs + ): + """""" + Create a line plot visualizaing the distribution of per-base read depth. + + Parameters + ---------- + mode : {'aggregated', 'individual'}, default: 'aggregated' + Determines how to display the lines: + + - 'aggregated': Aggregate over repeated values to show the mean + and 95% confidence interval. + - 'individual': Show data for individual samples. + + frac : float, default: 0.1 + Fraction of data to be sampled (to speed up the process). + ax : matplotlib.axes.Axes, optional + Pre-existing axes for the plot. Otherwise, crete a new one. + figsize : tuple, optional + Width, height in inches. Format: (float, float). + kwargs + Other keyword arguments will be passed down to + :meth:`seaborn.lineplot`. + + Returns + ------- + matplotlib.axes.Axes + The matplotlib axes containing the plot. + + Examples + -------- + By default (``mode='aggregated'``), the method will aggregate over + repeated values: + + .. plot:: + :context: close-figs + + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> from fuc import pycov + >>> data = { + ... 'Chromosome': ['chr1'] * 1000, + ... 'Position': np.arange(1000, 2000), + ... 'A': pycov.simulate(loc=35, scale=5), + ... 'B': pycov.simulate(loc=25, scale=7), + ... } + >>> cf = pycov.CovFrame.from_dict(data) + >>> cf.plot_distribution(mode='aggregated', frac=0.9) + >>> plt.tight_layout() + + We can display data for individual samples: + + .. plot:: + :context: close-figs + + >>> cf.plot_distribution(mode='individual', frac=0.9) + >>> plt.tight_layout() + """""" + # Sample positions to speed up the process. + df = self.df.sample(frac=frac) + + def one_col(c): + s = c.value_counts() + s = s / s.sum() + return s + + df = df.iloc[:, 2:].apply(one_col) + df = df.fillna(0) + df = df.reset_index().rename(columns=dict(index='Coverage')) + df = df.melt(id_vars='Coverage', var_name='Sample', + value_name='Fraction') + + # Determines how to display the lines. + if mode == 'aggregated': + hue = None + else: + hue = 'Sample' + + if ax is None: + fig, ax = plt.subplots(figsize=figsize) + + sns.lineplot( + x='Coverage', y='Fraction', data=df, hue=hue, ax=ax, **kwargs + ) + + ax.set_xlabel('Coverage') + ax.set_ylabel('Fraction of sampled bases') + + return ax + + def copy_df(self): + """"""Return a copy of the dataframe."""""" + return self.df.copy() + + def copy(self): + """"""Return a copy of the CovFrame."""""" + return self.__class__(self.copy_df()) + + def to_string(self): + """""" + Render the CovFrame to a console-friendly tabular output. + + Returns + ------- + str + String representation of the CovFrame. + """""" + return self.df.to_csv(index=False, sep='\t') + + def to_file(self, fn, compression=False): + """""" + Write the CovFrame to a TSV file. + + If the file name ends with '.gz', the method will automatically + use the GZIP compression when writing the file. + + Parameters + ---------- + fn : str + TSV file (compressed or uncompressed). + compression : bool, default: False + If True, use the GZIP compression. + """""" + if fn.endswith('.gz') or compression: + f = gzip.open(fn, 'wt') + else: + f = open(fn, 'w') + f.write(self.to_string()) + f.close() + + def mask_bed(self, bed, opposite=False): + """""" + Mask rows that overlap with BED data. + + Parameters + ---------- + bed : pybed.BedFrame or str + BedFrame object or BED file. + opposite : bool, default: False + If True, mask rows that don't overlap with BED data. + + Returns + ------- + CovFrame + Masked CovFrame. + + Examples + -------- + Assume we have the following data: + + >>> import numpy as np + >>> from fuc import pycov, pybed + >>> data = { + ... 'Chromosome': ['chr1'] * 1000, + ... 'Position': np.arange(1000, 2000), + ... 'A': pycov.simulate(loc=35, scale=5), + ... 'B': pycov.simulate(loc=25, scale=7), + ... } + >>> cf = pycov.CovFrame.from_dict(data) + >>> cf.df.head() + Chromosome Position A B + 0 chr1 1000 34 31 + 1 chr1 1001 31 20 + 2 chr1 1002 41 22 + 3 chr1 1003 28 41 + 4 chr1 1004 34 23 + >>> data = { + ... 'Chromosome': ['chr1', 'chr1'], + ... 'Start': [1000, 1003], + ... 'End': [1002, 1004] + ... } + >>> bf = pybed.BedFrame.from_dict([], data) + >>> bf.gr.df + Chromosome Start End + 0 chr1 1000 1002 + 1 chr1 1003 1004 + + We can mask rows that overlap with the BED data: + + >>> cf.mask_bed(bf).df.head() + Chromosome Position A B + 0 chr1 1000 NaN NaN + 1 chr1 1001 NaN NaN + 2 chr1 1002 41.0 22.0 + 3 chr1 1003 NaN NaN + 4 chr1 1004 34.0 23.0 + + We can also do the opposite: + + >>> cf.mask_bed(bf, opposite=True).df.head() + Chromosome Position A B + 0 chr1 1000 34.0 31.0 + 1 chr1 1001 31.0 20.0 + 2 chr1 1002 NaN NaN + 3 chr1 1003 28.0 41.0 + 4 chr1 1004 NaN NaN + """""" + if isinstance(bed, pybed.BedFrame): + bf = bed + else: + bf = pybed.BedFrame.from_file(bed) + def one_row(r): + if opposite: + if bf.gr[r.Chromosome, r.Position:r.Position+1].empty: + r[2:] = r[2:].apply(lambda x: np.nan) + else: + if not bf.gr[r.Chromosome, r.Position:r.Position+1].empty: + r[2:] = r[2:].apply(lambda x: np.nan) + return r + df = self.df.apply(one_row, axis=1) + return self.__class__(df) + + def update_chr_prefix(self, mode='remove'): + """""" + Add or remove the (annoying) 'chr' string from the Chromosome column. + + Parameters + ---------- + mode : {'add', 'remove'}, default: 'remove' + Whether to add or remove the 'chr' string. + + Returns + ------- + CovFrame + Updated CovFrame. + + Examples + -------- + + >>> import numpy as np + >>> from fuc import pycov + >>> data = { + ... 'Chromosome': ['chr1'] * 3 + ['2'] * 3, + ... 'Position': np.arange(1, 7), + ... 'A': pycov.simulate(loc=35, scale=5, size=6), + ... 'B': pycov.simulate(loc=25, scale=7, size=6), + ... } + >>> cf = pycov.CovFrame.from_dict(data) + >>> cf.df + Chromosome Position A B + 0 chr1 1 35 25 + 1 chr1 2 23 14 + 2 chr1 3 32 23 + 3 2 4 38 25 + 4 2 5 33 8 + 5 2 6 21 22 + >>> cf.update_chr_prefix(mode='remove').df + Chromosome Position A B + 0 1 1 35 25 + 1 1 2 23 14 + 2 1 3 32 23 + 3 2 4 38 25 + 4 2 5 33 8 + 5 2 6 21 22 + >>> cf.update_chr_prefix(mode='add').df + Chromosome Position A B + 0 chr1 1 35 25 + 1 chr1 2 23 14 + 2 chr1 3 32 23 + 3 chr2 4 38 25 + 4 chr2 5 33 8 + 5 chr2 6 21 22 + """""" + if mode == 'remove': + def one_row(r): + r.Chromosome = r.Chromosome.replace('chr', '') + return r + elif mode == 'add': + def one_row(r): + if 'chr' not in r.Chromosome: + r.Chromosome = 'chr' + r.Chromosome + return r + else: + raise ValueError(f'Incorrect mode: {mode}') + df = self.df.apply(one_row, axis=1) + return self.__class__(df) + + def subset(self, samples, exclude=False): + """""" + Subset CovFrame for specified samples. + + Parameters + ---------- + samples : str or list + Sample name or list of names (the order matters). + exclude : bool, default: False + If True, exclude specified samples. + + Returns + ------- + CovFrame + Subsetted CovFrame. + + Examples + -------- + Assume we have the following data: + + >>> import numpy as np + >>> from fuc import pycov + >>> data = { + ... 'Chromosome': ['chr1'] * 1000, + ... 'Position': np.arange(1000, 2000), + ... 'A': pycov.simulate(loc=35, scale=5), + ... 'B': pycov.simulate(loc=25, scale=7), + ... 'C': pycov.simulate(loc=15, scale=2), + ... 'D': pycov.simulate(loc=45, scale=8), + ... } + >>> cf = pycov.CovFrame.from_dict(data) + >>> cf.df.head() + Chromosome Position A B C D + 0 chr1 1000 30 30 15 37 + 1 chr1 1001 25 24 11 43 + 2 chr1 1002 33 24 16 50 + 3 chr1 1003 29 22 15 46 + 4 chr1 1004 34 30 11 32 + + We can subset the CovFrame for the samples A and B: + + >>> cf.subset(['A', 'B']).df.head() + Chromosome Position A B + 0 chr1 1000 30 30 + 1 chr1 1001 25 24 + 2 chr1 1002 33 24 + 3 chr1 1003 29 22 + 4 chr1 1004 34 30 + + Alternatively, we can exclude those samples: + + >>> cf.subset(['A', 'B'], exclude=True).df.head() + Chromosome Position C D + 0 chr1 1000 15 37 + 1 chr1 1001 11 43 + 2 chr1 1002 16 50 + 3 chr1 1003 15 46 + 4 chr1 1004 11 32 + """""" + if isinstance(samples, str): + samples = [samples] + if exclude: + samples = [x for x in self.samples if x not in samples] + cols = self.df.columns[:2].to_list() + samples + return self.__class__(self.df[cols]) + + def rename(self, names, indicies=None): + """""" + Rename the samples. + + Parameters + ---------- + names : dict or list + Dict of old names to new names or list of new names. + indicies : list or tuple, optional + List of 0-based sample indicies. Alternatively, a tuple + (int, int) can be used to specify an index range. + + Returns + ------- + CovFrame + Updated CovFrame. + + Examples + -------- + + >>> import numpy as np + >>> from fuc import pycov + >>> data = { + ... 'Chromosome': ['chr1'] * 2, + ... 'Position': np.arange(1, 3), + ... 'A': pycov.simulate(loc=35, scale=5, size=2), + ... 'B': pycov.simulate(loc=25, scale=7, size=2), + ... 'C': pycov.simulate(loc=25, scale=7, size=2), + ... 'D': pycov.simulate(loc=25, scale=7, size=2), + ... } + >>> cf = pycov.CovFrame.from_dict(data) + >>> cf.df + Chromosome Position A B C D + 0 chr1 1 31 19 28 15 + 1 chr1 2 35 24 22 17 + >>> cf.rename(['1', '2', '3', '4']).df + Chromosome Position 1 2 3 4 + 0 chr1 1 31 19 28 15 + 1 chr1 2 35 24 22 17 + >>> cf.rename({'B': '2', 'C': '3'}).df + Chromosome Position A 2 3 D + 0 chr1 1 31 19 28 15 + 1 chr1 2 35 24 22 17 + >>> cf.rename(['2', '4'], indicies=[1, 3]).df + Chromosome Position A 2 C 4 + 0 chr1 1 31 19 28 15 + 1 chr1 2 35 24 22 17 + >>> cf.rename(['2', '3'], indicies=(1, 3)).df + Chromosome Position A 2 3 D + 0 chr1 1 31 19 28 15 + 1 chr1 2 35 24 22 17 + """""" + samples = common.rename(self.samples, names, indicies=indicies) + columns = self.df.columns[:2].to_list() + samples + cf = self.copy() + cf.df.columns = columns + return cf + + def merge( + self, other, how='inner' + ): + """""" + Merge with the other CovFrame. + + Parameters + ---------- + other : CovFrame + Other CovFrame. Note that the 'chr' prefix in contig names (e.g. + 'chr1' vs. '1') will be automatically added or removed as + necessary to match the contig names of ``self``. + how : str, default: 'inner' + Type of merge as defined in :meth:`pandas.DataFrame.merge`. + + Returns + ------- + CovFrame + Merged CovFrame. + + See Also + -------- + merge + Merge multiple CovFrame objects. + + Examples + -------- + Assume we have the following data: + + >>> import numpy as np + >>> from fuc import pycov + >>> data1 = { + ... 'Chromosome': ['chr1'] * 5, + ... 'Position': np.arange(100, 105), + ... 'A': pycov.simulate(loc=35, scale=5, size=5), + ... 'B': pycov.simulate(loc=25, scale=7, size=5), + ... } + >>> data2 = { + ... 'Chromosome': ['1'] * 5, + ... 'Position': np.arange(102, 107), + ... 'C': pycov.simulate(loc=35, scale=5, size=5), + ... } + >>> cf1 = pycov.CovFrame.from_dict(data1) + >>> cf2 = pycov.CovFrame.from_dict(data2) + >>> cf1.df + Chromosome Position A B + 0 chr1 100 40 27 + 1 chr1 101 32 33 + 2 chr1 102 32 22 + 3 chr1 103 32 29 + 4 chr1 104 37 22 + >>> cf2.df + Chromosome Position C + 0 1 102 33 + 1 1 103 29 + 2 1 104 35 + 3 1 105 27 + 4 1 106 25 + + We can merge the two VcfFrames with `how='inner'` (default): + + >>> cf1.merge(cf2).df + Chromosome Position A B C + 0 chr1 102 32 22 33 + 1 chr1 103 32 29 29 + 2 chr1 104 37 22 35 + + We can also merge with `how='outer'`: + + >>> cf1.merge(cf2, how='outer').df + Chromosome Position A B C + 0 chr1 100 40.0 27.0 NaN + 1 chr1 101 32.0 33.0 NaN + 2 chr1 102 32.0 22.0 33.0 + 3 chr1 103 32.0 29.0 29.0 + 4 chr1 104 37.0 22.0 35.0 + 5 chr1 105 NaN NaN 27.0 + 6 chr1 106 NaN NaN 25.0 + """""" + if self.has_chr_prefix and other.has_chr_prefix: + pass + elif self.has_chr_prefix and not other.has_chr_prefix: + other = other.update_chr_prefix('add') + elif not self.has_chr_prefix and other.has_chr_prefix: + other = other.update_chr_prefix('remove') + else: + pass + + df = self.df.merge(other.df, on=['Chromosome', 'Position'], how=how) + + merged = self.__class__(df) + + return merged +","Python" +"Pharmacogenetics","sbslee/fuc","fuc/api/pyvep.py",".py","44507","528",""""""" +The pyvep submodule is designed for parsing VCF annotation data from the +`Ensembl VEP `_ +program. It should be used with ``pyvcf.VcfFrame``. + +The input VCF should already contain functional annotation data from +Ensembl VEP. The recommended method is Ensembl VEP's +`web interface `_ with +“RefSeq transcripts” as the transcript database and the filtering option +“Show one selected consequence per variant”. + +A typical VEP-annotated VCF file contains many fields ranging from gene +symbol to protein change. However, most of the analysis in pyvep uses the +following fields: + ++-----+--------------------+---------------------+----------------------------------------------------------------------------------------------------------+ +| No. | Name | Description | Examples | ++=====+====================+=====================+==========================================================================================================+ +| 1 | Allele | Variant allele | 'C', 'T', 'CG' | ++-----+--------------------+---------------------+----------------------------------------------------------------------------------------------------------+ +| 2 | Consequence | Consequence type | 'missense_variant', 'stop_gained' | ++-----+--------------------+---------------------+----------------------------------------------------------------------------------------------------------+ +| 3 | IMPACT | Consequence impact | 'MODERATE', 'HIGH' | ++-----+--------------------+---------------------+----------------------------------------------------------------------------------------------------------+ +| 4 | SYMBOL | Gene symbol | 'TP53', 'APC' | ++-----+--------------------+---------------------+----------------------------------------------------------------------------------------------------------+ +| 5 | Gene | Ensembl ID | 7157, 55294 | ++-----+--------------------+---------------------+----------------------------------------------------------------------------------------------------------+ +| 6 | BIOTYPE | Transcript biotype | 'protein_coding', 'pseudogene', 'miRNA' | ++-----+--------------------+---------------------+----------------------------------------------------------------------------------------------------------+ +| 7 | EXON | Exon number | '8/17', '17/17' | ++-----+--------------------+---------------------+----------------------------------------------------------------------------------------------------------+ +| 8 | Protein_position | Amino acid position | 234, 1510 | ++-----+--------------------+---------------------+----------------------------------------------------------------------------------------------------------+ +| 9 | Amino_acids | Amino acid changes | 'R/\*', 'A/X', 'V/A' | ++-----+--------------------+---------------------+----------------------------------------------------------------------------------------------------------+ +| 10 | Existing_variation | Variant identifier | 'rs17851045', 'rs786201856&COSV57325157' | ++-----+--------------------+---------------------+----------------------------------------------------------------------------------------------------------+ +| 11 | STRAND | Genomic strand | 1, -1 | ++-----+--------------------+---------------------+----------------------------------------------------------------------------------------------------------+ +| 12 | SIFT | SIFT prediction | 'tolerated(0.6)', 'tolerated_low_confidence(0.37)', 'deleterious_low_confidence(0.03)', 'deleterious(0)' | ++-----+--------------------+---------------------+----------------------------------------------------------------------------------------------------------+ +| 13 | PolyPhen | PolyPhen prediction | 'benign(0.121)', 'possibly_damaging(0.459)', 'probably_damaging(0.999)' | ++-----+--------------------+---------------------+----------------------------------------------------------------------------------------------------------+ +| 14 | CLIN_SIG | ClinVar prediction | 'pathogenic', 'likely_pathogenic&pathogenic' | ++-----+--------------------+---------------------+----------------------------------------------------------------------------------------------------------+ +"""""" + +import re +import pandas as pd +import numpy as np +from . import pyvcf + +# https://m.ensembl.org/info/docs/tools/vep/vep_formats.html + +DATA_TYPES = { + 'Allele': 'str', + 'Consequence': 'str', + 'IMPACT': 'str', + 'SYMBOL': 'str', + 'Gene': 'str', + 'Feature_type': 'str', + 'Feature': 'str', + 'BIOTYPE': 'str', + 'EXON': 'str', + 'INTRON': 'str', + 'HGVSc': 'str', + 'HGVSp': 'str', + 'cDNA_position': 'str', + 'CDS_position': 'str', + 'Protein_position': 'str', + 'Amino_acids': 'str', + 'Codons': 'str', + 'Existing_variation': 'str', + 'DISTANCE': 'str', + 'STRAND': 'str', + 'FLAGS': 'str', + 'SYMBOL_SOURCE': 'str', + 'HGNC_ID': 'str', + 'MANE_SELECT': 'str', + 'MANE_PLUS_CLINICAL': 'str', + 'TSL': 'str', + 'APPRIS': 'str', + 'REFSEQ_MATCH': 'str', + 'REFSEQ_OFFSET': 'str', + 'GIVEN_REF': 'str', + 'USED_REF': 'str', + 'BAM_EDIT': 'str', + 'SIFT': 'str', + 'PolyPhen': 'str', + 'AF': 'float64', + 'AFR_AF': 'float64', + 'AMR_AF': 'float64', + 'EAS_AF': 'float64', + 'EUR_AF': 'float64', + 'SAS_AF': 'float64', + 'AA_AF': 'float64', + 'EA_AF': 'float64', + 'gnomAD_AF': 'float64', + 'gnomAD_AFR_AF': 'float64', + 'gnomAD_AMR_AF': 'float64', + 'gnomAD_ASJ_AF': 'float64', + 'gnomAD_EAS_AF': 'float64', + 'gnomAD_FIN_AF': 'float64', + 'gnomAD_NFE_AF': 'float64', + 'gnomAD_OTH_AF': 'float64', + 'gnomAD_SAS_AF': 'float64', + 'CLIN_SIG': 'str', + 'SOMATIC': 'str', + 'PHENO': 'str', + 'PUBMED': 'str', + 'MOTIF_NAME': 'str', + 'MOTIF_POS': 'str', + 'HIGH_INF_POS': 'str', + 'MOTIF_SCORE_CHANGE': 'str', + 'TRANSCRIPTION_FACTORS': 'str', +} + +SEVERITIY = [ + 'transcript_ablation', + 'splice_acceptor_variant', + 'splice_donor_variant', + 'stop_gained', + 'frameshift_variant', + 'stop_lost', + 'start_lost', + 'transcript_amplification', + 'inframe_insertion', + 'inframe_deletion', + 'missense_variant', + 'protein_altering_variant', + 'splice_region_variant', + 'incomplete_terminal_codon_variant', + 'start_retained_variant', + 'stop_retained_variant', + 'synonymous_variant', + 'coding_sequence_variant', + 'mature_miRNA_variant', + '5_prime_UTR_variant', + '3_prime_UTR_variant', + 'non_coding_transcript_exon_variant', + 'intron_variant', + 'NMD_transcript_variant', + 'non_coding_transcript_variant', + 'upstream_gene_variant', + 'downstream_gene_variant', + 'TFBS_ablation', + 'TFBS_amplification', + 'TF_binding_site_variant', + 'regulatory_region_ablation', + 'regulatory_region_amplification', + 'feature_elongation', + 'regulatory_region_variant', + 'feature_truncation', + 'intergenic_variant' +] + +def row_firstann(r): + """""" + Return the first result in the row. + + Parameters + ---------- + r : pandas.Series + VCF row. + + Returns + ------- + str + Annotation result. Empty string if annotation is not found. + + See Also + -------- + row_mostsevere + Similar method that returns result with the most severe + consequence in the row. + + Examples + -------- + + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr2', 'chr2'], + ... 'POS': [100, 101, 200, 201], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['G', 'C', 'G', 'CCCA'], + ... 'ALT': ['C', 'T', 'A', 'C'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': [ + ... 'CSQ=C|downstream_gene_variant|MODIFIER|ZBTB17|ENSG00000116809|Transcript|ENST00000375733.2|protein_coding|||||||||||4617|-1||HGNC|12936||||||||||||||||,C|downstream_gene_variant|MODIFIER|ZBTB17|ENSG00000116809|Transcript|ENST00000375743.4|protein_coding|||||||||||4615|-1||HGNC|12936||||||||||||||||,C|missense_variant|MODERATE|SPEN|ENSG00000065526|Transcript|ENST00000375759.3|protein_coding|12/15||||10322|10118|3373|Q/P|cAg/cCg|||1||HGNC|17575|||||tolerated_low_confidence(0.08)|possibly_damaging(0.718)||||||||||,C|downstream_gene_variant|MODIFIER|ZBTB17|ENSG00000116809|Transcript|ENST00000440560.1|protein_coding|||||||||||4615|-1|cds_start_NF|HGNC|12936||||||||||||||||,C|downstream_gene_variant|MODIFIER|ZBTB17|ENSG00000116809|Transcript|ENST00000462525.1|processed_transcript|||||||||||4615|-1||HGNC|12936||||||||||||||||,C|upstream_gene_variant|MODIFIER|SPEN|ENSG00000065526|Transcript|ENST00000487496.1|processed_transcript|||||||||||1329|1||HGNC|17575||||||||||||||||,C|downstream_gene_variant|MODIFIER|ZBTB17|ENSG00000116809|Transcript|ENST00000537142.1|protein_coding|||||||||||4617|-1||HGNC|12936||||||||||||||||,C|regulatory_region_variant|MODIFIER|||RegulatoryFeature|ENSR00000922256|promoter_flanking_region|||||||||||||||||||||||||||||||', + ... 'CSQ=T|downstream_gene_variant|MODIFIER|CSDE1|ENSG00000009307|Transcript|ENST00000261443.5|protein_coding||||||||||COSV99795232|3453|-1||HGNC|29905|||||||||1|1||||||,T|downstream_gene_variant|MODIFIER|CSDE1|ENSG00000009307|Transcript|ENST00000339438.6|protein_coding||||||||||COSV99795232|3071|-1||HGNC|29905|||||||||1|1||||||,T|downstream_gene_variant|MODIFIER|CSDE1|ENSG00000009307|Transcript|ENST00000358528.4|protein_coding||||||||||COSV99795232|3075|-1||HGNC|29905|||||||||1|1||||||,T|downstream_gene_variant|MODIFIER|CSDE1|ENSG00000009307|Transcript|ENST00000369530.1|protein_coding||||||||||COSV99795232|3470|-1||HGNC|29905|||||||||1|1||||||,T|missense_variant|MODERATE|NRAS|ENSG00000213281|Transcript|ENST00000369535.4|protein_coding|3/7||||502|248|83|A/D|gCc/gAc|COSV99795232||-1||HGNC|7989|||||deleterious(0.02)|probably_damaging(0.946)|||1|1||||||,T|downstream_gene_variant|MODIFIER|CSDE1|ENSG00000009307|Transcript|ENST00000438362.2|protein_coding||||||||||COSV99795232|3074|-1||HGNC|29905|||||||||1|1||||||,T|downstream_gene_variant|MODIFIER|CSDE1|ENSG00000009307|Transcript|ENST00000483407.1|processed_transcript||||||||||COSV99795232|3960|-1||HGNC|29905|||||||||1|1||||||,T|downstream_gene_variant|MODIFIER|CSDE1|ENSG00000009307|Transcript|ENST00000530886.1|protein_coding||||||||||COSV99795232|3463|-1||HGNC|29905|||||||||1|1||||||,T|downstream_gene_variant|MODIFIER|CSDE1|ENSG00000009307|Transcript|ENST00000534699.1|protein_coding||||||||||COSV99795232|4115|-1||HGNC|29905|||||||||1|1||||||', + ... 'CSQ=A|missense_variant|MODERATE|NTRK1|ENSG00000198400|Transcript|ENST00000358660.3|protein_coding|10/16||||1296|1255|419|A/T|Gcc/Acc|COSV62328771||1||HGNC|8031|||||deleterious(0.01)|probably_damaging(0.999)|||1|1||||||,A|missense_variant|MODERATE|NTRK1|ENSG00000198400|Transcript|ENST00000368196.3|protein_coding|10/16||||1375|1255|419|A/T|Gcc/Acc|COSV62328771||1||HGNC|8031|||||deleterious(0.01)|possibly_damaging(0.894)|||1|1||||||,A|missense_variant|MODERATE|NTRK1|ENSG00000198400|Transcript|ENST00000392302.2|protein_coding|11/17||||1339|1165|389|A/T|Gcc/Acc|COSV62328771||1||HGNC|8031|||||deleterious(0.01)|probably_damaging(0.983)|||1|1||||||,A|downstream_gene_variant|MODIFIER|NTRK1|ENSG00000198400|Transcript|ENST00000489021.2|processed_transcript||||||||||COSV62328771|1037|1||HGNC|8031|||||||||1|1||||||,A|stop_gained&NMD_transcript_variant|HIGH|NTRK1|ENSG00000198400|Transcript|ENST00000497019.2|nonsense_mediated_decay|10/16||||1183|1032|344|W/*|tgG/tgA|COSV62328771||1||HGNC|8031|||||||||1|1||||||,A|missense_variant|MODERATE|NTRK1|ENSG00000198400|Transcript|ENST00000524377.1|protein_coding|11/17||||1314|1273|425|A/T|Gcc/Acc|COSV62328771||1||HGNC|8031|||||deleterious(0.01)|probably_damaging(0.996)|||1|1||||||,A|non_coding_transcript_exon_variant|MODIFIER|NTRK1|ENSG00000198400|Transcript|ENST00000530298.1|retained_intron|12/17||||1313|||||COSV62328771||1||HGNC|8031|||||||||1|1||||||,A|non_coding_transcript_exon_variant|MODIFIER|NTRK1|ENSG00000198400|Transcript|ENST00000534682.1|retained_intron|2/4||||496|||||COSV62328771||1||HGNC|8031|||||||||1|1||||||,A|regulatory_region_variant|MODIFIER|||RegulatoryFeature|ENSR00001787924|open_chromatin_region||||||||||COSV62328771||||||||||||||1|1||||||', + ... 'CSQ=-|upstream_gene_variant|MODIFIER|LRRC56|ENSG00000161328|Transcript|ENST00000270115.7|protein_coding||||||||||rs1164486792|3230|1||HGNC|25430||||||||||1||||||,-|inframe_deletion|MODERATE|HRAS|ENSG00000174775|Transcript|ENST00000311189.7|protein_coding|2/6||||198-200|26-28|9-10|VG/G|gTGGgc/ggc|rs1164486792||-1||HGNC|5173||||||||||1||||||,-|inframe_deletion|MODERATE|HRAS|ENSG00000174775|Transcript|ENST00000397594.1|protein_coding|1/5||||79-81|26-28|9-10|VG/G|gTGGgc/ggc|rs1164486792||-1||HGNC|5173||||||||||1||||||,-|inframe_deletion|MODERATE|HRAS|ENSG00000174775|Transcript|ENST00000397596.2|protein_coding|2/5||||162-164|26-28|9-10|VG/G|gTGGgc/ggc|rs1164486792||-1||HGNC|5173||||||||||1||||||,-|inframe_deletion|MODERATE|HRAS|ENSG00000174775|Transcript|ENST00000417302.1|protein_coding|2/6||||214-216|26-28|9-10|VG/G|gTGGgc/ggc|rs1164486792||-1||HGNC|5173||||||||||1||||||,-|inframe_deletion|MODERATE|HRAS|ENSG00000174775|Transcript|ENST00000451590.1|protein_coding|2/5||||214-216|26-28|9-10|VG/G|gTGGgc/ggc|rs1164486792||-1||HGNC|5173||||||||||1||||||,-|upstream_gene_variant|MODIFIER|HRAS|ENSG00000174775|Transcript|ENST00000462734.1|processed_transcript||||||||||rs1164486792|700|-1||HGNC|5173||||||||||1||||||,-|non_coding_transcript_exon_variant|MODIFIER|HRAS|ENSG00000174775|Transcript|ENST00000468682.2|processed_transcript|2/3||||514-516|||||rs1164486792||-1||HGNC|5173||||||||||1||||||,-|upstream_gene_variant|MODIFIER|HRAS|ENSG00000174775|Transcript|ENST00000478324.1|processed_transcript||||||||||rs1164486792|683|-1||HGNC|5173||||||||||1||||||,-|upstream_gene_variant|MODIFIER|HRAS|ENSG00000174775|Transcript|ENST00000479482.1|processed_transcript||||||||||rs1164486792|319|-1||HGNC|5173||||||||||1||||||,-|non_coding_transcript_exon_variant|MODIFIER|HRAS|ENSG00000174775|Transcript|ENST00000482021.1|processed_transcript|2/2||||149-151|||||rs1164486792||-1||HGNC|5173||||||||||1||||||,-|inframe_deletion&NMD_transcript_variant|MODERATE|HRAS|ENSG00000174775|Transcript|ENST00000493230.1|nonsense_mediated_decay|2/7||||202-204|26-28|9-10|VG/G|gTGGgc/ggc|rs1164486792||-1||HGNC|5173||||||||||1||||||,-|downstream_gene_variant|MODIFIER|RP13-46H24.1|ENSG00000254739|Transcript|ENST00000526431.1|antisense||||||||||rs1164486792|4636|1||Clone_based_vega_gene|||||||||||1||||||,-|regulatory_region_variant|MODIFIER|||RegulatoryFeature|ENSR00000035647|promoter||||||||||rs1164486792|||||||||||||||1||||||' + ... ], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT'], + ... 'Steven': ['0/1', '0/1', '0/1', '0/1'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict(meta, data) + >>> vf.df.apply(pyvep.row_firstann, axis=1) + 0 C|downstream_gene_variant|MODIFIER|ZBTB17|ENSG... + 1 T|downstream_gene_variant|MODIFIER|CSDE1|ENSG0... + 2 A|missense_variant|MODERATE|NTRK1|ENSG00000198... + 3 -|upstream_gene_variant|MODIFIER|LRRC56|ENSG00... + dtype: object + """""" + results = pyvcf.row_parseinfo(r, 'CSQ') + if not results: + return '' + return results.split(',')[0] + +def row_mostsevere(r): + """""" + Return result with the most severe consequence in the row. + + Parameters + ---------- + r : pandas.Series + VCF row. + + Returns + ------- + str + Annotation result. Empty string if annotation is not found. + + See Also + -------- + row_firstann + Similar method that returns the first result in the row. + + Examples + -------- + + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr2', 'chr2'], + ... 'POS': [100, 101, 200, 201], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['G', 'C', 'G', 'CCCA'], + ... 'ALT': ['C', 'T', 'A', 'C'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': [ + ... 'CSQ=C|downstream_gene_variant|MODIFIER|ZBTB17|ENSG00000116809|Transcript|ENST00000375733.2|protein_coding|||||||||||4617|-1||HGNC|12936||||||||||||||||,C|downstream_gene_variant|MODIFIER|ZBTB17|ENSG00000116809|Transcript|ENST00000375743.4|protein_coding|||||||||||4615|-1||HGNC|12936||||||||||||||||,C|missense_variant|MODERATE|SPEN|ENSG00000065526|Transcript|ENST00000375759.3|protein_coding|12/15||||10322|10118|3373|Q/P|cAg/cCg|||1||HGNC|17575|||||tolerated_low_confidence(0.08)|possibly_damaging(0.718)||||||||||,C|downstream_gene_variant|MODIFIER|ZBTB17|ENSG00000116809|Transcript|ENST00000440560.1|protein_coding|||||||||||4615|-1|cds_start_NF|HGNC|12936||||||||||||||||,C|downstream_gene_variant|MODIFIER|ZBTB17|ENSG00000116809|Transcript|ENST00000462525.1|processed_transcript|||||||||||4615|-1||HGNC|12936||||||||||||||||,C|upstream_gene_variant|MODIFIER|SPEN|ENSG00000065526|Transcript|ENST00000487496.1|processed_transcript|||||||||||1329|1||HGNC|17575||||||||||||||||,C|downstream_gene_variant|MODIFIER|ZBTB17|ENSG00000116809|Transcript|ENST00000537142.1|protein_coding|||||||||||4617|-1||HGNC|12936||||||||||||||||,C|regulatory_region_variant|MODIFIER|||RegulatoryFeature|ENSR00000922256|promoter_flanking_region|||||||||||||||||||||||||||||||', + ... 'CSQ=T|downstream_gene_variant|MODIFIER|CSDE1|ENSG00000009307|Transcript|ENST00000261443.5|protein_coding||||||||||COSV99795232|3453|-1||HGNC|29905|||||||||1|1||||||,T|downstream_gene_variant|MODIFIER|CSDE1|ENSG00000009307|Transcript|ENST00000339438.6|protein_coding||||||||||COSV99795232|3071|-1||HGNC|29905|||||||||1|1||||||,T|downstream_gene_variant|MODIFIER|CSDE1|ENSG00000009307|Transcript|ENST00000358528.4|protein_coding||||||||||COSV99795232|3075|-1||HGNC|29905|||||||||1|1||||||,T|downstream_gene_variant|MODIFIER|CSDE1|ENSG00000009307|Transcript|ENST00000369530.1|protein_coding||||||||||COSV99795232|3470|-1||HGNC|29905|||||||||1|1||||||,T|missense_variant|MODERATE|NRAS|ENSG00000213281|Transcript|ENST00000369535.4|protein_coding|3/7||||502|248|83|A/D|gCc/gAc|COSV99795232||-1||HGNC|7989|||||deleterious(0.02)|probably_damaging(0.946)|||1|1||||||,T|downstream_gene_variant|MODIFIER|CSDE1|ENSG00000009307|Transcript|ENST00000438362.2|protein_coding||||||||||COSV99795232|3074|-1||HGNC|29905|||||||||1|1||||||,T|downstream_gene_variant|MODIFIER|CSDE1|ENSG00000009307|Transcript|ENST00000483407.1|processed_transcript||||||||||COSV99795232|3960|-1||HGNC|29905|||||||||1|1||||||,T|downstream_gene_variant|MODIFIER|CSDE1|ENSG00000009307|Transcript|ENST00000530886.1|protein_coding||||||||||COSV99795232|3463|-1||HGNC|29905|||||||||1|1||||||,T|downstream_gene_variant|MODIFIER|CSDE1|ENSG00000009307|Transcript|ENST00000534699.1|protein_coding||||||||||COSV99795232|4115|-1||HGNC|29905|||||||||1|1||||||', + ... 'CSQ=A|missense_variant|MODERATE|NTRK1|ENSG00000198400|Transcript|ENST00000358660.3|protein_coding|10/16||||1296|1255|419|A/T|Gcc/Acc|COSV62328771||1||HGNC|8031|||||deleterious(0.01)|probably_damaging(0.999)|||1|1||||||,A|missense_variant|MODERATE|NTRK1|ENSG00000198400|Transcript|ENST00000368196.3|protein_coding|10/16||||1375|1255|419|A/T|Gcc/Acc|COSV62328771||1||HGNC|8031|||||deleterious(0.01)|possibly_damaging(0.894)|||1|1||||||,A|missense_variant|MODERATE|NTRK1|ENSG00000198400|Transcript|ENST00000392302.2|protein_coding|11/17||||1339|1165|389|A/T|Gcc/Acc|COSV62328771||1||HGNC|8031|||||deleterious(0.01)|probably_damaging(0.983)|||1|1||||||,A|downstream_gene_variant|MODIFIER|NTRK1|ENSG00000198400|Transcript|ENST00000489021.2|processed_transcript||||||||||COSV62328771|1037|1||HGNC|8031|||||||||1|1||||||,A|stop_gained&NMD_transcript_variant|HIGH|NTRK1|ENSG00000198400|Transcript|ENST00000497019.2|nonsense_mediated_decay|10/16||||1183|1032|344|W/*|tgG/tgA|COSV62328771||1||HGNC|8031|||||||||1|1||||||,A|missense_variant|MODERATE|NTRK1|ENSG00000198400|Transcript|ENST00000524377.1|protein_coding|11/17||||1314|1273|425|A/T|Gcc/Acc|COSV62328771||1||HGNC|8031|||||deleterious(0.01)|probably_damaging(0.996)|||1|1||||||,A|non_coding_transcript_exon_variant|MODIFIER|NTRK1|ENSG00000198400|Transcript|ENST00000530298.1|retained_intron|12/17||||1313|||||COSV62328771||1||HGNC|8031|||||||||1|1||||||,A|non_coding_transcript_exon_variant|MODIFIER|NTRK1|ENSG00000198400|Transcript|ENST00000534682.1|retained_intron|2/4||||496|||||COSV62328771||1||HGNC|8031|||||||||1|1||||||,A|regulatory_region_variant|MODIFIER|||RegulatoryFeature|ENSR00001787924|open_chromatin_region||||||||||COSV62328771||||||||||||||1|1||||||', + ... 'CSQ=-|upstream_gene_variant|MODIFIER|LRRC56|ENSG00000161328|Transcript|ENST00000270115.7|protein_coding||||||||||rs1164486792|3230|1||HGNC|25430||||||||||1||||||,-|inframe_deletion|MODERATE|HRAS|ENSG00000174775|Transcript|ENST00000311189.7|protein_coding|2/6||||198-200|26-28|9-10|VG/G|gTGGgc/ggc|rs1164486792||-1||HGNC|5173||||||||||1||||||,-|inframe_deletion|MODERATE|HRAS|ENSG00000174775|Transcript|ENST00000397594.1|protein_coding|1/5||||79-81|26-28|9-10|VG/G|gTGGgc/ggc|rs1164486792||-1||HGNC|5173||||||||||1||||||,-|inframe_deletion|MODERATE|HRAS|ENSG00000174775|Transcript|ENST00000397596.2|protein_coding|2/5||||162-164|26-28|9-10|VG/G|gTGGgc/ggc|rs1164486792||-1||HGNC|5173||||||||||1||||||,-|inframe_deletion|MODERATE|HRAS|ENSG00000174775|Transcript|ENST00000417302.1|protein_coding|2/6||||214-216|26-28|9-10|VG/G|gTGGgc/ggc|rs1164486792||-1||HGNC|5173||||||||||1||||||,-|inframe_deletion|MODERATE|HRAS|ENSG00000174775|Transcript|ENST00000451590.1|protein_coding|2/5||||214-216|26-28|9-10|VG/G|gTGGgc/ggc|rs1164486792||-1||HGNC|5173||||||||||1||||||,-|upstream_gene_variant|MODIFIER|HRAS|ENSG00000174775|Transcript|ENST00000462734.1|processed_transcript||||||||||rs1164486792|700|-1||HGNC|5173||||||||||1||||||,-|non_coding_transcript_exon_variant|MODIFIER|HRAS|ENSG00000174775|Transcript|ENST00000468682.2|processed_transcript|2/3||||514-516|||||rs1164486792||-1||HGNC|5173||||||||||1||||||,-|upstream_gene_variant|MODIFIER|HRAS|ENSG00000174775|Transcript|ENST00000478324.1|processed_transcript||||||||||rs1164486792|683|-1||HGNC|5173||||||||||1||||||,-|upstream_gene_variant|MODIFIER|HRAS|ENSG00000174775|Transcript|ENST00000479482.1|processed_transcript||||||||||rs1164486792|319|-1||HGNC|5173||||||||||1||||||,-|non_coding_transcript_exon_variant|MODIFIER|HRAS|ENSG00000174775|Transcript|ENST00000482021.1|processed_transcript|2/2||||149-151|||||rs1164486792||-1||HGNC|5173||||||||||1||||||,-|inframe_deletion&NMD_transcript_variant|MODERATE|HRAS|ENSG00000174775|Transcript|ENST00000493230.1|nonsense_mediated_decay|2/7||||202-204|26-28|9-10|VG/G|gTGGgc/ggc|rs1164486792||-1||HGNC|5173||||||||||1||||||,-|downstream_gene_variant|MODIFIER|RP13-46H24.1|ENSG00000254739|Transcript|ENST00000526431.1|antisense||||||||||rs1164486792|4636|1||Clone_based_vega_gene|||||||||||1||||||,-|regulatory_region_variant|MODIFIER|||RegulatoryFeature|ENSR00000035647|promoter||||||||||rs1164486792|||||||||||||||1||||||' + ... ], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT'], + ... 'Steven': ['0/1', '0/1', '0/1', '0/1'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict(meta, data) + >>> vf.df.apply(pyvep.row_mostsevere, axis=1) + 0 C|missense_variant|MODERATE|SPEN|ENSG000000655... + 1 T|missense_variant|MODERATE|NRAS|ENSG000002132... + 2 A|stop_gained&NMD_transcript_variant|HIGH|NTRK... + 3 -|inframe_deletion|MODERATE|HRAS|ENSG000001747... + dtype: object + """""" + results = pyvcf.row_parseinfo(r, 'CSQ') + if not results: + return '' + f = lambda x: SEVERITIY.index(x.split('|')[1].split('&')[0]) + return sorted(results.split(','), key=f)[0] + +def parseann(vf, targets, sep=' | ', as_series=False): + """""" + Parse variant annotations in VcfFrame. + + If there are multiple results per row, the method will use the first + one for extracting requested data. + + Parameters + ---------- + vf : VcfFrame + VcfFrame. + targets : list + List of subfield IDs or indicies or both. + sep : str, default: ' | ' + Separator for joining requested annotations. + as_series : bool, default: False + If True, return 1D array instead of VcfFrame. + + Returns + ------- + VcfFrame or pandas.Series + Parsed annotations in VcfFrame or 1D array. + + Examples + -------- + Assume we have the following data: + + >>> meta = [ + ... '##fileformat=VCFv4.1', + ... '##VEP=""v104"" time=""2021-05-20 10:50:12"" cache=""/net/isilonP/public/ro/ensweb-data/latest/tools/grch37/e104/vep/cache/homo_sapiens/104_GRCh37"" db=""homo_sapiens_core_104_37@hh-mysql-ens-grch37-web"" 1000genomes=""phase3"" COSMIC=""92"" ClinVar=""202012"" HGMD-PUBLIC=""20204"" assembly=""GRCh37.p13"" dbSNP=""154"" gencode=""GENCODE 19"" genebuild=""2011-04"" gnomAD=""r2.1"" polyphen=""2.2.2"" regbuild=""1.0"" sift=""sift5.2.2""', + ... '##INFO=' + ... ] + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr2', 'chr2'], + ... 'POS': [100, 101, 200, 201], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['G', 'C', 'CAG', 'C'], + ... 'ALT': ['T', 'T', 'C', 'T'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': [ + ... 'CSQ=T|missense_variant|MODERATE|MTOR|ENSG00000198793|Transcript|ENST00000361445.4|protein_coding|47/58||||6721|6644|2215|S/Y|tCt/tAt|rs587777894&COSV63868278&COSV63868313||-1||HGNC|3942|||||deleterious(0)|possibly_damaging(0.876)||likely_pathogenic&pathogenic|0&1&1|1&1&1|26619011&27159400&24631838&26018084&27830187|||||', + ... 'CSQ=T|synonymous_variant|LOW|MTOR|ENSG00000198793|Transcript|ENST00000361445.4|protein_coding|49/58||||6986|6909|2303|L|ctG/ctA|rs11121691&COSV63870864||-1||HGNC|3942|||||||0.2206|benign|0&1|1&1|24996771|||||', + ... 'CSQ=-|frameshift_variant|HIGH|BRCA2|ENSG00000139618|Transcript|ENST00000380152.3|protein_coding|18/27||||8479-8480|8246-8247|2749|Q/X|cAG/c|rs80359701||1||HGNC|1101||||||||pathogenic||1|26467025&26295337&15340362|||||', + ... 'CSQ=T|missense_variant|MODERATE|MTOR|ENSG00000198793|Transcript|ENST00000361445.4|protein_coding|30/58||||4516|4439|1480|R/H|cGc/cAc|rs780930764&COSV63868373||-1||HGNC|3942|||||tolerated(0.13)|benign(0)||likely_benign|0&1|1&1||||||' + ... ], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT'], + ... 'Steven': ['0/1', '0/1', '0/1', '0/1'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict(meta, data) + + We can extract gene symbols: + + >>> pyvep.parseann(vf, ['SYMBOL']).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . G T . . MTOR GT 0/1 + 1 chr1 101 . C T . . MTOR GT 0/1 + 2 chr2 200 . CAG C . . BRCA2 GT 0/1 + 3 chr2 201 . C T . . MTOR GT 0/1 + + If we want to add variant impact: + + >>> pyvep.parseann(vf, ['SYMBOL', 'IMPACT']).df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . G T . . MTOR | MODERATE GT 0/1 + 1 chr1 101 . C T . . MTOR | LOW GT 0/1 + 2 chr2 200 . CAG C . . BRCA2 | HIGH GT 0/1 + 3 chr2 201 . C T . . MTOR | MODERATE GT 0/1 + + If we want to change the delimter: + + >>> pyvep.parseann(vf, ['SYMBOL', 'IMPACT'], sep=',').df + CHROM POS ID REF ALT QUAL FILTER INFO FORMAT Steven + 0 chr1 100 . G T . . MTOR,MODERATE GT 0/1 + 1 chr1 101 . C T . . MTOR,LOW GT 0/1 + 2 chr2 200 . CAG C . . BRCA2,HIGH GT 0/1 + 3 chr2 201 . C T . . MTOR,MODERATE GT 0/1 + + Finally, we can return a 1D array instead of VcfFrame: + + >>> pyvep.parseann(vf, ['SYMBOL'], as_series=True) + 0 MTOR + 1 MTOR + 2 BRCA2 + 3 MTOR + dtype: object + """""" + _targets = [x if isinstance(x, int) else annot_names(vf).index(x) for x in targets] + def func(r): + ann = row_firstann(r) + if not ann: + return '.' + ann = ann.split('|') + ann = sep.join([ann[i] for i in _targets]) + return ann + s = vf.df.apply(func, axis=1) + if as_series: + return s + new_vf = vf.copy() + new_vf.df.INFO = s + return new_vf + +def to_frame(vf, as_zero=False): + """""" + Create a DataFrame containing analysis-ready VEP annotation data. + + Parameters + ---------- + vf : VcfFrame + VcfFrame object. + as_zero : bool, default: False + If True, missing values will be converted to zeros instead of ``NaN``. + + Returns + ------- + pandas.DataFrame + DataFrame containing VEP annotation data. + """""" + f = lambda r: pd.Series(row_firstann(r).split('|')) + df = vf.df.apply(f, axis=1) + if as_zero: + df = df.replace('', 0) + else: + df = df.replace('', np.nan) + df.columns = annot_names(vf) + d = {} + for col in df.columns: + if col in DATA_TYPES: + d[col] = DATA_TYPES[col] + df = df.astype(d) + return df + +def pick_result(vf, mode='mostsevere'): + """""" + Return a new VcfFrame after picking one result per row. + + Parameters + ---------- + vf : VcfFrame + VcfFrame object. + mode : {'mostsevere', 'firstann'}, default: 'mostsevere' + Selection mode: + + - mostsevere: use ``row_mostsevere`` method + - firstann: use ``row_firstann`` method + + Returns + ------- + VcfFrame + New VcfFrame. + + Examples + -------- + + >>> from fuc import pyvep, pyvcf + >>> meta = [ + ... '##fileformat=VCFv4.1', + ... '##VEP=""v104"" time=""2021-05-20 10:50:12"" cache=""/net/isilonP/public/ro/ensweb-data/latest/tools/grch37/e104/vep/cache/homo_sapiens/104_GRCh37"" db=""homo_sapiens_core_104_37@hh-mysql-ens-grch37-web"" 1000genomes=""phase3"" COSMIC=""92"" ClinVar=""202012"" HGMD-PUBLIC=""20204"" assembly=""GRCh37.p13"" dbSNP=""154"" gencode=""GENCODE 19"" genebuild=""2011-04"" gnomAD=""r2.1"" polyphen=""2.2.2"" regbuild=""1.0"" sift=""sift5.2.2""', + ... '##INFO=' + ... ] + >>> data = { + ... 'CHROM': ['chr1', 'chr1', 'chr2', 'chr2'], + ... 'POS': [100, 101, 200, 201], + ... 'ID': ['.', '.', '.', '.'], + ... 'REF': ['G', 'C', 'G', 'CCCA'], + ... 'ALT': ['C', 'T', 'A', 'C'], + ... 'QUAL': ['.', '.', '.', '.'], + ... 'FILTER': ['.', '.', '.', '.'], + ... 'INFO': [ + ... 'CSQ=C|downstream_gene_variant|MODIFIER|ZBTB17|ENSG00000116809|Transcript|ENST00000375733.2|protein_coding|||||||||||4617|-1||HGNC|12936||||||||||||||||,C|downstream_gene_variant|MODIFIER|ZBTB17|ENSG00000116809|Transcript|ENST00000375743.4|protein_coding|||||||||||4615|-1||HGNC|12936||||||||||||||||,C|missense_variant|MODERATE|SPEN|ENSG00000065526|Transcript|ENST00000375759.3|protein_coding|12/15||||10322|10118|3373|Q/P|cAg/cCg|||1||HGNC|17575|||||tolerated_low_confidence(0.08)|possibly_damaging(0.718)||||||||||,C|downstream_gene_variant|MODIFIER|ZBTB17|ENSG00000116809|Transcript|ENST00000440560.1|protein_coding|||||||||||4615|-1|cds_start_NF|HGNC|12936||||||||||||||||,C|downstream_gene_variant|MODIFIER|ZBTB17|ENSG00000116809|Transcript|ENST00000462525.1|processed_transcript|||||||||||4615|-1||HGNC|12936||||||||||||||||,C|upstream_gene_variant|MODIFIER|SPEN|ENSG00000065526|Transcript|ENST00000487496.1|processed_transcript|||||||||||1329|1||HGNC|17575||||||||||||||||,C|downstream_gene_variant|MODIFIER|ZBTB17|ENSG00000116809|Transcript|ENST00000537142.1|protein_coding|||||||||||4617|-1||HGNC|12936||||||||||||||||,C|regulatory_region_variant|MODIFIER|||RegulatoryFeature|ENSR00000922256|promoter_flanking_region|||||||||||||||||||||||||||||||', + ... 'CSQ=T|downstream_gene_variant|MODIFIER|CSDE1|ENSG00000009307|Transcript|ENST00000261443.5|protein_coding||||||||||COSV99795232|3453|-1||HGNC|29905|||||||||1|1||||||,T|downstream_gene_variant|MODIFIER|CSDE1|ENSG00000009307|Transcript|ENST00000339438.6|protein_coding||||||||||COSV99795232|3071|-1||HGNC|29905|||||||||1|1||||||,T|downstream_gene_variant|MODIFIER|CSDE1|ENSG00000009307|Transcript|ENST00000358528.4|protein_coding||||||||||COSV99795232|3075|-1||HGNC|29905|||||||||1|1||||||,T|downstream_gene_variant|MODIFIER|CSDE1|ENSG00000009307|Transcript|ENST00000369530.1|protein_coding||||||||||COSV99795232|3470|-1||HGNC|29905|||||||||1|1||||||,T|missense_variant|MODERATE|NRAS|ENSG00000213281|Transcript|ENST00000369535.4|protein_coding|3/7||||502|248|83|A/D|gCc/gAc|COSV99795232||-1||HGNC|7989|||||deleterious(0.02)|probably_damaging(0.946)|||1|1||||||,T|downstream_gene_variant|MODIFIER|CSDE1|ENSG00000009307|Transcript|ENST00000438362.2|protein_coding||||||||||COSV99795232|3074|-1||HGNC|29905|||||||||1|1||||||,T|downstream_gene_variant|MODIFIER|CSDE1|ENSG00000009307|Transcript|ENST00000483407.1|processed_transcript||||||||||COSV99795232|3960|-1||HGNC|29905|||||||||1|1||||||,T|downstream_gene_variant|MODIFIER|CSDE1|ENSG00000009307|Transcript|ENST00000530886.1|protein_coding||||||||||COSV99795232|3463|-1||HGNC|29905|||||||||1|1||||||,T|downstream_gene_variant|MODIFIER|CSDE1|ENSG00000009307|Transcript|ENST00000534699.1|protein_coding||||||||||COSV99795232|4115|-1||HGNC|29905|||||||||1|1||||||', + ... 'CSQ=A|missense_variant|MODERATE|NTRK1|ENSG00000198400|Transcript|ENST00000358660.3|protein_coding|10/16||||1296|1255|419|A/T|Gcc/Acc|COSV62328771||1||HGNC|8031|||||deleterious(0.01)|probably_damaging(0.999)|||1|1||||||,A|missense_variant|MODERATE|NTRK1|ENSG00000198400|Transcript|ENST00000368196.3|protein_coding|10/16||||1375|1255|419|A/T|Gcc/Acc|COSV62328771||1||HGNC|8031|||||deleterious(0.01)|possibly_damaging(0.894)|||1|1||||||,A|missense_variant|MODERATE|NTRK1|ENSG00000198400|Transcript|ENST00000392302.2|protein_coding|11/17||||1339|1165|389|A/T|Gcc/Acc|COSV62328771||1||HGNC|8031|||||deleterious(0.01)|probably_damaging(0.983)|||1|1||||||,A|downstream_gene_variant|MODIFIER|NTRK1|ENSG00000198400|Transcript|ENST00000489021.2|processed_transcript||||||||||COSV62328771|1037|1||HGNC|8031|||||||||1|1||||||,A|stop_gained&NMD_transcript_variant|HIGH|NTRK1|ENSG00000198400|Transcript|ENST00000497019.2|nonsense_mediated_decay|10/16||||1183|1032|344|W/*|tgG/tgA|COSV62328771||1||HGNC|8031|||||||||1|1||||||,A|missense_variant|MODERATE|NTRK1|ENSG00000198400|Transcript|ENST00000524377.1|protein_coding|11/17||||1314|1273|425|A/T|Gcc/Acc|COSV62328771||1||HGNC|8031|||||deleterious(0.01)|probably_damaging(0.996)|||1|1||||||,A|non_coding_transcript_exon_variant|MODIFIER|NTRK1|ENSG00000198400|Transcript|ENST00000530298.1|retained_intron|12/17||||1313|||||COSV62328771||1||HGNC|8031|||||||||1|1||||||,A|non_coding_transcript_exon_variant|MODIFIER|NTRK1|ENSG00000198400|Transcript|ENST00000534682.1|retained_intron|2/4||||496|||||COSV62328771||1||HGNC|8031|||||||||1|1||||||,A|regulatory_region_variant|MODIFIER|||RegulatoryFeature|ENSR00001787924|open_chromatin_region||||||||||COSV62328771||||||||||||||1|1||||||', + ... 'CSQ=-|upstream_gene_variant|MODIFIER|LRRC56|ENSG00000161328|Transcript|ENST00000270115.7|protein_coding||||||||||rs1164486792|3230|1||HGNC|25430||||||||||1||||||,-|inframe_deletion|MODERATE|HRAS|ENSG00000174775|Transcript|ENST00000311189.7|protein_coding|2/6||||198-200|26-28|9-10|VG/G|gTGGgc/ggc|rs1164486792||-1||HGNC|5173||||||||||1||||||,-|inframe_deletion|MODERATE|HRAS|ENSG00000174775|Transcript|ENST00000397594.1|protein_coding|1/5||||79-81|26-28|9-10|VG/G|gTGGgc/ggc|rs1164486792||-1||HGNC|5173||||||||||1||||||,-|inframe_deletion|MODERATE|HRAS|ENSG00000174775|Transcript|ENST00000397596.2|protein_coding|2/5||||162-164|26-28|9-10|VG/G|gTGGgc/ggc|rs1164486792||-1||HGNC|5173||||||||||1||||||,-|inframe_deletion|MODERATE|HRAS|ENSG00000174775|Transcript|ENST00000417302.1|protein_coding|2/6||||214-216|26-28|9-10|VG/G|gTGGgc/ggc|rs1164486792||-1||HGNC|5173||||||||||1||||||,-|inframe_deletion|MODERATE|HRAS|ENSG00000174775|Transcript|ENST00000451590.1|protein_coding|2/5||||214-216|26-28|9-10|VG/G|gTGGgc/ggc|rs1164486792||-1||HGNC|5173||||||||||1||||||,-|upstream_gene_variant|MODIFIER|HRAS|ENSG00000174775|Transcript|ENST00000462734.1|processed_transcript||||||||||rs1164486792|700|-1||HGNC|5173||||||||||1||||||,-|non_coding_transcript_exon_variant|MODIFIER|HRAS|ENSG00000174775|Transcript|ENST00000468682.2|processed_transcript|2/3||||514-516|||||rs1164486792||-1||HGNC|5173||||||||||1||||||,-|upstream_gene_variant|MODIFIER|HRAS|ENSG00000174775|Transcript|ENST00000478324.1|processed_transcript||||||||||rs1164486792|683|-1||HGNC|5173||||||||||1||||||,-|upstream_gene_variant|MODIFIER|HRAS|ENSG00000174775|Transcript|ENST00000479482.1|processed_transcript||||||||||rs1164486792|319|-1||HGNC|5173||||||||||1||||||,-|non_coding_transcript_exon_variant|MODIFIER|HRAS|ENSG00000174775|Transcript|ENST00000482021.1|processed_transcript|2/2||||149-151|||||rs1164486792||-1||HGNC|5173||||||||||1||||||,-|inframe_deletion&NMD_transcript_variant|MODERATE|HRAS|ENSG00000174775|Transcript|ENST00000493230.1|nonsense_mediated_decay|2/7||||202-204|26-28|9-10|VG/G|gTGGgc/ggc|rs1164486792||-1||HGNC|5173||||||||||1||||||,-|downstream_gene_variant|MODIFIER|RP13-46H24.1|ENSG00000254739|Transcript|ENST00000526431.1|antisense||||||||||rs1164486792|4636|1||Clone_based_vega_gene|||||||||||1||||||,-|regulatory_region_variant|MODIFIER|||RegulatoryFeature|ENSR00000035647|promoter||||||||||rs1164486792|||||||||||||||1||||||' + ... ], + ... 'FORMAT': ['GT', 'GT', 'GT', 'GT'], + ... 'Steven': ['0/1', '0/1', '0/1', '0/1'], + ... } + >>> vf = pyvcf.VcfFrame.from_dict(meta, data) + >>> vf1 = pyvep.pick_result(vf, mode='mostsevere') + >>> vf2 = pyvep.pick_result(vf, mode='firstann') + >>> vf1.df.INFO + 0 CSQ=C|missense_variant|MODERATE|SPEN|ENSG00000065526|Transcript|ENST00000375759.3|protein_coding|12/15||||10322|10118|3373|Q/P|cAg/cCg|||1||HGNC|17575|||||tolerated_low_confidence(0.08)|possibly_damaging(0.718)|||||||||| + 1 CSQ=T|missense_variant|MODERATE|NRAS|ENSG00000213281|Transcript|ENST00000369535.4|protein_coding|3/7||||502|248|83|A/D|gCc/gAc|COSV99795232||-1||HGNC|7989|||||deleterious(0.02)|probably_damaging(0.946)|||1|1|||||| + 2 CSQ=A|stop_gained&NMD_transcript_variant|HIGH|NTRK1|ENSG00000198400|Transcript|ENST00000497019.2|nonsense_mediated_decay|10/16||||1183|1032|344|W/*|tgG/tgA|COSV62328771||1||HGNC|8031|||||||||1|1|||||| + 3 CSQ=-|inframe_deletion|MODERATE|HRAS|ENSG00000174775|Transcript|ENST00000311189.7|protein_coding|2/6||||198-200|26-28|9-10|VG/G|gTGGgc/ggc|rs1164486792||-1||HGNC|5173||||||||||1|||||| + Name: INFO, dtype: object + >>> vf2.df.INFO + 0 CSQ=C|downstream_gene_variant|MODIFIER|ZBTB17|ENSG00000116809|Transcript|ENST00000375733.2|protein_coding|||||||||||4617|-1||HGNC|12936|||||||||||||||| + 1 CSQ=T|downstream_gene_variant|MODIFIER|CSDE1|ENSG00000009307|Transcript|ENST00000261443.5|protein_coding||||||||||COSV99795232|3453|-1||HGNC|29905|||||||||1|1|||||| + 2 CSQ=A|missense_variant|MODERATE|NTRK1|ENSG00000198400|Transcript|ENST00000358660.3|protein_coding|10/16||||1296|1255|419|A/T|Gcc/Acc|COSV62328771||1||HGNC|8031|||||deleterious(0.01)|probably_damaging(0.999)|||1|1|||||| + 3 CSQ=-|upstream_gene_variant|MODIFIER|LRRC56|ENSG00000161328|Transcript|ENST00000270115.7|protein_coding||||||||||rs1164486792|3230|1||HGNC|25430||||||||||1|||||| + Name: INFO, dtype: object + """""" + funcs = {'mostsevere': row_mostsevere, 'firstann': row_firstann} + new_vf = vf.copy() + one_row = lambda r: pyvcf.row_updateinfo(r, 'CSQ', funcs[mode](r)) + new_vf.df.INFO = vf.df.apply(one_row, axis=1) + return new_vf + +def annot_names(vf): + """""" + Return the list of avaialble consequence annotations in the VcfFrame. + + Parameters + ---------- + vf : VcfFrame + VcfFrame. + + Returns + ------- + list + List of consequence annotations. + """""" + l = [] + for i, line in enumerate(vf.meta): + if 'ID=CSQ' in line: + l = re.search(r'Format: (.*?)"">', vf.meta[i]).group(1).split('|') + return l + +def filter_query(vf, expr, opposite=None, as_index=False, as_zero=False): + """""" + Select rows that satisfy the query expression. + + This method essentially wraps the :meth:`pandas.DataFrame.query` method. + + Parameters + ---------- + expr : str + The query string to evaluate. + opposite : bool, default: False + If True, return rows that don't meet the said criteria. + as_index : bool, default: False + If True, return boolean index array instead of VcfFrame. + as_zero : bool, default: False + If True, missing values will be converted to zeros instead of ``NaN``. + + Returns + ------- + VcfFrame or pandas.Series + Filtered VcfFrame or boolean index array. + + Examples + -------- + + >>> from fuc import common, pyvcf, pyvep + >>> common.load_dataset('tcga-laml') + >>> fn = '~/fuc-data/tcga-laml/tcga_laml_vep.vcf' + >>> vf = pyvcf.VcfFrame.from_file(fn) + >>> filtered_vf = pyvep.filter_query(vf, ""SYMBOL == 'TP53'"") + >>> filtered_vf = pyvep.filter_query(vf, ""SYMBOL != 'TP53'"") + >>> filtered_vf = pyvep.filter_query(vf, ""SYMBOL != 'TP53'"", opposite=True) + >>> filtered_vf = pyvep.filter_query(vf, ""Consequence in ['splice_donor_variant', 'stop_gained']"") + >>> filtered_vf = pyvep.filter_query(vf, ""(SYMBOL == 'TP53') and (Consequence.str.contains('stop_gained'))"") + >>> filtered_vf = pyvep.filter_query(vf, ""gnomAD_AF < 0.001"") + >>> filtered_vf = pyvep.filter_query(vf, ""gnomAD_AF < 0.001"", as_zero=True) + >>> filtered_vf = pyvep.filter_query(vf, ""(IMPACT == 'HIGH') or (Consequence.str.contains('missense_variant') and (PolyPhen.str.contains('damaging') or SIFT.str.contains('deleterious')))"") + """""" + df = to_frame(vf, as_zero=as_zero) + i = vf.df.index.isin(df.query(expr).index) + if opposite: + i = ~i + if as_index: + return i + return vf.__class__(vf.copy_meta(), vf.df[i]) +","Python" +"Pharmacogenetics","sbslee/fuc","docs/create.py",".py","11423","439","import subprocess +import pydoc + +from fuc.api.common import FUC_PATH +from fuc.cli import commands +from fuc import pyvcf +import fuc + +modules = [x for x in dir(fuc) if x not in ['api', 'cli'] and '__' not in x] + +# -- README.rst --------------------------------------------------------------- + +credit = """""" +.. + This file was automatically generated by docs/create.py. +"""""" + +readme_file = f'{FUC_PATH}/README.rst' + +fuc_help = subprocess.run(['fuc', '-h'], capture_output=True, text=True, check=True).stdout +fuc_help = '\n'.join([' ' + x for x in fuc_help.splitlines()]) + +module_help = '' +for module in modules: + description = pydoc.getdoc(getattr(fuc, module)).split('\n\n')[0].replace('\n', ' ') + module_help += f'- **{module}** : {description}\n' + +d = dict(credit=credit, fuc_help=fuc_help, module_help=module_help) + +readme = """""" +{credit} +README +****** + +.. image:: https://badge.fury.io/py/fuc.svg + :target: https://badge.fury.io/py/fuc + +.. image:: https://readthedocs.org/projects/sbslee-fuc/badge/?version=latest + :target: https://sbslee-fuc.readthedocs.io/en/latest/?badge=latest + :alt: Documentation Status + +.. image:: https://anaconda.org/bioconda/fuc/badges/version.svg + :target: https://anaconda.org/bioconda/fuc + +.. image:: https://anaconda.org/bioconda/fuc/badges/license.svg + :target: https://github.com/sbslee/fuc/blob/main/LICENSE + +.. image:: https://anaconda.org/bioconda/fuc/badges/downloads.svg + :target: https://anaconda.org/bioconda/fuc/files + +Introduction +============ + +The main goal of the fuc package (pronounced ""eff-you-see"") is to wrap some of the most **f**\ requently **u**\ sed **c**\ ommands in the field of bioinformatics into one place. + +The package is written in Python, and supports both command line interface (CLI) and application programming interface (API) whose documentations are available at the `Read the Docs `_. + +Currently, fuc can be used to analyze, summarize, visualize, and manipulate the following file formats: + +- Sequence Alignment/Map (SAM) +- Binary Alignment/Map (BAM) +- CRAM +- Variant Call Format (VCF) +- Mutation Annotation Format (MAF) +- Browser Extensible Data (BED) +- FASTQ +- FASTA +- General Feature Format (GFF) +- Gene Transfer Format (GTF) +- delimiter-separated values format (e.g. comma-separated values or CSV format) + +Additionally, fuc can be used to parse output data from the following programs: + +- `Ensembl Variant Effect Predictor (VEP) `__ +- `SnpEff `__ +- `bcl2fastq and bcl2fastq2 `__ +- `Kallisto `__ + +Your contributions (e.g. feature ideas, pull requests) are most welcome. + +| Author: Seung-been ""Steven"" Lee +| Email: sbstevenlee@gmail.com +| License: MIT License + +Citation +======== + +If you use fuc in a published analysis, please report the program version +and cite the following article: + +Lee et al., 2022. `ClinPharmSeq: A targeted sequencing panel for clinical pharmacogenetics implementation `__. PLOS ONE. + +Support fuc +=========== + +If you find my work useful, please consider becoming a `sponsor `__. + +Installation +============ + +The following packages are required to run fuc: + +.. parsed-literal:: + + biopython + lxml + matplotlib + matplotlib-venn + numpy + pandas + pyranges + pysam + scipy + seaborn + statsmodels + +There are various ways you can install fuc. The recommended way is via conda (`Anaconda `__): + +.. code-block:: text + + $ conda install -c bioconda fuc + +Above will automatically download and install all the dependencies as well. Alternatively, you can use pip (`PyPI `__) to install fuc and all of its dependencies: + +.. code-block:: text + + $ pip install fuc + +Finally, you can clone the GitHub repository and then install fuc locally: + +.. code-block:: text + + $ git clone https://github.com/sbslee/fuc + $ cd fuc + $ pip install . + +The nice thing about this approach is that you will have access to development versions that are not available in Anaconda or PyPI. For example, you can access a development branch with the ``git checkout`` command. When you do this, please make sure your environment already has all the dependencies installed. + +Getting help +============ + +For detailed documentations on the fuc package's CLI and API, please refer to the `Read the Docs `_. + +For getting help on the fuc CLI: + +.. code-block:: text + + $ fuc -h +{fuc_help} + +For getting help on a specific command (e.g. vcf-merge): + +.. code-block:: text + + $ fuc vcf-merge -h + +Below is the list of submodules available in the fuc API: + +{module_help} +For getting help on a specific submodule (e.g. pyvcf): + +.. code:: python3 + + >>> from fuc import pyvcf + >>> help(pyvcf) + +In Jupyter Notebook and Lab, you can see the documentation for a python +function by hitting ``SHIFT + TAB``. Hit it twice to expand the view. + +CLI examples +============ + +**SAM/BAM/CRAM** + +To print the header of a SAM file: + +.. code-block:: text + + $ fuc bam-head in.sam + +To index a CRAM file: + +.. code-block:: text + + $ fuc bam-index in.cram + +To rename the samples in a SAM file: + +.. code-block:: text + + $ fuc bam-rename in.sam NA12878 > out.sam + +To slice a BAM file: + +.. code-block:: text + + $ fuc bam-slice in.bam chr1:100-200 > out.bam + +**BED** + +To find intersection between BED files: + +.. code-block:: text + + $ fuc bed-intxn 1.bed 2.bed 3.bed > intersect.bed + +**FASTQ** + +To count sequence reads in a FASTQ file: + +.. code-block:: text + + $ fuc fq-count example.fastq + +**FUC** + +To check whether a file exists in the operating system: + +.. code-block:: text + + $ fuc fuc-exist example.txt + +To find all VCF files within the current directory recursively: + +.. code-block:: text + + $ fuc fuc-find .vcf.gz + +**TABLE** + +To merge two tab-delimited files: + +.. code-block:: text + + $ fuc tbl-merge left.tsv right.tsv > merged.tsv + +**VCF** + +To merge VCF files: + +.. code-block:: text + + $ fuc vcf-merge 1.vcf 2.vcf 3.vcf > merged.vcf + +To filter a VCF file annotated by Ensembl VEP: + +.. code-block:: text + + $ fuc vcf-vep in.vcf 'SYMBOL == ""TP53""' > out.vcf + +API examples +============ + +**BAM** + +To create read depth profile of a region from a CRAM file: + +.. code:: python3 + + >>> from fuc import pycov + >>> cf = pycov.CovFrame.from_file('HG00525.final.cram', zero=True, + ... region='chr12:21161194-21239796', names=['HG00525']) + >>> cf.plot_region('chr12:21161194-21239796') + +.. image:: https://raw.githubusercontent.com/sbslee/fuc-data/main/images/coverage.png + +**VCF** + +To filter a VCF file based on a BED file: + +.. code:: python3 + + >>> from fuc import pyvcf + >>> vf = pyvcf.VcfFrame.from_file('original.vcf') + >>> filtered_vf = vf.filter_bed('targets.bed') + >>> filtered_vf.to_file('filtered.vcf') + +To remove indels from a VCF file: + +.. code:: python3 + + >>> from fuc import pyvcf + >>> vf = pyvcf.VcfFrame.from_file('with_indels.vcf') + >>> filtered_vf = vf.filter_indel() + >>> filtered_vf.to_file('no_indels.vcf') + +To create a Venn diagram showing genotype concordance between groups: + +.. code:: python3 + + >>> from fuc import pyvcf, common + >>> common.load_dataset('pyvcf') + >>> f = '~/fuc-data/pyvcf/plot_comparison.vcf' + >>> vf = pyvcf.VcfFrame.from_file(f) + >>> a = ['Steven_A', 'John_A', 'Sara_A'] + >>> b = ['Steven_B', 'John_B', 'Sara_B'] + >>> c = ['Steven_C', 'John_C', 'Sara_C'] + >>> vf.plot_comparison(a, b, c) + +.. image:: https://raw.githubusercontent.com/sbslee/fuc-data/main/images/plot_comparison.png + +To create various figures for normal-tumor analysis: + +.. code:: python3 + + >>> import matplotlib.pyplot as plt + >>> from fuc import common, pyvcf + >>> common.load_dataset('pyvcf') + >>> vf = pyvcf.VcfFrame.from_file('~/fuc-data/pyvcf/normal-tumor.vcf') + >>> af = pyvcf.AnnFrame.from_file('~/fuc-data/pyvcf/normal-tumor-annot.tsv', sample_col='Sample') + >>> normal = af.df[af.df.Tissue == 'Normal'].index + >>> tumor = af.df[af.df.Tissue == 'Tumor'].index + >>> fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(2, 2, figsize=(10, 10)) + >>> vf.plot_tmb(ax=ax1) + >>> vf.plot_tmb(ax=ax2, af=af, group_col='Tissue') + >>> vf.plot_hist_format('#DP', ax=ax3, af=af, group_col='Tissue') + >>> vf.plot_regplot(normal, tumor, ax=ax4) + >>> plt.tight_layout() + +.. image:: https://raw.githubusercontent.com/sbslee/fuc-data/main/images/normal-tumor.png + +**MAF** + +To create an oncoplot with a MAF file: + +.. code:: python3 + + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> mf.plot_oncoplot() + +.. image:: https://raw.githubusercontent.com/sbslee/fuc-data/main/images/oncoplot.png + +To create a customized oncoplot with a MAF file, see the `Create customized oncoplot `__ tutorial: + +.. image:: https://raw.githubusercontent.com/sbslee/fuc-data/main/images/customized_oncoplot.png + +To create a summary figure for a MAF file: + +.. code:: python3 + + >>> from fuc import common, pymaf + >>> common.load_dataset('tcga-laml') + >>> maf_file = '~/fuc-data/tcga-laml/tcga_laml.maf.gz' + >>> mf = pymaf.MafFrame.from_file(maf_file) + >>> mf.plot_summary() + +.. image:: https://raw.githubusercontent.com/sbslee/fuc-data/main/images/maf_summary-2.png + +"""""".format(**d) + +with open(readme_file, 'w') as f: + f.write(readme.lstrip()) + +# -- cli.rst ----------------------------------------------------------------- + +cli_file = f'{FUC_PATH}/docs/cli.rst' + +cli = """""" +{credit} +CLI +*** + +Introduction +============ + +This section describes command line interface (CLI) for the fuc package. + +For getting help on the fuc CLI: + +.. code-block:: text + + $ fuc -h +{fuc_help} + +For getting help on a specific command (e.g. vcf-merge): + +.. code-block:: text + + $ fuc vcf-merge -h + +"""""".format(**d) + +for command in commands: + s = f'{command}\n' + s += '=' * (len(s)-1) + '\n' + s += '\n' + s += '.. code-block:: text\n' + s += '\n' + s += f' $ fuc {command} -h\n' + command_help = subprocess.run(['fuc', command, '-h'], capture_output=True, text=True, check=True).stdout + command_help = '\n'.join([' ' + x for x in command_help.splitlines()]) + s += command_help + '\n' + s += '\n' + cli += s + +with open(cli_file, 'w') as f: + f.write(cli.lstrip()) + +# -- api.rst ----------------------------------------------------------------- + +api_file = f'{FUC_PATH}/docs/api.rst' + +api = """""" +{credit} +API +*** + +Introduction +============ + +This section describes application programming interface (API) for the fuc package. + +Below is the list of submodules available in the fuc API: + +{module_help} +For getting help on a specific submodule (e.g. pyvcf): + +.. code:: python3 + + from fuc import pyvcf + help(pyvcf) + +"""""".format(**d) + +for module in modules: + s = f'fuc.{module}\n' + s += '=' * (len(s)-1) + '\n' + s += '\n' + s += f'.. automodule:: fuc.api.{module}\n' + s += ' :members:\n' + s += '\n' + api += s + +with open(api_file, 'w') as f: + f.write(api.lstrip()) +","Python" +"Pharmacogenetics","sbslee/fuc","docs/conf.py",".py","3518","131","# Configuration file for the Sphinx documentation builder. +# +# This file only contains a selection of the most common options. For a full +# list see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +# -- Path setup -------------------------------------------------------------- + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. + +import os +import sys +sys.path.insert(0, os.path.abspath('.')) +sys.path.insert(0, os.path.abspath('../')) + +# -- Project information ----------------------------------------------------- + +project = 'fuc' +copyright = '2021, Seung-been ""Steven"" Lee' +author = 'Seung-been ""Steven"" Lee' + + +# -- General configuration --------------------------------------------------- + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.autodoc', + 'sphinx.ext.napoleon', + 'sphinx.ext.linkcode', + 'sphinx.ext.autosectionlabel', + 'sphinx_rtd_theme', + 'sphinx_issues', + 'autodocsumm', + 'matplotlib.sphinxext.plot_directive' +] + +autodoc_mock_imports = [ + 'Bio', + 'lxml', + 'pyranges', +] + +autodoc_default_options = { + 'autosummary': True, +} + +issues_github_path = 'sbslee/fuc' + +napoleon_use_param = False + +autosectionlabel_prefix_document = True + +# Include the example source for plots in API docs +plot_include_source = True +plot_formats = [('png', 90)] +plot_html_show_formats = False +plot_html_show_source_link = False + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = 'sphinx_rtd_theme' + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named ""default.css"" will overwrite the builtin ""default.css"". +html_static_path = [] + +# -- Add external links to source code with sphinx.ext.linkcode -------------- + +import inspect + +def linkcode_resolve(domain, info): + if domain != 'py': + return None + + modname = info['module'] + + if not modname: + return None + + submod = sys.modules.get(modname) + + if submod is None: + return None + + fullname = info['fullname'] + obj = submod + + for part in fullname.split('.'): + try: + obj = getattr(obj, part) + except AttributeError: + return None + + try: + fn = inspect.getsourcefile(inspect.unwrap(obj)) + except TypeError: + fn = None + if not fn: + return None + + try: + source, lineno = inspect.getsourcelines(obj) + except OSError: + lineno = None + + if lineno: + linespec = f'#L{lineno}-L{lineno + len(source) - 1}' + else: + linespec = '' + + fn = fn.split('/api/')[1] + + return f'https://github.com/sbslee/fuc/tree/main/fuc/api/{fn}/{linespec}' +","Python" +"Pharmacogenetics","sbslee/fuc","docs/examples/vcf_sv.py",".py","2338","61","from fuc import pyvcf, common +import matplotlib.pyplot as plt +import seaborn as sns + +sns.set() + +cyp2d6_starts = [42522500,42522852,42523448,42523843,42524175,42524785,42525034,42525739,42526613] +cyp2d6_ends = [42522754,42522994,42523636,42523985,42524352,42524946,42525187,42525911,42526883] +cyp2d7_starts = [42536213,42536565,42537161,42537543,42537877,42538479,42538728,42539410,42540284] +cyp2d7_ends = [42536467,42536707,42537349,42537685,42538054,42538640,42538881,42539582,42540576] + +common.load_dataset('pyvcf') +vcf_file = '~/fuc-data/pyvcf/getrm-cyp2d6-vdr.vcf' +vf = pyvcf.VcfFrame.from_file(vcf_file) + +fig, axes = plt.subplots(2, 3, figsize=(18, 12)) + +[[ax1, ax2, ax3], [ax4, ax5, ax6]] = axes + +vf.plot_region('NA18973', ax=ax1, color='tab:green') +vf.plot_region('HG00276', ax=ax2, color='tab:green') +vf.plot_region('NA19109', ax=ax3, color='tab:green') + +vf.plot_region('NA18973', ax=ax4, k='#AD_FRAC_REF', label='REF') +vf.plot_region('NA18973', ax=ax4, k='#AD_FRAC_ALT', label='ALT') +vf.plot_region('HG00276', ax=ax5, k='#AD_FRAC_REF') +vf.plot_region('HG00276', ax=ax5, k='#AD_FRAC_ALT') +vf.plot_region('NA19109', ax=ax6, k='#AD_FRAC_REF') +vf.plot_region('NA19109', ax=ax6, k='#AD_FRAC_ALT') + +ax1.set_title('NA18973 (no structural variation)', fontsize=25) +ax2.set_title('NA10831 (CYP2D6 deletion)', fontsize=25) +ax3.set_title('NA19109 (CYP2D6 duplication)', fontsize=25) + +ax4.set_ylabel('Allele fraction') +ax4.legend(loc='upper left', fontsize=20, markerscale=2) + +for ax in [ax1, ax2, ax3]: + ax.set_xlabel('') + ax.set_xticklabels([]) + ax.set_ylim([-15, 120]) + common.plot_exons(cyp2d6_starts, cyp2d6_ends, name='CYP2D6', offset=8, y=-5, height=5, ax=ax) + common.plot_exons(cyp2d7_starts, cyp2d7_ends, name='CYP2D7', offset=8, y=-5, height=5, ax=ax) + +for ax in [ax2, ax3, ax5, ax6]: + ax.set_ylabel('') + ax.set_yticklabels([]) + +for ax in [ax1, ax4, ax5, ax6]: + ax.xaxis.label.set_size(20) + ax.yaxis.label.set_size(20) + ax.tick_params(axis='both', which='major', labelsize=15) + +for ax in [ax4, ax5, ax6]: + ax.set_ylim([-0.15, 1.1]) + common.plot_exons(cyp2d6_starts, cyp2d6_ends, name='CYP2D6', offset=0.075, y=-0.05, height=0.05, ax=ax) + common.plot_exons(cyp2d7_starts, cyp2d7_ends, name='CYP2D7', offset=0.075, y=-0.05, height=0.05, ax=ax) + +plt.tight_layout() +plt.savefig('vcf_sv.png') +","Python" +"Pharmacogenetics","sbslee/fuc","docs/examples/customized_oncoplot_1.py",".py","3665","89","# File: customized_oncoplot_1.py + +import matplotlib.pyplot as plt +from fuc import common, pymaf + +common.load_dataset('tcga-laml') +mf = pymaf.MafFrame.from_file('~/fuc-data/tcga-laml/tcga_laml.maf.gz') +af = common.AnnFrame.from_file('~/fuc-data/tcga-laml/tcga_laml_annot.tsv', sample_col=0) +af.df['days_to_last_followup'] = common.convert_num2cat(af.df['days_to_last_followup']) + +# Define the shared variables. +count=10 +figsize=(15, 10) +label_fontsize=13 +ticklabels_fontsize=12 +legend_fontsize=12 + +# Create the figure. Getting the right height ratios can be tricky and often requires a trial-and-error process. +fig, axes = plt.subplots(6, 2, figsize=figsize, gridspec_kw={'height_ratios': [1, 10, 1, 1, 1, 3.5], 'width_ratios': [10, 1]}) +[[ax1, ax2], [ax3, ax4], [ax5, ax6], [ax7, ax8], [ax9, ax10], [ax11, ax12]] = axes +fig.suptitle('customized_oncoplot_1.py', fontsize=20) + +# Create the TMB plot. +samples = list(mf.matrix_waterfall(count).columns) +mf.plot_tmb(ax=ax1, samples=samples) +ax1.set_xlabel('') +ax1.spines['right'].set_visible(False) +ax1.spines['top'].set_visible(False) +ax1.spines['bottom'].set_visible(False) +ax1.set_ylabel('TMB', fontsize=label_fontsize) +ax1.set_yticks([0, mf.matrix_tmb().sum(axis=1).max()]) +ax1.tick_params(axis='y', which='major', labelsize=ticklabels_fontsize) + +ax2.remove() + +# Create the waterfall plot. +mf.plot_waterfall(count=count, ax=ax3, linewidths=0.5) +ax3.set_xlabel('') +ax3.tick_params(axis='y', which='major', labelrotation=0, labelsize=ticklabels_fontsize) + +# Create the genes plot. +mf.plot_genes(count=count, ax=ax4, mode='samples', width=0.95) +ax4.spines['right'].set_visible(False) +ax4.spines['left'].set_visible(False) +ax4.spines['top'].set_visible(False) +ax4.set_yticks([]) +ax4.set_xlabel('Samples', fontsize=label_fontsize) +ax4.set_xticks([0, mf.matrix_genes(count=10, mode='samples').sum(axis=1).max()]) +ax4.set_ylim(-0.5, count-0.5) +ax4.tick_params(axis='x', which='major', labelsize=ticklabels_fontsize) + +# Create the annotation plot for 'FAB_classification'. +_, handles1 = af.plot_annot('FAB_classification', samples=samples, ax=ax5, colors='Dark2', xticklabels=False) +ax5.set_ylabel('') + +ax6.remove() + +# Create the annotation plot for 'days_to_last_followup'. +_, handles2 = af.plot_annot('days_to_last_followup', samples=samples, ax=ax7, colors='viridis', sequential=True, xticklabels=False) +ax7.set_ylabel('') +ax8.remove() + +# Create the annotation plot for 'Overall_Survival_Status'. +_, handles3 = af.plot_annot('Overall_Survival_Status', samples=samples, ax=ax9, colors='Pastel1', xticklabels=False) +ax9.set_xlabel('Samples', fontsize=label_fontsize) +ax9.set_ylabel('') + +ax10.remove() + +# Create the legends. Getting the right legend locations can be tricky and often requires a trial-and-error process. +handles4 = common.legend_handles(pymaf.NONSYN_NAMES + ['Multi_Hit'], pymaf.NONSYN_COLORS + ['k']) + +leg1 = ax11.legend(handles=handles1, loc=(0.43, 0), title='FAB_classification', ncol=2, fontsize=legend_fontsize, title_fontsize=legend_fontsize) +leg2 = ax11.legend(handles=handles2, loc=(0.62, 0), title='days_to_last_followup', fontsize=legend_fontsize, title_fontsize=legend_fontsize) +leg3 = ax11.legend(handles=handles3, loc=(0.82, 0), title='Overall_Survival_Status', fontsize=legend_fontsize, title_fontsize=legend_fontsize) +leg4 = ax11.legend(handles=handles4, loc=(0, 0), title='Variant_Classification', ncol=2, fontsize=legend_fontsize, title_fontsize=legend_fontsize) + +ax11.add_artist(leg1) +ax11.add_artist(leg2) +ax11.add_artist(leg3) +ax11.add_artist(leg4) +ax11.axis('off') + +ax12.remove() + +plt.tight_layout() +plt.subplots_adjust(wspace=0.01, hspace=0.01) +plt.savefig('customized_oncoplot_1.png') +","Python" +"Pharmacogenetics","sbslee/fuc","docs/examples/customized_oncoplot_3.py",".py","3758","89","# File: customized_oncoplot_3.py + +import matplotlib.pyplot as plt +from fuc import common, pymaf +common.load_dataset('tcga-laml') +mf = pymaf.MafFrame.from_file('~/fuc-data/tcga-laml/tcga_laml.maf.gz') +af = common.AnnFrame.from_file('~/fuc-data/tcga-laml/tcga_laml_annot.tsv', sample_col=0) +af.df['days_to_last_followup'] = common.convert_num2cat(af.df['days_to_last_followup']) + +# Filter the MafFrame. +mf = mf.filter_annot(af, ""Overall_Survival_Status == 1"") + +# Define the shared variables. +count=10 +figsize=(15, 10) +label_fontsize=13 +ticklabels_fontsize=12 +legend_fontsize=12 + +# Create the figure. Getting the right height ratios can be tricky and often requires a trial-and-error process. +fig, axes = plt.subplots(6, 2, figsize=figsize, gridspec_kw={'height_ratios': [1, 10, 1, 1, 1, 3.5], 'width_ratios': [10, 1]}) +[[ax1, ax2], [ax3, ax4], [ax5, ax6], [ax7, ax8], [ax9, ax10], [ax11, ax12]] = axes +fig.suptitle('customized_oncoplot_3.py', fontsize=20) + +# Create the TMB plot. +samples = list(mf.matrix_waterfall(count).columns) +mf.plot_tmb(ax=ax1, samples=samples) +ax1.set_xlabel('') +ax1.spines['right'].set_visible(False) +ax1.spines['top'].set_visible(False) +ax1.spines['bottom'].set_visible(False) +ax1.set_ylabel('TMB', fontsize=label_fontsize) +ax1.set_yticks([0, mf.matrix_tmb().sum(axis=1).max()]) +ax1.tick_params(axis='y', which='major', labelsize=ticklabels_fontsize) + +ax2.remove() + +# Create the waterfall plot. +mf.plot_waterfall(count=count, ax=ax3, linewidths=1, samples=samples) +ax3.set_xlabel('') +ax3.tick_params(axis='y', which='major', labelrotation=0, labelsize=ticklabels_fontsize) + +# Create the genes plot. +mf.plot_genes(count=count, ax=ax4, mode='samples', width=0.95) +ax4.spines['right'].set_visible(False) +ax4.spines['left'].set_visible(False) +ax4.spines['top'].set_visible(False) +ax4.set_yticks([]) +ax4.set_xlabel('Samples', fontsize=label_fontsize) +ax4.set_xticks([0, mf.matrix_genes(count=10, mode='samples').sum(axis=1).max()]) +ax4.set_ylim(-0.5, count-0.5) +ax4.tick_params(axis='x', which='major', labelsize=ticklabels_fontsize) + +# Create the annotation plot for 'FAB_classification'. +_, handles1 = af.plot_annot('FAB_classification', samples=samples, ax=ax5, colors='Dark2', xticklabels=False) +ax5.set_ylabel('') +ax6.remove() + +# Create the annotation plot for 'days_to_last_followup'. +_, handles2 = af.plot_annot('days_to_last_followup', samples=samples, ax=ax7, colors='viridis', sequential=True, xticklabels=False) +ax7.set_ylabel('') + +ax8.remove() + +# Create the annotation plot for 'Overall_Survival_Status'. +_, handles3 = af.plot_annot('Overall_Survival_Status', samples=samples, ax=ax9, colors='Pastel1', xticklabels=False) +ax9.set_xlabel('Samples', fontsize=label_fontsize) +ax9.set_ylabel('') + +ax10.remove() + +# Create the legends. Getting the right legend locations can be tricky and often requires a trial-and-error process. +handles4 = common.legend_handles(pymaf.NONSYN_NAMES + ['Multi_Hit'], pymaf.NONSYN_COLORS + ['k']) +leg4 = ax11.legend(handles=handles4, loc=(0, 0), title='Variant_Classification', ncol=2, fontsize=legend_fontsize, title_fontsize=legend_fontsize) +leg1 = ax11.legend(handles=handles1, loc=(0.43, 0), title='FAB_classification', ncol=2, fontsize=legend_fontsize, title_fontsize=legend_fontsize) +leg2 = ax11.legend(handles=handles2, loc=(0.62, 0), title='days_to_last_followup', fontsize=legend_fontsize, title_fontsize=legend_fontsize) +leg3 = ax11.legend(handles=handles3, loc=(0.82, 0), title='Overall_Survival_Status', fontsize=legend_fontsize, title_fontsize=legend_fontsize) +ax11.add_artist(leg1) +ax11.add_artist(leg2) +ax11.add_artist(leg3) +ax11.add_artist(leg4) +ax11.axis('off') + +ax12.remove() + +plt.tight_layout() +plt.subplots_adjust(wspace=0.01, hspace=0.01) +plt.savefig('customized_oncoplot_3.png') +","Python" +"Pharmacogenetics","sbslee/fuc","docs/examples/customized_oncoplot_2.py",".py","3727","86","# File: customized_oncoplot_2.py + +import matplotlib.pyplot as plt +from fuc import common, pymaf +common.load_dataset('tcga-laml') +mf = pymaf.MafFrame.from_file('~/fuc-data/tcga-laml/tcga_laml.maf.gz') +af = common.AnnFrame.from_file('~/fuc-data/tcga-laml/tcga_laml_annot.tsv', sample_col=0) +af.df['days_to_last_followup'] = common.convert_num2cat(af.df['days_to_last_followup']) + +# Define the shared variables. +count=10 +figsize=(15, 10) +label_fontsize=13 +ticklabels_fontsize=12 +legend_fontsize=12 + +# Create the figure. Getting the right height ratios can be tricky and often requires a trial-and-error process. +fig, axes = plt.subplots(6, 2, figsize=figsize, gridspec_kw={'height_ratios': [1, 10, 1, 1, 1, 3.5], 'width_ratios': [10, 1]}) +[[ax1, ax2], [ax3, ax4], [ax5, ax6], [ax7, ax8], [ax9, ax10], [ax11, ax12]] = axes +fig.suptitle('customized_oncoplot_2.py', fontsize=20) + +# Create the TMB plot. +samples = af.sorted_samples(['FAB_classification', 'Overall_Survival_Status'], mf=mf, nonsyn=True) +mf.plot_tmb(ax=ax1, samples=samples) +ax1.set_xlabel('') +ax1.spines['right'].set_visible(False) +ax1.spines['top'].set_visible(False) +ax1.spines['bottom'].set_visible(False) +ax1.set_ylabel('TMB', fontsize=label_fontsize) +ax1.set_yticks([0, mf.matrix_tmb().sum(axis=1).max()]) +ax1.tick_params(axis='y', which='major', labelsize=ticklabels_fontsize) + +ax2.remove() + +# Create the waterfall plot. +mf.plot_waterfall(count=count, ax=ax3, linewidths=0.5, samples=samples) +ax3.set_xlabel('') +ax3.tick_params(axis='y', which='major', labelrotation=0, labelsize=ticklabels_fontsize) + +# Create the genes plot. +mf.plot_genes(count=count, ax=ax4, mode='samples', width=0.95) +ax4.spines['right'].set_visible(False) +ax4.spines['left'].set_visible(False) +ax4.spines['top'].set_visible(False) +ax4.set_yticks([]) +ax4.set_xlabel('Samples', fontsize=label_fontsize) +ax4.set_xticks([0, mf.matrix_genes(count=10, mode='samples').sum(axis=1).max()]) +ax4.set_ylim(-0.5, count-0.5) +ax4.tick_params(axis='x', which='major', labelsize=ticklabels_fontsize) + +# Create the annotation plot for 'FAB_classification'. +_, handles1 = af.plot_annot('FAB_classification', samples=samples, ax=ax5, colors='Dark2', xticklabels=False) +ax5.set_ylabel('') +ax6.remove() + +# Create the annotation plot for 'days_to_last_followup'. +_, handles2 = af.plot_annot('days_to_last_followup', samples=samples, ax=ax7, colors='viridis', sequential=True, xticklabels=False) +ax7.set_ylabel('') + +ax8.remove() + +# Create the annotation plot for 'Overall_Survival_Status'. +_, handles3 = af.plot_annot('Overall_Survival_Status', samples=samples, ax=ax9, colors='Pastel1', xticklabels=False) +ax9.set_xlabel('Samples', fontsize=label_fontsize) +ax9.set_ylabel('') + +ax10.remove() + +# Create the legends. Getting the right legend locations can be tricky and often requires a trial-and-error process. +handles4 = common.legend_handles(pymaf.NONSYN_NAMES + ['Multi_Hit'], pymaf.NONSYN_COLORS + ['k']) +leg4 = ax11.legend(handles=handles4, loc=(0, 0), title='Variant_Classification', ncol=2, fontsize=legend_fontsize, title_fontsize=legend_fontsize) +leg1 = ax11.legend(handles=handles1, loc=(0.43, 0), title='FAB_classification', ncol=2, fontsize=legend_fontsize, title_fontsize=legend_fontsize) +leg2 = ax11.legend(handles=handles2, loc=(0.62, 0), title='days_to_last_followup', fontsize=legend_fontsize, title_fontsize=legend_fontsize) +leg3 = ax11.legend(handles=handles3, loc=(0.82, 0), title='Overall_Survival_Status', fontsize=legend_fontsize, title_fontsize=legend_fontsize) +ax11.add_artist(leg1) +ax11.add_artist(leg2) +ax11.add_artist(leg3) +ax11.add_artist(leg4) +ax11.axis('off') + +ax12.remove() + +plt.tight_layout() +plt.subplots_adjust(wspace=0.01, hspace=0.01) +plt.savefig('customized_oncoplot_2.png') +","Python"