db.py 12.7 KB
Newer Older
aknecht2's avatar
aknecht2 committed
1
from pymongo import MongoClient
2
import pymongo.errors
3
4
5
import gridfs
import sys
import traceback
6
import os
7
from pprint import pprint
aknecht2's avatar
aknecht2 committed
8

9

10
11
12
class MongoDB(object):

    def __init__(self, host, username, password):
13
14
        self.client = MongoClient(host)
        self.db = self.client.chipseq
15
        try:
16
            self.db.authenticate(username, password, mechanism="SCRAM-SHA-1")
17
18
19
20
21
22
23
        except:
            print("Could not authenticate to db %s!" % (host,))
            print traceback.format_exc()
            sys.exit(1)
        self.gfs = gridfs.GridFS(self.db)
        return

24
25
26
27
28
29
30
31
32
33
34
35
    def delete_result(self, result_id):
        # Make sure result exists
        cursor = self.db.results.find({
            "_id": result_id
        })
        if cursor.count() == 1:
            result = cursor.next()
            self.gfs.delete(result["gridfs_id"])
            self.db[result["result_type"]].delete_many({"result_id": result["_id"]})
            self.db.results.delete_one({"_id": result["_id"]})
        else:
            print "result_id %s doesn't exist." % (result_id,)
36
37
        return

38
39
40
41
    def create_result(self, output_file, control_ids, experiment_ids, result_type, additional_data = {}, gfs_attributes = {}):
        # Make sure output_file exists
        if os.path.isfile(output_file):
            # Make sure that all control_ids & experiment_ids are valid
42
43
44
            # REMEMBER, these are ids for control & experiment SAMPLES
            valid_controls = [self.is_valid_sample(cid) for cid in control_ids]
            valid_experiments = [self.is_valid_sample(eid) for eid in experiment_ids]
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
            if all(valid_controls) and all(valid_experiments):
                # First, we load the output file into gfs
                with open(output_file, "r") as rh:
                    # Calling put returns the gfs id
                    gridfs_id = self.gfs.put(rh, filename=os.path.basename(output_file), **gfs_attributes)
                # Now, we create the actual result entry by combining all necessary info
                result_entry = {
                    "gridfs_id": gridfs_id,
                    "control_ids": control_ids,
                    "experiment_ids": experiment_ids,
                    "result_type": result_type
                }
                # Add additional attributes into the result_entry
                result_entry.update(additional_data)
                # Insert the entry into the database, and return the id
                result = self.db.results.insert_one(result_entry)
                return (True, "Result created successfully.", result.inserted_id)
            else:
63
                msg = "Not all input ids are valid.  The following are invalid: "
64
                for id_list, valid_list in zip([control_ids, experiment_ids], [valid_controls, valid_experiments]):
65
                    msg += ",".join([id_list[i] for i, valid in enumerate(valid_list) if not valid])
66
67
68
69
70
71
72
73
74
75
76
77
78
        else:
            msg = "Specified output_file %s does not exist." % (output_file,)
        return (False, msg, None)

    def save_bed(self, bed_file, control_ids, experiment_ids, additional_data = {}):
        # Create result_entry for bed_file
        valid, msg, result_id = self.create_result(bed_file, control_ids, experiment_ids, "bed", additional_data, gfs_attributes = {"file_type": "bed"})
        if valid:
            # Now we load the actual bed data into the bed collection.
            # Data is in a six column format
            # chr, start, end, name, score, strand
            # Load data using a list comprehension over lines,
            # then insert with insert_many()
79
            print "loading bed_data..."
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
            with open(bed_file, "r") as rh:
                bed_data = [
                    {
                        "result_id": result_id,
                        "chr": line_info[0],
                        "start": line_info[1],
                        "end": line_info[2],
                        "name": line_info[3],
                        "score": line_info[4],
                        "strand": line_info[5]
                    }
                    for line in rh.readlines()
                    for line_info in (line.split(),)
                ]
                try:
95
                    print "bed data loaded, inserting."
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
                    self.db.bed.insert_many(bed_data)
                    return (True, "Bed file successfully inserted.", result_id)
                except pymongo.errors.OperationFailure as e:
                    valid = False
                    msg = "Error inserting bed_file %s: %s" % (bed_file, e)
        return (valid, msg, None)

    def save_peak(self, peak_file, control_ids, experiment_ids, additional_data = {}):
        # Create result_entry for peak_file
        valid, msg, result_id = self.create_result(peak_file, control_ids, experiment_ids, "peak", additional_data, gfs_attributes = {"file_type": os.path.splitext(peak_file)[1][1:]})
        if valid:
            # Now we load the actual peak data into the collection
            # Data is in a 10 column format
            # chr, start, end, name, score, strand, signal_value, p_value, q_value, summit
            with open(peak_file, "r") as rh:
                peak_data = [
                    {
                        "result_id": result_id,
                        "chr": line_info[0],
                        "start": line_info[1],
                        "end": line_info[2],
                        "name": line_info[3],
                        "score": line_info[4],
                        "strand": line_info[5],
                        "signal_value": line_info[6],
                        "p_value": line_info[7],
                        "q_value": line_info[8],
                        "summit": line_info[9]
                    }
                    for line in rh.readlines()
                    for line_info in (line.split(),)
                ]
                try:
                    self.db.peak.insert_many(peak_data)
                    return (True, "Peak file successfully inserted.", result_id)
                except pymongo.errors.OperationFailure as e:
                    valid = False
                    msg = "Error inserting peak_file %s: %s" % (peak_file, e)
        return (valid, msg, None)

