This file is indexed.

/usr/share/arden/arden-analyze is in arden 1.0-1.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
#! /usr/bin/python
"""
Created on Thu Aug 18  2012

Script for analyzing mapping results using an artificial reference genome (ART / ARG). An exhaustive comparison is performed between the input files (SAM format).
The goal is to calculate a ROC curve and the AUC value to compare different read mapper / different settings on the same read mapper. Therefore FP and TP have to be identified.
The TP are from the original reference. The FP are from the ART and are defined as unique mappings in a sense that no FP alignment occurs on the reference.

@author: Sven Giese
"""



"""
Copyright (c) 2012, Sven H. Giese, gieseS@rki.de, 
Robert Koch-Institut, Germany,
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * The name of the author may not be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL MARTIN S. LINDNER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""


import time
import cProfile
import sys
from optparse import OptionParser
import os


from core import  AnalyseMapping as AM
from core import   PlotData as PD



def TestFiles(input):
    """Function which checks if all required files are correctly specified (existing) """
    controlDic = AM.readInput(input)
    # indicator variable
    error = 0
    for mapper in controlDic["mapper"].keys():
        # does the file exist?
        try:
            # yes
            fobj = open(controlDic["mapper"][mapper][0][0],"r")
            fobj.close()
        except IOError:
            # nope --> error
            print "error opening file %s. Does it exist?" % controlDic["mapper"][mapper][0][0]
            error =1
            
        # do the same for the artificial reference mappings
        for p,artificial in enumerate(controlDic["mapper"][mapper][1]):
            try:
                
                fobj = open(artificial,"r")
                fobj.close()
            except IOError:
                print "error opening file %s. Does it exist?" % artificial
                error =1
    return(error)
            
def main():
    """ Control function for arden-analyze """
    usage = """usage: %prog [options] [INPUT FILE] [OUTPUTFOLDER] ...
    Required Arguments:
    
    OUTPUTFOLDER:\t path to output destination folder.
    INPUT FILE: \t ppath to ini file. To get the required format have a look at the example files.
    
    Script to analyze the results of the artificial reference genome mapping. This script identifies the putative TPs / FPs
    on a specific data set (reads).
    """
    
    parser = OptionParser(usage=usage,version="%prog 1.0")
    parser.add_option("-p", "--phred", type='int',dest="phred",action="store",  default=33,help="Specify the PHRED encoding of the input reads i.e. Illumina 1.3+ = -p 33.[default: %default]")
    parser.add_option("-r", "--internalrank", type='int',dest="rank",action="store",  default=1,help="Use internal ranking for reads (needed if the read names cannot be lexicographically be sorted in the same way in python and your OS by sam tools).[default: %default]")
    parser.description=""
    (options, args) = parser.parse_args() 
    numArgs = len(args)
         
    # numArgs has to be equal to # required parameters
    if numArgs ==2 :
        input = args[0]
        outpath = args[1]
        # adjust options, otherwise default is used
        internalrank = options.rank
        phred = options.phred
  
        
    else:
        print("!!!Wrong number of parameters!!!")
        parser.print_help()
        sys.exit(1)
    
    
    
   
    UseInternalRank = 1
    controlDic = AM.readInput(input)
   
    print("#######################################################################################")
    print ("Input Settings:")
    print ("Inputfile:\t%s" % input)
    print ("Outputpath:\t%s" % outpath)
    print ("Reads:\t%s" % controlDic["fastqfile"])
    print ("UseInternalRank:\t%s" % UseInternalRank)
    print ("Phred:\t%s" % phred)
    print("#######################################################################################")
    print ("\r\nStart...")
    error = TestFiles(input)
    if error == 1:
        print "Program aborted. Check your inputfiles!"
        sys.exit()
    else:
        print "Inputfiles checked successfully."
    
    # check if output dir exists; else create output 
    if not os.path.exists(os.path.dirname(outpath)):
        os.makedirs(os.path.dirname(outpath))
    
    # readdictionary with ID as key and quality as VALUE
    start1 = time.time()
    readdic =  AM.readReadQualities(controlDic["fastqfile"])
    end1 = time.time()
    # extend Readdic
    readdic,reverseReadArray =  AM.extendReadDic(readdic)
    
    
    # init resultdictionary which carries all information about temporary results etc.
    resultdic = {}
    resultdic["nreads"] = len(readdic)
    resultdic["maxalngt"] = 0
    resultdic["AUC"] = {}
    resultdic["alngts"] = {}
    resultdic["id"] =[]
    resultdic["mapper"] =[]
    resultdic["lines"] = {}
    resultdic["mreads"] = {} # mapped reads
    
    

    # init list for comparing artificial and reference
    compareList = []


    
    #### looping #####
    print ("########Progress (analysis):########")
    print ("Mapper\t\tOutputfile\t\tOverallAlignments (TP/FP)\t\t Time")
    for mapper in controlDic["mapper"].keys():
        
        
        resultdic["mapper"].append(mapper)
        # initialize output files (write once to them in case an earlier version exists)
        AM.initOutFiles(controlDic,mapper,outpath)
        # set refname
        refname = controlDic["mapper"][mapper][0][0].split("/")[-1]
        
        print ("%s" %mapper.upper()),
        
        if UseInternalRank == 1:
            rankDic = AM.GetOrderDictionary(controlDic["mapper"][mapper][0][0])
            
        for p,artificial in enumerate(controlDic["mapper"][mapper][1]):
            # list for calculation the difference between reference and artificial within a read region
            compareList = AM.CreateCompareList(controlDic["fasta"]["reffasta"],controlDic["fasta"]["artfasta"][p])
            filename = artificial.split("/")[-1]
            outfile = mapper+"_"+artificial.split("/")[-1][:-4]+".esam"


            start = time.time()
            # main function, write results to 4 variables
            tp,fp,LineCounter,MappedReads = AM.ReadSAMnoMem(controlDic["mapper"][mapper][0][0],artificial,outpath+outfile,compareList,readdic,rankDic,phred)
            end = time.time()
            # dummy, configurable sensitivity calculation
            tempmaxsens = tp
            # maintain results in the resultstructure dictionary
            resultdic["alngts"][outfile] = (tp,fp)
            resultdic["lines"][outfile] = LineCounter
            resultdic["mreads"][outfile] = MappedReads
            resultdic["id"].append(outfile)
            
            print (outfile),
            print  ("\t%0.2f (%0.2f/%0.2f)" %(tp+fp,tp,fp)),
            print ("\t%0.2f sec." %(end-start))
    ##################################################################################################################################

  
    # start evaluation process. SAM files are not getting touched anymore
    print ("\r\n########Progress (evaluation):########")    
    print ("Mapper\tTP\tFP\tTime")
    for resultfile in resultdic["id"]:
        print resultfile.split("_")[0],
        
        #do sme name generation for this iteration
        prefix   = outpath+resultfile.split(".")[0]
        filename = resultfile.split(".")[0]
        
        # read data into an array
        dataArray = AM.ReadFromTab(outpath+resultfile,resultdic["lines"][resultfile])
        
        # get tp and fp arrays
        tp =[i for i in dataArray if i.mr[0] ==1]
        fp =[i for i in dataArray if i.mr[0] ==0]
        
        print ("\t %d"  % resultdic["alngts"][resultfile][0]), # TP
        print ("\t %d"  % resultdic["alngts"][resultfile][1]), # FP
        
        start = time.time()
        #try:
        resultdic["AUC"][resultfile] = PD.CalculateRoc2(dataArray,prefix,resultdic["nreads"],resultdic["lines"][resultfile],resultdic["mreads"][resultfile],filename)     
        #except:
            #print("error calculating AUC...")
            
            
        end = time.time()
        print ("\t%0.2f" %(end-start))
    
    # prepare labels and names for plotting the data
    ids =[i for i in resultdic['id']]
    mappernames = [i for i in resultdic['mapper']]
    label = [k for k in xrange(1,len(ids)+1)]
    tuple =[resultdic['alngts'][k] for k in ids]
    tp = [i[0] for i in tuple]
    fp = [i[1] for i in tuple]
    

    # plot an histogram: tp,fp comparison (all mappers included)    
    PD.plotOverviewHist(fp,tp,label,prefix,mappernames)
    

    fobj = open(outpath+"results.txt","w")
    
    ## maintain resultfile
    fobj.write("mapper\tfile\ttp\tfp\tsens\tspec\tAUC\tmappedReads\tInputReads\tF\r\n")
    for resultfile in (resultdic["id"]):

        mapper = resultfile.split("_")[0]
        file =resultfile.replace(".esam","")
        tp =resultdic["alngts"][resultfile][0]
        fp = resultdic["alngts"][resultfile][1]
        
        #sens = (tp / tp+fp) * F
        sens = round((float(tp) / resultdic["lines"][resultfile]) * (float(resultdic["mreads"][resultfile] )/ resultdic["nreads"]),3)
        #sens = 1-(fp / tp+fp) * F
        spec = 1- round((float(fp) / resultdic["lines"][resultfile]) *  (float(resultdic["mreads"][resultfile]) / resultdic["nreads"]),3)
        auc = resultdic["AUC"][resultfile]
        pmappedReads = round(float(resultdic["mreads"][resultfile]) / resultdic["nreads"],3)
        fobj.write("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\r\n" %(mapper,file,tp,fp,sens,spec,auc,resultdic["mreads"][resultfile],resultdic["nreads"],pmappedReads))
    fobj.close()


if __name__ == "__main__":
    a = time.time()
    main()
    b = time.time()
    print ("Finished!")
    print ("Done in %0.2f seconds!" % (b-a))