<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 Goal
Follow-up to
Step1:  BD min/max
Step2:  Nestly
assuming fragments already simulated
Step3:  Nestly params
Step4:  Copying input files
Step5:  Multi-window HR-SIP
Step6:  Making confusion matrices
Step7:  Aggregating the confusion matrix data
Step8:  --End of simulation--
Plotting results
Step9:  Checking that specificity is not always 1 (perfect)
<ASSISTANT_TASK:>
Python Code:
import os
import glob
import itertools
import nestly
%load_ext rpy2.ipython
%load_ext pushnote
%%R
library(ggplot2)
library(dplyr)
library(tidyr)
library(gridExtra)
Explanation: Goal
Follow-up to: atomIncorp_taxaIncorp
Determining the effect of 'heavy' BD window (number of windows & window sizes) on HR-SIP accuracy
Apply a sparsity cutoff after to selecting 'heavy' fraction samples 
In other words, taxa must be present in just most of the 'heavy' fraction sampels
Variable parameters:
'heavy' BD window sizes
Init
End of explanation
## min G+C cutoff
min_GC = 13.5
## max G+C cutoff
max_GC = 80
## max G+C shift
max_13C_shift_in_BD = 0.036
min_BD = min_GC/100.0 * 0.098 + 1.66    
max_BD = max_GC/100.0 * 0.098 + 1.66    
max_BD = max_BD + max_13C_shift_in_BD
print 'Min BD: {}'.format(min_BD)
print 'Max BD: {}'.format(max_BD)
Explanation: BD min/max
End of explanation
# paths
workDir = '/home/nick/notebook/SIPSim/dev/bac_genome1147/'
buildDir = os.path.join(workDir, 'atomIncorp_taxaIncorp_MW-HR-SIP_postSpar')
dataDir = os.path.join(workDir, 'atomIncorp_taxaIncorp')
if not os.path.isdir(buildDir):
    os.makedirs(buildDir)
%cd $buildDir
# making an experimental design file for qSIP
x = range(1,7)
y = ['control', 'treatment']
expDesignFile = os.path.join(buildDir, 'qSIP_exp_design.txt')
with open(expDesignFile, 'wb') as outFH:
    for i,z in itertools.izip(x,itertools.cycle(y)):
        line = '\t'.join([str(i),z])
        outFH.write(line + '\n')
!head $expDesignFile       
Explanation: Nestly
assuming fragments already simulated
End of explanation
# building tree structure
nest = nestly.Nest()
# varying params
nest.add('percIncorp', [0, 15, 25, 50, 100])
nest.add('percTaxa', [1, 5, 10, 25, 50])
nest.add('rep', range(1,11))
## set params
nest.add('abs', ['1e9'], create_dir=False)
nest.add('np', [10], create_dir=False)
nest.add('Monte_rep', [100000], create_dir=False)
nest.add('subsample_dist', ['lognormal'], create_dir=False)
nest.add('subsample_mean', [9.432], create_dir=False)
nest.add('subsample_scale', [0.5], create_dir=False)
nest.add('subsample_min', [10000], create_dir=False)
nest.add('subsample_max', [30000], create_dir=False)
nest.add('min_BD', [min_BD], create_dir=False)
nest.add('max_BD', [max_BD], create_dir=False)
nest.add('DBL_scaling', [0.5], create_dir=False)
nest.add('bandwidth', [0.8], create_dir=False)
nest.add('heavy_BD_min', [1.71], create_dir=False)
nest.add('heavy_BD_max', [1.75], create_dir=False)
nest.add('topTaxaToPlot', [100], create_dir=False)
nest.add('padj', [0.1], create_dir=False)
nest.add('log2', [0.25], create_dir=False)
nest.add('occurs', ['0.0,0.05,0.1,0.15,0.2,0.25,0.3,0.35,0.4,0.45,0.5'], create_dir=False)
### input/output files
nest.add('buildDir', [buildDir], create_dir=False)
nest.add('exp_design', [expDesignFile], create_dir=False)
# building directory tree
nest.build(buildDir)
# bash file to run
bashFile = os.path.join(buildDir, 'SIPSimRun.sh')
Explanation: Nestly params
End of explanation
files = !find . -name "*.json"
dirs = [os.path.split(x)[0] for x in files]
srcFiles = ['OTU_abs1e9_PCR_sub_w.txt', 'OTU_abs1e9_PCR_sub_meta.txt', 'BD-shift_stats.txt']
for d in dirs:
    for f in srcFiles:
        f1 = os.path.join(dataDir, d, f)
        f2 = os.path.join(buildDir, d, f)
        cmd = 'cp -f {} {}'.format(f1, f2)
        !$cmd
