<commit_before>/*
 * Copyright 2015 OpenCB
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.opencb.cellbase.mongodb.db.variation;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.mongodb.*;
import com.mongodb.util.JSON;
import org.opencb.biodata.models.feature.Region;
import org.opencb.biodata.models.variant.annotation.Clinvar;
import org.opencb.biodata.models.variant.annotation.Cosmic;
import org.opencb.biodata.models.variant.annotation.Gwas;
import org.opencb.biodata.models.variant.annotation.VariantAnnotation;
import org.opencb.biodata.models.variation.GenomicVariant;

import org.opencb.cellbase.core.db.api.variation.ClinicalDBAdaptor;
import org.opencb.cellbase.mongodb.db.MongoDBAdaptor;
import org.opencb.datastore.core.QueryOptions;
import org.opencb.datastore.core.QueryResult;
import org.opencb.datastore.mongodb.MongoDataStore;

import java.util.*;
import java.util.regex.Pattern;

/**
 * Created by antonior on 11/18/14.
 * @author <NAME> <EMAIL>
 */
public class ClinicalMongoDBAdaptor extends MongoDBAdaptor implements ClinicalDBAdaptor {


    public ClinicalMongoDBAdaptor(String species, String assembly, MongoDataStore mongoDataStore) {
        super(species, assembly, mongoDataStore);
        mongoDBCollection = mongoDataStore.getCollection("clinical");

        logger.info("ClinicalMongoDBAdaptor: in 'constructor'");
    }

    @Override
    public QueryResult first() {
        return mongoDBCollection.find(new BasicDBObject(), new QueryOptions("limit", 1));
    }

    @Override
    public QueryResult count() {
        return mongoDBCollection.count();
    }

    @Override
    public QueryResult stats() {
        return null;
    }

    @Override
    public QueryResult getAll(QueryOptions options) {
        System.out.println("options = " + options.get("exclude"));
        if(includeContains(options.getAsStringList("source"), "clinvar")) {
            return getAllClinvar(options);
        } else {
            // TODO implement!
            return new QueryResult();
        }
    }

    @Override
    public QueryResult next(String chromosome, int position, QueryOptions options) {
        return null;
    }

    @Override
    public QueryResult getAllClinvar(QueryOptions options) {
//        options.addToListOption("include", "clinvarSet");
//        options.addToListOption("include", "chromosome");
//        options.addToListOption("include", "start");
//        options.addToListOption("include", "end");
//        options.addToListOption("include", "reference");
//        options.addToListOption("include", "alternate");
//        options.addToListOption("include", "annot");
        QueryBuilder builder = QueryBuilder.start();

        builder = addClinvarFilters(builder, options);

//        List<DBObject> pipeline = new ArrayList<>();
//        pipeline = addClinvarAggregationFilters(pipeline, options);
//        DBObject fields = new BasicDBObject();
//        fields.put("clinvarSet", 1);
//        fields.put("chromosome", 1);
//        fields.put("start", 1);
//        fields.put("end", 1);
//        fields.put("reference", 1);
//        fields.put("alternate", 1);
//        fields.put("annot", 1);
//        pipeline.add(new BasicDBObject("$project", fields));



//        return executeAggregation2("", pipeline, options);
        return executeQuery("result", builder.get(), options);
//        return prepareClinvarQueryResultList(Collections.singletonList(executeQuery("result", builder.get(), options))).get(0);
    }


    private QueryBuilder addClinvarFilters(QueryBuilder builder, QueryOptions options) {
        List<DBObject> filterSteps = new ArrayList<>();
        builder.and(new BasicDBObject("clinvarSet", new BasicDBObject("$exists", 1)));
        builder = addClinvarRcvFilter(builder, options);
        builder = addClinvarRsFilter(builder, options);
        builder = addClinvarSoTermFilter(builder, options);
        builder = addClinvarTypeFilter(builder, options);
        builder = addClinvarReviewFilter(builder, options);
        builder = addClinvarClinicalSignificanceFilter(builder, options);
        builder = addClinvarRegionFilter(builder, options);
        builder = addClinvarGeneFilter(builder, options);
        builder = addClinvarPhenotypeFilter(builder, options);
//
//        // Filtering steps repeated twice to avoid undwind over all clinical records
//        pipeline.addAll(filterSteps);
////        pipeline.add(new BasicDBObject("$unwind", "$clinvarList"));
////        pipeline.addAll(filterSteps);
//        pipeline.add(new BasicDBObject("$limit", 100));

        return builder;
    }