136
137
138
139
140
141
142
143
144
145
146
    def is_valid_sample(self, sample_accession):
        try:
            cursor = self.db.samples.find({
                "accession": sample_accession
            })
            if cursor.count() == 1:
                return True
        except pymongo.errors.OperationFailure as e:
            print "Error with sample_accession %s: %s" % (sample_accession, e)
        return False

147
148
149
150
151
152
153
154
155
156
157
158
159
    def is_valid_experiment(self, experiment_id):
        try:
            cursor = self.db.experiments.find({
                "target": {"$exists": True},
                "revoked_files.0": {"$exists": False},
                "@id": "/experiments/%s/" % (experiment_id,)
            })
            if cursor.count() == 1:
                return True
        except pymongo.errors.OperationFailure as e:
            print "Error with experiment_id %s: %s" % (experiment_id, e)
        return False

160
161
162
163
164
165
166
167
168
169
170
171
    def check_valid_samples(self):
        cursor = self.db.experiments.aggregate([
            {
                "$match": {
                    "target": {"$exists": True},
                    "revoked_files.0": {"$exists": False},
                    "assembly.0": {"$exists": True},
                    "assembly.1": {"$exists": False}
                }
            },
            {
                "$lookup": {
172
                    "from": "samples",
173
                    "localField": "uuid",
174
175
176
177
178
179
180
181
182
183
184
185
186
                    "foreignField": "experiment_id",
                    "as": "samples"
                }
            }
        ])
        total = 0
        has_samples = 0
        for document in cursor:
            total += 1
            if len(document["samples"]) > 0:
                has_samples += 1
        return (has_samples, total)

187
188
189
190
191
192
193
194
195
196
197
198
199
200
    def get_assembly(self, experiment_id):
        valid = True
        msg = ""
        data = ""
        cursor = self.db.experiments.find({
            "target": {"$exists": True},
            "revoked_files.0": {"$exists": False},
            "assembly.0": {"$exists": True},
            "assembly.1": {"$exists": False},
            "@id": "/experiments/%s/" % (experiment_id,)
        })
        if cursor.count() == 1:
            document = cursor.next()
            data = document["assembly"][0]
aknecht2's avatar
aknecht2 committed
201
            msg = "Succesfully retrieved assembly for experiment with id '%s'.\n" % (experiment_id,)
202
203
        else:
            valid = False
aknecht2's avatar
aknecht2 committed
204
            msg = "Experiment with id '%s' does not exist.\n" % (experiment_id,)
205
206
        return (valid, msg, data)

207
208
209
210
    def get_samples(self, experiment_id):
        valid = True
        msg = ""
        data = {}
211
212
213
214
        # First, check to make sure the target experiment is valid
        if self.is_valid_experiment(experiment_id):
            # Next, we check that there is a least 1 possible control
            check3 = self.db.experiments.find({
215
216
                "target": {"$exists": True},
                "revoked_files.0": {"$exists": False},
217
218
219
                "assembly.0": {"$exists": True},
                "assembly.1": {"$exists": False},
                "possible_controls.0": {"$exists": True},
220
221
                "@id": "/experiments/%s/" % (experiment_id,)
            })
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
            if check3.count() == 1:
                # Complicated aggregtaion pipeline does the following steps:
                # 1. Find the experiment that matches the given id
                # 2. Join samples into the collection by exp_id
                # 3. Iterate through possible_controls
                # 4. Join possible_control data into control_exps
                # 5. Iterate through control_exps
                # 6. Join samples into the control_exps by exp_id
                # 7. Re-aggregate all data into arrays
                pipeline = [
                    {
                        "$match": {
                            "target": {"$exists": True},
                            "revoked_files.0": {"$exists": False},
                            "assembly.0": {"$exists": True},
                            "assembly.1": {"$exists": False},
                            "possible_controls.0": {"$exists": True},
                            "@id": "/experiments/%s/" % (experiment_id,)
240
                        }
241
242
243
244
245
246
247
                    },
                    {
                        "$lookup": {
                            "from": "samples",
                            "localField": "uuid",
                            "foreignField": "experiment_id",
                            "as": "samples"
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
278
279
                    },
                    {
                        "$unwind": "$possible_controls"
                    },
                    {
                        "$lookup": {
                            "from": "samples",
                            "localField": "possible_controls.uuid",
                            "foreignField": "experiment_id",
                            "as": "possible_controls.samples"
                        }
                    },
                    {
                        "$group": {
                            "_id": "$_id",
                            "possible_controls": {"$push": "$possible_controls"},
                            "samples": {"$push": "$samples"}
                        }
                    }
                ]
                cursor = self.db.experiments.aggregate(pipeline)
                # We should have only 1 document
                document = cursor.next()
                control_inputs = [sample for control in document["possible_controls"] for sample in control["samples"] if ("file_type" in sample and sample["file_type"] == "fastq")]
                experiment_inputs = [sample for sample in document["samples"][0] if ("file_type" in sample and sample["file_type"] == "fastq")]
                if (len(control_inputs) > 0 and len(experiment_inputs) > 0):
                    msg = "Succesfully retrieved input files for experiment with id '%s'.\n" % (experiment_id,)
                    data = {
                        "control": control_inputs,
                        "experiment": experiment_inputs
                    }
280
281
                else:
                    valid = False
282
                    msg = "Experiment with id '%s' has %s possible control inputs, and %s possible experiment inputs.\n" % (experiment_id, len(control_inputs), len(experiment_inputs))
283
284
            else:
                valid = False
285
                msg = "Experiment with id '%s' does not have possible_controls.\n" % (experiment_id,)
286
287
        else:
            valid = False
288
            msg = "Experiment with id '%s' is not valid!  It may not exist, or it may be missing required metadata.\n" % (experiment_id,)
289
        return (valid, msg, data)