示例#1
0
 def __init__(self,
              localId,
              referenceSet,
              randomSeed=0,
              numVariantSets=1,
              numCalls=1,
              variantDensity=0.5,
              numReadGroupSets=1,
              numReadGroupsPerReadGroupSet=1,
              numAlignments=1,
              numFeatureSets=1):
     super(SimulatedDataset, self).__init__(localId)
     self._description = "Simulated dataset {}".format(localId)
     # TODO create a simulated Ontology
     # Variants
     for i in range(numVariantSets):
         localId = "simVs{}".format(i)
         seed = randomSeed + i
         variantSet = variants.SimulatedVariantSet(self, referenceSet,
                                                   localId, seed, numCalls,
                                                   variantDensity)
         callSets = variantSet.getCallSets()
         # Add biosamples
         for callSet in callSets:
             bioSample = biodata.BioSample(self, callSet.getLocalId())
             bioSample2 = biodata.BioSample(self,
                                            callSet.getLocalId() + "2")
             individual = biodata.Individual(self, callSet.getLocalId())
             bioSample.setIndividualId(individual.getId())
             bioSample2.setIndividualId(individual.getId())
             self.addIndividual(individual)
             self.addBioSample(bioSample)
             self.addBioSample(bioSample2)
         self.addVariantSet(variantSet)
         variantAnnotationSet = variants.SimulatedVariantAnnotationSet(
             variantSet, "simVas{}".format(i), seed)
         variantSet.addVariantAnnotationSet(variantAnnotationSet)
     # Reads
     for i in range(numReadGroupSets):
         localId = 'simRgs{}'.format(i)
         seed = randomSeed + i
         readGroupSet = reads.SimulatedReadGroupSet(
             self, localId, referenceSet, seed,
             numReadGroupsPerReadGroupSet, numAlignments)
         for rg in readGroupSet.getReadGroups():
             bioSample = biodata.BioSample(self, rg.getLocalId())
             individual = biodata.Individual(self, rg.getLocalId())
             bioSample.setIndividualId(individual.getId())
             rg.setBioSampleId(bioSample.getId())
             self.addIndividual(individual)
             self.addBioSample(bioSample)
         self.addReadGroupSet(readGroupSet)
     # Features
     for i in range(numFeatureSets):
         localId = "simFs{}".format(i)
         seed = randomSeed + i
         featureSet = sequenceAnnotations.SimulatedFeatureSet(
             self, localId, seed)
         featureSet.setReferenceSet(referenceSet)
         self.addFeatureSet(featureSet)
示例#2
0
 def addBioSample(self):
     """
     Adds a new biosample into this repo
     """
     self._openRepo()
     dataset = self._repo.getDatasetByName(self._args.datasetName)
     bioSample = bio_metadata.BioSample(
         dataset, self._args.bioSampleName)
     bioSample.populateFromJson(self._args.bioSample)
     self._updateRepo(self._repo.insertBioSample, bioSample)
示例#3
0
 def _readBioSampleTable(self, cursor):
     cursor.row_factory = sqlite3.Row
     cursor.execute("SELECT * FROM BioSample;")
     for row in cursor:
         dataset = self.getDataset(row[b'datasetId'])
         bioSample = biodata.BioSample(
             dataset, row[b'name'])
         bioSample.populateFromRow(row)
         assert bioSample.getId() == row[b'id']
         dataset.addBioSample(bioSample)