Explanation: Copying input files
End of explanation
bashFileTmp = os.path.splitext(bashFile)[0] + '_HRSIP_multi.sh'
bashFileTmp
%%writefile $bashFileTmp
#!/bin/bash
# phyloseq
## making phyloseq object from OTU table
SIPSimR phyloseq_make \
    OTU_abs{abs}_PCR_sub_w.txt \
    -s OTU_abs{abs}_PCR_sub_meta.txt \
    > OTU_abs{abs}_PCR_sub.physeq   
    
## HR SIP pipeline
SIPSimR phyloseq_DESeq2 \
    --log2 {log2} \
    --hypo greater \
    --cont 1,3,5 \
    --treat 2,4,6 \
    --occur_heavy {occurs} \
    -w 1.71-1.75 \
    --all OTU_abs1e9_PCR_sub_MW1_all.txt \
    OTU_abs{abs}_PCR_sub.physeq \
    > OTU_abs1e9_PCR_sub_MW1_DESeq2
    
SIPSimR phyloseq_DESeq2 \
    --log2 {log2} \
    --hypo greater \
    --cont 1,3,5 \
    --treat 2,4,6 \
    --occur_heavy {occurs} \
    -w 1.71-1.78 \
    --all OTU_abs1e9_PCR_sub_MW2_all.txt \
    OTU_abs{abs}_PCR_sub.physeq \
    > OTU_abs1e9_PCR_sub_MW2_DESeq2    
SIPSimR phyloseq_DESeq2 \
    --log2 {log2} \
    --hypo greater \
    --cont 1,3,5 \
    --treat 2,4,6 \
    --occur_heavy {occurs} \
    -w 1.69-1.74,1.73-1.78 \
    --all OTU_abs1e9_PCR_sub_MW3_all.txt \
    OTU_abs{abs}_PCR_sub.physeq \
    > OTU_abs1e9_PCR_sub_MW3_DESeq2
       
SIPSimR phyloseq_DESeq2 \
    --log2 {log2} \
    --hypo greater \
    --cont 1,3,5 \
    --treat 2,4,6 \
    --occur_heavy {occurs} \
    -w 1.70-1.73,1.72-1.75,1.74-1.77 \
    --all OTU_abs1e9_PCR_sub_MW4_all.txt \
    OTU_abs{abs}_PCR_sub.physeq \
    > OTU_abs1e9_PCR_sub_MW4_DESeq2
  
SIPSimR phyloseq_DESeq2 \
    --log2 {log2} \
    --hypo greater \
    --cont 1,3,5 \
    --treat 2,4,6 \
    --occur_heavy {occurs} \
    -w 1.69-1.73,1.72-1.76,1.75-1.79 \
    --all OTU_abs1e9_PCR_sub_MW5_all.txt \
    OTU_abs{abs}_PCR_sub.physeq \
    > OTU_abs1e9_PCR_sub_MW5_DESeq2
!chmod 777 $bashFileTmp
!cd $workDir; \
    nestrun --template-file $bashFileTmp -d $buildDir --log-file HR-SIP_multi.log -j 10
%pushnote postSpar MW-HR-SIP complete
Explanation: Multi-window HR-SIP
End of explanation
bashFileTmp = os.path.splitext(bashFile)[0] + '_cMtx.sh'
bashFileTmp
%%writefile $bashFileTmp
#!/bin/bash
# HR-SIP multiple 'heavy' BD windows
SIPSimR DESeq2_confuseMtx \
    --libs 2,4,6 \
    --padj {padj} \
    -o DESeq2_MW1-cMtx \
    BD-shift_stats.txt \
    OTU_abs1e9_PCR_sub_MW1_DESeq2
      
SIPSimR DESeq2_confuseMtx \
    --libs 2,4,6 \
    --padj {padj} \
    -o DESeq2_MW2-cMtx \
    BD-shift_stats.txt \
    OTU_abs1e9_PCR_sub_MW2_DESeq2
    
SIPSimR DESeq2_confuseMtx \
    --libs 2,4,6 \
    --padj {padj} \
    -o DESeq2_MW3-cMtx \
    BD-shift_stats.txt \
    OTU_abs1e9_PCR_sub_MW3_DESeq2
    
SIPSimR DESeq2_confuseMtx \
    --libs 2,4,6 \
    --padj {padj} \
    -o DESeq2_MW4-cMtx \
    BD-shift_stats.txt \
    OTU_abs1e9_PCR_sub_MW4_DESeq2
SIPSimR DESeq2_confuseMtx \
    --libs 2,4,6 \
    --padj {padj} \
    -o DESeq2_MW5-cMtx \
    BD-shift_stats.txt \
    OTU_abs1e9_PCR_sub_MW5_DESeq2          
!chmod 777 $bashFileTmp
!cd $workDir; \
    nestrun --template-file $bashFileTmp -d $buildDir --log-file cMtx.log -j 10