    private QueryBuilder addClinvarPhenotypeFilter(QueryBuilder builder, QueryOptions options) {
        List<String> phenotypeList = options.getAsStringList("phenotype", "|");
        if (phenotypeList != null && phenotypeList.size() > 0) {
            logger.info("phenotype filter activated, phenotype list: "+phenotypeList.toString());

            builder = builder.and(new BasicDBObject("clinvarSet.referenceClinVarAssertion.traitSet.trait.name.elementValue.value",
                    new BasicDBObject("$in", getClinvarPhenotypeRegex(phenotypeList))));

        }
        return builder;
    }

    private QueryBuilder addClinvarGeneFilter(QueryBuilder builder, QueryOptions options) {
//        List<String> geneList = (List<String>) options.get("gene");
        List<String> geneList = options.getAsStringList("gene");
        if (geneList != null && geneList.size() > 0) {
            logger.info("gene filter activated, gene list: " + geneList.toString());
            builder = builder.and(new BasicDBObject("clinvarSet.referenceClinVarAssertion.measureSet.measure.measureRelationship.symbol.elementValue.value",
                    new BasicDBObject("$in", geneList)));
        }
        return builder;
    }

    private QueryBuilder addClinvarRegionFilter(QueryBuilder builder, QueryOptions options) {
        List<Region> regionList = Region.parseRegions((String) options.get("region"));<commit_msg>mongodb: ClinicalMongoDBAdaptor phenotype filter now splits by '|' instead of ';', fixes #110<commit_after>/*
 * Copyright 2015 OpenCB
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.opencb.cellbase.mongodb.db.variation;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.mongodb.*;
import com.mongodb.util.JSON;
import org.opencb.biodata.models.feature.Region;
import org.opencb.biodata.models.variant.annotation.Clinvar;
import org.opencb.biodata.models.variant.annotation.Cosmic;
import org.opencb.biodata.models.variant.annotation.Gwas;
import org.opencb.biodata.models.variant.annotation.VariantAnnotation;
import org.opencb.biodata.models.variation.GenomicVariant;

import org.opencb.cellbase.core.db.api.variation.ClinicalDBAdaptor;
import org.opencb.cellbase.mongodb.db.MongoDBAdaptor;
import org.opencb.datastore.core.QueryOptions;
import org.opencb.datastore.core.QueryResult;
import org.opencb.datastore.mongodb.MongoDataStore;

import java.util.*;
import java.util.regex.Pattern;

/**
 * Created by antonior on 11/18/14.
 * @author <NAME> <EMAIL>
 */
public class ClinicalMongoDBAdaptor extends MongoDBAdaptor implements ClinicalDBAdaptor {


    public ClinicalMongoDBAdaptor(String species, String assembly, MongoDataStore mongoDataStore) {
        super(species, assembly, mongoDataStore);
        mongoDBCollection = mongoDataStore.getCollection("clinical");

        logger.info("ClinicalMongoDBAdaptor: in 'constructor'");
    }

    @Override
    public QueryResult first() {
        return mongoDBCollection.find(new BasicDBObject(), new QueryOptions("limit", 1));
    }

    @Override
    public QueryResult count() {
        return mongoDBCollection.count();
    }

    @Override
    public QueryResult stats() {
        return null;
    }

    @Override
    public QueryResult getAll(QueryOptions options) {
        System.out.println("options = " + options.get("exclude"));
        if(includeContains(options.getAsStringList("source"), "clinvar")) {
            return getAllClinvar(options);
        } else {
            // TODO implement!
            return new QueryResult();
        }
    }

    @Override
    public QueryResult next(String chromosome, int position, QueryOptions options) {
        return null;
    }

    @Override
    public QueryResult getAllClinvar(QueryOptions options) {
//        options.addToListOption("include", "clinvarSet");
//        options.addToListOption("include", "chromosome");
//        options.addToListOption("include", "start");
//        options.addToListOption("include", "end");
//        options.addToListOption("include", "reference");
//        options.addToListOption("include", "alternate");
//        options.addToListOption("include", "annot");
        QueryBuilder builder = QueryBuilder.start();

        builder = addClinvarFilters(builder, options);

//        List<DBObject> pipeline = new ArrayList<>();
//        pipeline = addClinvarAggregationFilters(pipeline, options);
//        DBObject fields = new BasicDBObject();
//        fields.put("clinvarSet", 1);
//        fields.put("chromosome", 1);
//        fields.put("start", 1);
//        fields.put("end", 1);
//        fields.put("reference", 1);
//        fields.put("alternate", 1);
//        fields.put("annot", 1);
//        pipeline.add(new BasicDBObject("$project", fields));



//        return executeAggregation2("", pipeline, options);
        return executeQuery("result", builder.get(), options);
//        return prepareClinvarQueryResultList(Collections.singletonList(executeQuery("result", builder.get(), options))).get(0);
    }


    private QueryBuilder addClinvarFilters(QueryBuilder builder, QueryOptions options) {
        List<DBObject> filterSteps = new ArrayList<>();
        builder.and(new BasicDBObject("clinvarSet", new BasicDBObject("$exists", 1)));
        builder = addClinvarRcvFilter(builder, options);
        builder = addClinvarRsFilter(builder, options);
        builder = addClinvarSoTermFilter(builder, options);
        builder = addClinvarTypeFilter(builder, options);
        builder = addClinvarReviewFilter(builder, options);
        builder = addClinvarClinicalSignificanceFilter(builder, options);
        builder = addClinvarRegionFilter(builder, options);
        builder = addClinvarGeneFilter(builder, options);
        builder = addClinvarPhenotypeFilter(builder, options);
//
//        // Filtering steps repeated twice to avoid undwind over all clinical records
//        pipeline.addAll(filterSteps);
////        pipeline.add(new BasicDBObject("$unwind", "$clinvarList"));
////        pipeline.addAll(filterSteps);
//        pipeline.add(new BasicDBObject("$limit", 100));

        return builder;
    }

    private QueryBuilder addClinvarPhenotypeFilter(QueryBuilder builder, QueryOptions options) {
        List<String> phenotypeList = options.getAsStringList("phenotype", "\\|");
        if (phenotypeList != null && phenotypeList.size() > 0) {
            logger.info("phenotype filter activated, phenotype list: "+phenotypeList.toString());

            builder = builder.and(new BasicDBObject("clinvarSet.referenceClinVarAssertion.traitSet.trait.name.elementValue.value",
                    new BasicDBObject("$in", getClinvarPhenotypeRegex(phenotypeList))));

        }
        return builder;
    }

    private QueryBuilder addClinvarGeneFilter(QueryBuilder builder, QueryOptions options) {
//        List<String> geneList = (List<String>) options.get("gene");
        List<String> geneList = options.getAsStringList("gene");
        if (geneList != null && geneList.size() > 0) {
            logger.info("gene filter activated, gene list: " + geneList.toString());
            builder = builder.and(new BasicDBObject("clinvarSet.referenceClinVarAssertion.measureSet.measure.measureRelationship.symbol.elementValue.value",
                    new BasicDBObject("$in", geneList)));
        }
        return builder;
    }

    private QueryBuilder addClinvarRegionFilter(QueryBuilder builder, QueryOptions options) {
        List<Region> regionList = Region.parseRegions((String) options.get("region"));
{'fraction_non_alphanumeric': 0.11804742388758782, 'fraction_numerical': 0.004610655737704918, 'mean_word_length': 3.571763131482101, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 10}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4235659', 'n_tokens_mistral': 3956, 'n_tokens_neox': 3754, 'n_words': 813}