merger.py 5.61 KB
Newer Older
Aflitos, Saulo Alves's avatar
first  
Aflitos, Saulo Alves committed
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
#!/usr/bin/python
import os, sys
import glob
from pprint import pprint as pp


if len(sys.argv) < 4:
    print "no libs given"
    print sys.argv[0], "<IN CSV GROUP> <IN CSV LIB> <OUT FILE>"
    sys.exit(1)


CSV_GROUP  = sys.argv[1]
CSV_LIB    = sys.argv[2]
CSV_OUT    = sys.argv[3]

if (not os.path.exists( CSV_GROUP )) or ((CSV_LIB is not None) and (not os.path.exists(CSV_LIB))):
    if (not os.path.exists( CSV_GROUP )):
        print "csv group file %s does not exists" % CSV_GROUP

    if ((CSV_LIB is not None) and (not os.path.exists(CSV_LIB))):
        print "csv lib file %s does not exists" % CSV_LIB

    print sys.arv[0], "<IN CSV GROUP> <IN CSV LIB>"
    sys.exit(1)

if os.path.exists( CSV_OUT ):
    print "output file %s already exists" % CSV_OUT
    sys.exit( 1 )




def main():
    data   = {}
    groups = {}

    with open(CSV_LIB, 'r') as fhd:
        line_count = 0
        for line in fhd:
            line_count += 1
            if line_count == 1:
                continue

            if len(line.strip()) == 0 or line[0] == '#':
                continue

            #0             1             2              3         4       5          6            7            8              9                 10             11
            #library_name, project_name, organism_name, type    , paired, frag_size, frag_stddev, insert_size, insert_stddev, read_orientation, genomic_start, genomic_end
            #frags_PE_170, arcanum     , sa           , fragment, 1     , 170      , 17         ,            ,              , inward          , 0            ,           0

            cels   = line.split(',')
            print  "parsing line '%s'" % line.strip()
            gname  = cels[0].strip()
            fsize  = cels[5].strip()
            fstdd  = cels[6].strip()
            isize  = cels[7].strip()
            istdd  = cels[8].strip()

            if gname not in data:
                groups[gname] = {}

            gtype = ""
            gsize = 0
            gmin  = 0
            gmax  = 0
            gmax2 = 0

            if len(fsize) > 0:
                gtype = 'pe'
                gsize = int(fsize)
                gmin  = int(fsize) - int(fstdd)
                gmax  = int(fsize) + int(fstdd)
                gmax2 = int(fsize) + (3*int(fstdd))

            elif len(isize) > 0:
                gtype = 'mp'
                #data[gname]['type'] = 'pe'
                gsize = int(isize)
                gmin  = int(isize) - int(istdd)
                gmax  = int(isize) + int(istdd)
                gmax2 = int(isize) + (3*int(istdd))

            else:
                print line
                print "count not find size"
                sys.exit(1)

            groups[gname]['gtype'] = gtype
            groups[gname]['gsize'] = gsize
            groups[gname]['gmin' ] = gmin
            groups[gname]['gmax' ] = gmax
            groups[gname]['gmax2'] = gmax2



    with open(CSV_GROUP, 'r') as fhd:
        line_count = 0
        for line in fhd:
            line_count += 1
            if line_count == 1:
                continue

            if len(line.strip()) == 0 or line[0] == '#':
                continue

            #0
            #file_name                                             , group_name, library_name
            #120527_I247_FCC0U0NACXX_L7_TOMxitDGJDWAAPEI-93_*.fq.gz, MP_2000_1 , jumps_MP_2000

            cels   = line.split(',')
            print  "parsing line '%s'" % line.strip()
            fname  = cels[0].strip()
            gname  = cels[2].strip()
            fnames = glob.glob(fname)

            if len(fnames) == 0:
                print "error globing '%s'" % fname.strip()
                print " line '%s'"         % line.strip()
                sys.exit(1)

            cpref = os.path.basename( os.path.commonprefix(fnames) )
            cpref = cpref.rstrip("_.-")
            print cpref

            if len(fnames) % 2 != 0:
                print "oops. failed to glob"
                sys.exit(1)

            elif len(fnames) == 2:
                data[cpref] = { "file_names": [] }

                for ffname in fnames:
                    print ffname

                    if not os.path.exists(ffname) or not os.path.isfile(ffname):
                        print "file %s does not exists" % ffname
                        sys.exit(1)

                    datal = data[cpref]
                    datal["file_names"].append( ffname )

                    for key in groups[gname]:
                        datal[ key] = groups[gname][ key ]

            else:
                print "oops2. globed more than 2 files"
                sys.exit(1)
                for ffname in fnames:
                    print ffname

                    if not os.path.exists(ffname) or not os.path.isfile(ffname):
                        print "file %s does not exists" % ffname
                        sys.exit(1)

                    data[ffname] = {}

    #pp(data)

    with open(CSV_OUT, 'w') as ofh:
        outlines = []
        for gname in sorted( data ):
            ostr = gname
            datal = data[gname]
            for field in ['gtype', 'gsize', 'gmin', 'gmax', 'file_names']:
                opart  = ""
                fieldl = datal[ field ]
                if isinstance(fieldl, list):
                    opart += "," + ";".join( fieldl )

                else:
                    opart += "," + str(fieldl)

                ostr += opart
            print ostr
            outlines.append( ostr + "\n" )
        ofh.write("#group name,library name,library size,library size min,library size max,file names\n")
        ofh.writelines( outlines )

if __name__ == '__main__':
    main()
    print "\n\n"
    print 'finished'