Explanation: Making confusion matrices
End of explanation
def agg_cMtx(prefix):
    # all data
    #!nestagg delim \
    #    -d $buildDir \
    #    -k percIncorp,percTaxa,rep \
    #    -o $prefix-cMtx_data.txt \
    #    --tab \
    #    $prefix-cMtx_data.txt
    # overall
    x = prefix + '-cMtx_overall.txt'
    !nestagg delim \
        -d $buildDir \
        -k percIncorp,percTaxa,rep \
        -o $x \
        --tab \
        $x
    # by class
    x = prefix + '-cMtx_byClass.txt'
    !nestagg delim \
        -d $buildDir \
        -k percIncorp,percTaxa,rep \
        -o $x \
        --tab \
        $x
        
agg_cMtx('DESeq2_MW1')
agg_cMtx('DESeq2_MW2')
agg_cMtx('DESeq2_MW3')
agg_cMtx('DESeq2_MW4')
agg_cMtx('DESeq2_MW5')
%pushnote postSpar MW-HR-SIP run complete!
Explanation: Aggregating the confusion matrix data
End of explanation
F = os.path.join(buildDir, '*-cMtx_byClass.txt')
files = glob.glob(F)
files
%%R -i files
df_byClass = list()
for (f in files){
    ff = strsplit(f, '/') %>% unlist
    fff = ff[length(ff)]
    df_byClass[[fff]] = read.delim(f, sep='\t')
}
df_byClass = do.call(rbind, df_byClass)
df_byClass$file = gsub('\\.[0-9]+$', '', rownames(df_byClass))
df_byClass$method = gsub('-cMtx.+', '', df_byClass$file)
rownames(df_byClass) = 1:nrow(df_byClass)
df_byClass %>% head(n=3)
%%R
# renaming method
rename = data.frame(method = c('DESeq2_MW1', 'DESeq2_MW2', 'DESeq2_MW3', 'DESeq2_MW4', 'DESeq2_MW5'), 
                    method_new = c('1.71-1.75',
                                   '1.71-1.78',
                                   '1.69-1.74,1.73-1.78',
                                   '1.70-1.73,1.72-1.75,1.74-1.77',
                                   '1.69-1.73,1.72-1.76,1.75-1.79'))
df_byClass = inner_join(df_byClass, rename, c('method'='method')) %>%
    select(-method) %>%
    rename('method' = method_new) 
df_byClass$method = factor(df_byClass$method, levels=rename$method_new %>% as.vector)
df_byClass %>% head(n=3)
%%R -w 800 -h 550
# summarize by SIPSim rep & library rep
df_byClass.s = df_byClass %>%
    group_by(method, percIncorp, percTaxa, variables) %>%
    summarize(mean_value = mean(values),
              sd_value = sd(values))
# plotting
ggplot(df_byClass.s, aes(variables, mean_value, color=method,
                         ymin=mean_value-sd_value,
                         ymax=mean_value+sd_value)) +
    geom_pointrange(alpha=0.8, size=0.2) +
    labs(y='Value') +
    facet_grid(percTaxa ~ percIncorp) +
    theme_bw() +
    theme(
        text = element_text(size=16),
        axis.title.x = element_blank(),
        axis.text.x = element_text(angle=45, hjust=1)
    )
%%R -w 850 -h 600
# summarize by SIPSim rep & library rep
vars = c('Balanced Accuracy', 'Sensitivity', 'Specificity')
df_byClass.s.f = df_byClass.s %>%
    filter(variables %in% vars) 
# plotting
ggplot(df_byClass.s.f, aes(variables, mean_value, fill=method,
                         ymin=mean_value-sd_value,
                         ymax=mean_value+sd_value)) +
    #geom_pointrange(alpha=0.8, size=0.2) +
    geom_bar(stat='identity', position='dodge', width=0.8) +
    geom_errorbar(stat='identity', position='dodge', width=0.8) +
    scale_y_continuous(breaks=seq(0, 1, 0.2)) +
    scale_fill_discrete('"Heavy" BD window(s)') +
    facet_grid(percTaxa ~ percIncorp) +
    theme_bw() +
    theme(
        text = element_text(size=16),
        axis.title.x = element_blank(),
        axis.text.x = element_text(angle=45, hjust=1),
        axis.title.y = element_blank()
    )
Explanation: --End of simulation--
Plotting results
End of explanation
%%R -h 250 -w 650
df_byClass.sf = df_byClass %>% 
    filter(variables == 'Specificity') 
max_val = max(df_byClass.sf$values, na.rm=TRUE)
ggplot(df_byClass.sf, aes(values)) +
    geom_histogram() +
    scale_y_log10() +
    labs(x='Specificity') +
    theme_bw() +
    theme(
        text = element_text(size=16)
    )
Explanation: Checking that specificity is not always 1 (perfect)
End of explanation
<END_TASK>