示例#4
0
 def testToProtocolElement(self):
     dataset = datasets.Dataset('dataset1')
     # Write out a valid input
     validBioSample = protocol.BioSample(name="test",
                                         created="2016-05-19T21:00:19Z",
                                         updated="2016-05-19T21:00:19Z")
     validBioSample.info['test'].values.add().string_value = 'test-info'
     # pass through protocol creation
     bioSample = bioMetadata.BioSample(dataset, "test")
     bioSample.populateFromJson(protocol.toJson(validBioSample))
     gaBioSample = bioSample.toProtocolElement()
     # Verify elements exist
     self.assertEqual(gaBioSample.created, validBioSample.created)
     self.assertEqual(gaBioSample.updated, validBioSample.updated)
     # Invalid input
     invalidBioSample = '{"bad:", "json"}'
     bioSample = bioMetadata.Individual(dataset, "test")
     # Should fail
     self.assertRaises(exceptions.InvalidJsonException,
                       bioSample.populateFromJson, invalidBioSample)
    def run(self):
        if not os.path.exists(self.outputDirectory):
            os.makedirs(self.outputDirectory)
        self.repo.open("w")
        self.repo.initialise()

        referenceFileName = "ref_brca1.fa"
        inputRef = os.path.join(
            self.inputDirectory, referenceFileName)
        outputRef = os.path.join(
            self.outputDirectory, referenceFileName)
        shutil.copy(inputRef, outputRef)
        fastaFilePath = os.path.join(
            self.outputDirectory,
            referenceFileName + '.gz')
        pysam.tabix_compress(
            outputRef, fastaFilePath)

        with open(
                os.path.join(
                    self.inputDirectory, "ref_brca1.json")) as refMetadataFile:
            refMetadata = json.load(refMetadataFile)
        with open(
                os.path.join(
                    self.inputDirectory,
                    "referenceset_hg37.json")) as refMetadataFile:
            refSetMetadata = json.load(refMetadataFile)

        referenceSet = references.HtslibReferenceSet(
            refSetMetadata['assemblyId'])

        referenceSet.populateFromFile(fastaFilePath)
        referenceSet.setAssemblyId(refSetMetadata['assemblyId'])
        referenceSet.setDescription(refSetMetadata['description'])
        referenceSet.setNcbiTaxonId(refSetMetadata['ncbiTaxonId'])
        referenceSet.setIsDerived(refSetMetadata['isDerived'])
        referenceSet.setSourceUri(refSetMetadata['sourceUri'])
        referenceSet.setSourceAccessions(refSetMetadata['sourceAccessions'])
        for reference in referenceSet.getReferences():
            reference.setNcbiTaxonId(refMetadata['ncbiTaxonId'])
            reference.setSourceAccessions(
                refMetadata['sourceAccessions'])
        self.repo.insertReferenceSet(referenceSet)

        dataset = datasets.Dataset("brca1")
        self.repo.insertDataset(dataset)

        hg00096Individual = biodata.Individual(dataset, "HG00096")
        with open(
                os.path.join(
                    self.inputDirectory,
                    "individual_HG00096.json")) as jsonString:
            hg00096Individual.populateFromJson(jsonString.read())
        self.repo.insertIndividual(hg00096Individual)
        hg00096BioSample = biodata.BioSample(dataset, "HG00096")
        with open(
                os.path.join(
                    self.inputDirectory,
                    "bioSample_HG00096.json")) as jsonString:
            hg00096BioSample.populateFromJson(jsonString.read())
        hg00096BioSample.setIndividualId(hg00096Individual.getId())
        self.repo.insertBioSample(hg00096BioSample)
        hg00099Individual = biodata.Individual(dataset, "HG00099")
        with open(
                os.path.join(
                    self.inputDirectory,
                    "individual_HG00099.json")) as jsonString:
            hg00099Individual.populateFromJson(jsonString.read())
        self.repo.insertIndividual(hg00099Individual)
        hg00099BioSample = biodata.BioSample(dataset, "HG00099")
        with open(
                os.path.join(
                    self.inputDirectory,
                    "bioSample_HG00099.json")) as jsonString:
            hg00099BioSample.populateFromJson(jsonString.read())
        hg00099BioSample.setIndividualId(hg00099Individual.getId())
        self.repo.insertBioSample(hg00099BioSample)
        hg00101Individual = biodata.Individual(dataset, "HG00101")
        with open(
                os.path.join(
                    self.inputDirectory,
                    "individual_HG00101.json")) as jsonString:
            hg00101Individual.populateFromJson(jsonString.read())
        self.repo.insertIndividual(hg00101Individual)
        hg00101BioSample = biodata.BioSample(dataset, "HG00101")
        with open(
                os.path.join(
                    self.inputDirectory,
                    "bioSample_HG00101.json")) as jsonString:
            hg00101BioSample.populateFromJson(jsonString.read())
        hg00101BioSample.setIndividualId(hg00101Individual.getId())
        self.repo.insertBioSample(hg00101BioSample)

        readFiles = [
            "brca1_HG00096.sam",
            "brca1_HG00099.sam",
            "brca1_HG00101.sam"]

        for readFile in readFiles:
            name = readFile.split('_')[1].split('.')[0]
            readSrc = pysam.AlignmentFile(
                os.path.join(self.inputDirectory, readFile), "r")
            readDest = pysam.AlignmentFile(
                os.path.join(
                    self.outputDirectory,
                    name + ".bam"),
                "wb", header=readSrc.header)
            destFilePath = readDest.filename
            for readData in readSrc:
                readDest.write(readData)
            readDest.close()
            readSrc.close()
            pysam.index(destFilePath)
            readGroupSet = reads.HtslibReadGroupSet(dataset, name)
            readGroupSet.populateFromFile(destFilePath, destFilePath + ".bai")
            readGroupSet.setReferenceSet(referenceSet)
            bioSamples = [hg00096BioSample, hg00099BioSample, hg00101BioSample]
            for readGroup in readGroupSet.getReadGroups():
                for bioSample in bioSamples:
                    if bioSample.getLocalId() == readGroup.getSampleName():
                        readGroup.setBioSampleId(bioSample.getId())
            self.repo.insertReadGroupSet(readGroupSet)

        ontologyMapFileName = "so-xp-simple.obo"
        inputOntologyMap = os.path.join(
            self.inputDirectory, ontologyMapFileName)
        outputOntologyMap = os.path.join(
            self.outputDirectory, ontologyMapFileName)
        shutil.copy(inputOntologyMap, outputOntologyMap)

        sequenceOntology = ontologies.Ontology("so-xp-simple")
        sequenceOntology.populateFromFile(outputOntologyMap)
        sequenceOntology._id = "so-xp-simple"
        self.repo.insertOntology(sequenceOntology)
        self.repo.addOntology(sequenceOntology)

        vcfFiles = [
            "brca1_1kgPhase3_variants.vcf",
            "brca1_WASH7P_annotation.vcf",
            "brca1_OR4F_annotation.vcf"]
        for vcfFile in vcfFiles:
            self.addVariantSet(
                vcfFile,
                dataset,
                referenceSet,
                sequenceOntology,
                bioSamples)

        seqAnnFile = "brca1_gencodev19.gff3"
        seqAnnSrc = os.path.join(self.inputDirectory, seqAnnFile)
        seqAnnDest = os.path.join(self.outputDirectory, "gencodev19.db")
        dbgen = generate_gff3_db.Gff32Db(seqAnnSrc, seqAnnDest)
        dbgen.run()
        gencode = sequenceAnnotations.Gff3DbFeatureSet(dataset, "gencodev19")
        gencode.setOntology(sequenceOntology)
        gencode.populateFromFile(seqAnnDest)
        gencode.setReferenceSet(referenceSet)

        self.repo.insertFeatureSet(gencode)

        self.repo.commit()

        print("Done converting compliance data.", file=sys.stderr)
    def run(self):
        if not os.path.exists(self.outputDirectory):
            os.makedirs(self.outputDirectory)
        self.repo.open("w")
        self.repo.initialise()

        referenceFileName = "ref_brca1.fa"
        inputRef = os.path.join(self.inputDirectory, referenceFileName)
        outputRef = os.path.join(self.outputDirectory, referenceFileName)
        shutil.copy(inputRef, outputRef)
        fastaFilePath = os.path.join(self.outputDirectory,
                                     referenceFileName + '.gz')
        pysam.tabix_compress(outputRef, fastaFilePath)

        with open(os.path.join(self.inputDirectory,
                               "ref_brca1.json")) as refMetadataFile:
            refMetadata = json.load(refMetadataFile)
        with open(os.path.join(self.inputDirectory,
                               "referenceset_hg37.json")) as refMetadataFile:
            refSetMetadata = json.load(refMetadataFile)

        referenceSet = references.HtslibReferenceSet(
            refSetMetadata['assemblyId'])

        referenceSet.populateFromFile(fastaFilePath)
        referenceSet.setAssemblyId(refSetMetadata['assemblyId'])
        referenceSet.setDescription(refSetMetadata['description'])
        referenceSet.setNcbiTaxonId(refSetMetadata['ncbiTaxonId'])
        referenceSet.setIsDerived(refSetMetadata['isDerived'])
        referenceSet.setSourceUri(refSetMetadata['sourceUri'])
        referenceSet.setSourceAccessions(refSetMetadata['sourceAccessions'])
        for reference in referenceSet.getReferences():
            reference.setNcbiTaxonId(refMetadata['ncbiTaxonId'])
            reference.setSourceAccessions(refMetadata['sourceAccessions'])
        self.repo.insertReferenceSet(referenceSet)

        dataset = datasets.Dataset("brca1")
        # Some info is set, it isn't important what
        dataset.setInfo({"version": ga4gh.__version__})
        self.repo.insertDataset(dataset)

        hg00096Individual = biodata.Individual(dataset, "HG00096")
        with open(os.path.join(self.inputDirectory,
                               "individual_HG00096.json")) as jsonString:
            hg00096Individual.populateFromJson(jsonString.read())
        self.repo.insertIndividual(hg00096Individual)
        hg00096BioSample = biodata.BioSample(dataset, "HG00096")
        with open(os.path.join(self.inputDirectory,
                               "bioSample_HG00096.json")) as jsonString:
            hg00096BioSample.populateFromJson(jsonString.read())
        hg00096BioSample.setIndividualId(hg00096Individual.getId())
        self.repo.insertBioSample(hg00096BioSample)
        hg00099Individual = biodata.Individual(dataset, "HG00099")
        with open(os.path.join(self.inputDirectory,
                               "individual_HG00099.json")) as jsonString:
            hg00099Individual.populateFromJson(jsonString.read())
        self.repo.insertIndividual(hg00099Individual)
        hg00099BioSample = biodata.BioSample(dataset, "HG00099")
        with open(os.path.join(self.inputDirectory,
                               "bioSample_HG00099.json")) as jsonString:
            hg00099BioSample.populateFromJson(jsonString.read())
        hg00099BioSample.setIndividualId(hg00099Individual.getId())
        self.repo.insertBioSample(hg00099BioSample)
        hg00101Individual = biodata.Individual(dataset, "HG00101")
        with open(os.path.join(self.inputDirectory,
                               "individual_HG00101.json")) as jsonString:
            hg00101Individual.populateFromJson(jsonString.read())
        self.repo.insertIndividual(hg00101Individual)
        hg00101BioSample = biodata.BioSample(dataset, "HG00101")
        with open(os.path.join(self.inputDirectory,
                               "bioSample_HG00101.json")) as jsonString:
            hg00101BioSample.populateFromJson(jsonString.read())
        hg00101BioSample.setIndividualId(hg00101Individual.getId())
        self.repo.insertBioSample(hg00101BioSample)

        readFiles = [
            "brca1_HG00096.sam", "brca1_HG00099.sam", "brca1_HG00101.sam"
        ]

        for readFile in readFiles:
            name = readFile.split('_')[1].split('.')[0]
            readSrc = pysam.AlignmentFile(
                os.path.join(self.inputDirectory, readFile), "r")
            readDest = pysam.AlignmentFile(os.path.join(
                self.outputDirectory, name + ".bam"),
                                           "wb",
                                           header=readSrc.header)
            destFilePath = readDest.filename
            for readData in readSrc:
                readDest.write(readData)
            readDest.close()
            readSrc.close()
            pysam.index(destFilePath)
            readGroupSet = reads.HtslibReadGroupSet(dataset, name)
            readGroupSet.populateFromFile(destFilePath, destFilePath + ".bai")
            readGroupSet.setReferenceSet(referenceSet)
            dataset.addReadGroupSet(readGroupSet)
            bioSamples = [hg00096BioSample, hg00099BioSample, hg00101BioSample]
            for readGroup in readGroupSet.getReadGroups():
                for bioSample in bioSamples:
                    if bioSample.getLocalId() == readGroup.getSampleName():
                        readGroup.setBioSampleId(bioSample.getId())
            self.repo.insertReadGroupSet(readGroupSet)

        ontologyMapFileName = "so-xp-simple.obo"
        inputOntologyMap = os.path.join(self.inputDirectory,
                                        ontologyMapFileName)
        outputOntologyMap = os.path.join(self.outputDirectory,
                                         ontologyMapFileName)
        shutil.copy(inputOntologyMap, outputOntologyMap)

        sequenceOntology = ontologies.Ontology("so-xp-simple")
        sequenceOntology.populateFromFile(outputOntologyMap)
        sequenceOntology._id = "so-xp-simple"
        self.repo.insertOntology(sequenceOntology)
        self.repo.addOntology(sequenceOntology)

        vcfFiles = [
            "brca1_1kgPhase3_variants.vcf", "brca1_WASH7P_annotation.vcf",
            "brca1_OR4F_annotation.vcf"
        ]
        for vcfFile in vcfFiles:
            self.addVariantSet(vcfFile, dataset, referenceSet,
                               sequenceOntology, bioSamples)

        # Sequence annotations
        seqAnnFile = "brca1_gencodev19.gff3"
        seqAnnSrc = os.path.join(self.inputDirectory, seqAnnFile)
        seqAnnDest = os.path.join(self.outputDirectory, "gencodev19.db")
        dbgen = generate_gff3_db.Gff32Db(seqAnnSrc, seqAnnDest)
        dbgen.run()
        gencode = sequence_annotations.Gff3DbFeatureSet(dataset, "gencodev19")
        gencode.setOntology(sequenceOntology)
        gencode.populateFromFile(seqAnnDest)
        gencode.setReferenceSet(referenceSet)

        self.repo.insertFeatureSet(gencode)

        # add g2p featureSet
        g2pPath = os.path.join(self.inputDirectory, "cgd")
        # copy all files input directory to output path
        outputG2PPath = os.path.join(self.outputDirectory, "cgd")
        os.makedirs(outputG2PPath)
        for filename in glob.glob(os.path.join(g2pPath, '*.*')):
            shutil.copy(filename, outputG2PPath)

        featuresetG2P = g2p_featureset.PhenotypeAssociationFeatureSet(
            dataset, outputG2PPath)
        featuresetG2P.setOntology(sequenceOntology)
        featuresetG2P.setReferenceSet(referenceSet)
        featuresetG2P.populateFromFile(outputG2PPath)
        self.repo.insertFeatureSet(featuresetG2P)

        # add g2p phenotypeAssociationSet
        phenotypeAssociationSet = g2p_associationset\
            .RdfPhenotypeAssociationSet(dataset, "cgd", outputG2PPath)
        self.repo.insertPhenotypeAssociationSet(phenotypeAssociationSet)

        self.repo.commit()
        dataset.addFeatureSet(gencode)

        # RNA Quantification
        rnaDbName = os.path.join(self.outputDirectory, "rnaseq.db")
        store = rnaseq2ga.RnaSqliteStore(rnaDbName)
        store.createTables()
        rnaseq2ga.rnaseq2ga(self.inputDirectory + "/rna_brca1.tsv",
                            rnaDbName,
                            "rna_brca1.tsv",
                            "rsem",
                            featureType="transcript",
                            readGroupSetNames="HG00096",
                            featureSetNames="gencodev19",
                            dataset=dataset)
        rnaQuantificationSet = rna_quantification.SqliteRnaQuantificationSet(
            dataset, "rnaseq")
        rnaQuantificationSet.setReferenceSet(referenceSet)
        rnaQuantificationSet.populateFromFile(rnaDbName)
        self.repo.insertRnaQuantificationSet(rnaQuantificationSet)

        self.repo.commit()