<commit_before>"""
Copyright (C) 2015  Genome Research Ltd.

Author: <NAME> <<EMAIL>>

This program is part of metadata-check

metadata-check is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

This file has been created on Nov 09, 2015.
"""

from collections import defaultdict
import collections
from typing import List

from sequencescape import NamedModel, Sample, Study, Library
from mcheck.results.checks_results import CheckResult
from mcheck.results.constants import SEVERITY


class SeqscapeEntityQueryAndResults:
    def __init__(self, entities_fetched: NamedModel, query_ids: List, query_id_type: str, query_entity_type: str,
                 fetched_entity_type: str):
        """
        This is a class used to store data retrieved from Sequencescape DB.
        It holds entities are fetched from Seqscape when querying by a list of ids of type query_id_type.
        :param entities_fetched: entities fetched from Seqscape
        :param query_id_type: a type of id - e.g. "accession_number", "internal_id", "name"
        :param query_ids: a list of strings = the list of ids that Seqscape was queried by,
        :return:
        """
        if type(entities_fetched) == list:
            self.entities_fetched = entities_fetched
        else:
            self.entities_fetched = [entities_fetched]
        self.query_ids = [str(id) for id in query_ids]
        self.query_id_type = query_id_type
        self.query_entity_type = query_entity_type
        self.fetched_entity_type = fetched_entity_type

    def _find_missing_ids(self) -> List:
        ids_found = [str(getattr(ent, self.query_id_type)) for ent in self.entities_fetched]
        ids_missing = list(set(self.query_ids).difference(set(ids_found)))
        return ids_missing

    def _find_duplicated_ids(self) -> List:
        ids_found = [str(getattr(ent, self.query_id_type)) for ent in self.entities_fetched]
        ids_duplicated = [item for item, count in collections.Counter(ids_found).items() if count > 1]
        return ids_duplicated

    def check_all_ids_were_found(self) -> List:
        problems = []
        ids_missing = self._find_missing_ids()
        if ids_missing:
            problems.append(CheckResult(check_name="Check all ids were found",
                                        error_message="The following ids weren't found in SequencescapeDB: %s " %
                                                      ids_missing))
        return problems

    def check_no_duplicates_found(self) -> List:
        problems = []
        ids_dupl = self._find_duplicated_ids()
        if ids_dupl:
            entities_dupl = [ent for ent in self.entities_fetched if getattr(ent, self.query_id_type) in ids_dupl]
            problems.append(CheckResult("Check for duplicated ids",
                                        error_message="The following ids: %s are duplicated - entities: %s" % (
                                            ids_dupl, entities_dupl)))
        return problems


    def __str__(self):
        return str(self.query_entity_type) + " ID type: " + str(self.query_id_type) + ", query_ids =  " + \
               str(self.query_ids) + ", fetched entities: " + str(self.entities_fetched)

    def __repr__(self):
        return self.__str__()

    def __eq__(self, other):
        if not type(self) is type(other):
            return False
        return self.query_id_type == other.query_id_type and self.query_ids == other.query_ids and \
               self.entities_fetched == other.entities_fetched and self.query_entity_type == other.query_entity_type

    def __hash__(self):
        return hash(frozenset(self.entities_fetched))


class SeqscapeRawMetadata(object):
    """
    This class holds the metadata fetched from sequencescapeDB before being tested for sanity on its own.
    """

    def __init__(self):
        """
        Constructor - initializez the internal field keeping all the entities by entity type.
        _entities_dict_by_type = { 'sample' : [SeqscapeEntitiesFetchedByIdType(), SeqscapeEntitiesFetchedByIdType(),..]}
        _entities_fetched_by_association = {('sample', 'study'): [SeqscapeEntitiesFetchedBasedOnIds(), ..]}
        :return:
        """
        self._entities_dict_by_type = defaultdict(list)
        self._entities_fetched_by_association = defaultdict(
            list)  # key: tuple(entity_queried_type, entity_fetched_type)

    def add_fetched_entities(self, query_results: SeqscapeEntityQueryAndResults):
        """
        :param query_results: SeqscapeEntitiesFetchedByIdType object
        :param entity_type: str = the type of entity, can be 'sample', or 'library' or 'study'
        :return:
        """
        if query_results:
            entity_type = query_results.fetched_entity_type
            self._entities_dict_by_type[entity_type].append(query_results)

    def add_all_fetched_entities(self, query_results: List[SeqscapeEntityQueryAndResults]):
        if query_results:
            entity_type = query_results[0].fetched_entity_type
            self._entities_dict_by_type[entity_type].extend(query_results)

    def add_fetched_entities_by_association(self, query_results: SeqscapeEntityQueryAndResults) -> None:
        """
        This method adds a new entry in the dict of entities fetched from Seqscape in association with others.
        :param query_results: list[SeqscapeEntitiesFetchedBasedOnIds] to be added to the internal dict
        :return:
        """
        if query_results and not type(query_results) == SeqscapeEntityQueryAndResults:
            raise ValueError("Expected SeqscapeEntitiesFetched type and got: %s " % str(type(query_results)))
        if query_results:
            entity_type = (query_results.query_entity_type, query_results.fetched_entity_type)
            self._entities_fetched_by_association[entity_type].append(query_results)

    def get_fetched_entities_by_type(self, entity_type: str):
        return self._entities_dict_by_type[entity_type]

    def get_entities_by_type(self, entity_type: str):
        results = []
        for entities in self._entities_dict_by_type[entity_type]:
            results.extend(entities.entities_fetched)
        return results


    def get_entities_without_duplicates_by_entity_type(self, entity_type: str) -> List[NamedModel]:
        entities_by_type = self.get_entities_by_type(entity_type)
        all_entities = set(entities_by_type)
        return all_entities


    def get_all_fetched_entity_types(self) -> List[str]:
        return list(self._entities_dict_by_type.keys())

    def get_all_entities_from_query_results(self) -> List[NamedModel]:
        """
        Returns a list of SeqscapeEntitiesFetchedBasedOnIds for all the entity types concatenated together.
        """
        res = []
        for v in self._entities_dict_by_type.values():
            res.extend(v)
        return res


    def get_all_fetched_entities_by_association(self) -> List[SeqscapeEntityQueryAndResults]:
        return self._entities_fetched_by_association

    def get_all_fetched_entities_by_association_by_type(self, query_entity_type, fetched_entity_type):
        return self._entities_fetched_by_association[(query_entity_type, fetched_entity_type)]

    def get_all_entities_by_association_by_type(self, query_entity_type: str, fetched_entity_type:str) -> List[
        SeqscapeEntityQueryAndResults]:
        query_results = self._entities_fetched_by_association[(query_entity_type, fetched_entity_type)]
        res = []
        for v in query_results:<commit_msg>Added docs for a method<commit_after>"""
Copyright (C) 2015  Genome Research Ltd.

Author: <NAME> <<EMAIL>>

This program is part of metadata-check

metadata-check is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

This file has been created on Nov 09, 2015.
"""

from collections import defaultdict
import collections
from typing import List

from sequencescape import NamedModel, Sample, Study, Library
from mcheck.results.checks_results import CheckResult
from mcheck.results.constants import SEVERITY


class SeqscapeEntityQueryAndResults:
    def __init__(self, entities_fetched: NamedModel, query_ids: List, query_id_type: str, query_entity_type: str,
                 fetched_entity_type: str):
        """
        This is a class used to store data retrieved from Sequencescape DB.
        It holds entities are fetched from Seqscape when querying by a list of ids of type query_id_type.
        :param entities_fetched: entities fetched from Seqscape
        :param query_id_type: a type of id - e.g. "accession_number", "internal_id", "name"
        :param query_ids: a list of strings = the list of ids that Seqscape was queried by,
        :return:
        """
        if type(entities_fetched) == list:
            self.entities_fetched = entities_fetched
        else:
            self.entities_fetched = [entities_fetched]
        self.query_ids = [str(id) for id in query_ids]
        self.query_id_type = query_id_type
        self.query_entity_type = query_entity_type
        self.fetched_entity_type = fetched_entity_type

    def _find_missing_ids(self) -> List:
        ids_found = [str(getattr(ent, self.query_id_type)) for ent in self.entities_fetched]
        ids_missing = list(set(self.query_ids).difference(set(ids_found)))
        return ids_missing

    def _find_duplicated_ids(self) -> List:
        ids_found = [str(getattr(ent, self.query_id_type)) for ent in self.entities_fetched]
        ids_duplicated = [item for item, count in collections.Counter(ids_found).items() if count > 1]
        return ids_duplicated

    def check_all_ids_were_found(self) -> List:
        problems = []
        ids_missing = self._find_missing_ids()
        if ids_missing:
            problems.append(CheckResult(check_name="Check all ids were found",
                                        error_message="The following ids weren't found in SequencescapeDB: %s " %
                                                      ids_missing))
        return problems

    def check_no_duplicates_found(self) -> List:
        problems = []
        ids_dupl = self._find_duplicated_ids()
        if ids_dupl:
            entities_dupl = [ent for ent in self.entities_fetched if getattr(ent, self.query_id_type) in ids_dupl]
            problems.append(CheckResult("Check for duplicated ids",
                                        error_message="The following ids: %s are duplicated - entities: %s" % (
                                            ids_dupl, entities_dupl)))
        return problems


    def __str__(self):
        return str(self.query_entity_type) + " ID type: " + str(self.query_id_type) + ", query_ids =  " + \
               str(self.query_ids) + ", fetched entities: " + str(self.entities_fetched)

    def __repr__(self):
        return self.__str__()

    def __eq__(self, other):
        if not type(self) is type(other):
            return False
        return self.query_id_type == other.query_id_type and self.query_ids == other.query_ids and \
               self.entities_fetched == other.entities_fetched and self.query_entity_type == other.query_entity_type

    def __hash__(self):
        return hash(frozenset(self.entities_fetched))


class SeqscapeRawMetadata(object):
    """
    This class holds the metadata fetched from sequencescapeDB before being tested for sanity on its own.
    """

    def __init__(self):
        """
        Constructor - initializez the internal field keeping all the entities by entity type.
        _entities_dict_by_type = { 'sample' : [SeqscapeEntitiesFetchedByIdType(), SeqscapeEntitiesFetchedByIdType(),..]}
        _entities_fetched_by_association = {('sample', 'study'): [SeqscapeEntitiesFetchedBasedOnIds(), ..]}
        :return:
        """
        self._entities_dict_by_type = defaultdict(list)
        self._entities_fetched_by_association = defaultdict(
            list)  # key: tuple(entity_queried_type, entity_fetched_type)

    def add_fetched_entities(self, query_results: SeqscapeEntityQueryAndResults):
        """
        :param query_results: SeqscapeEntitiesFetchedByIdType object
        :param entity_type: str = the type of entity, can be 'sample', or 'library' or 'study'
        :return:
        """
        if query_results:
            entity_type = query_results.fetched_entity_type
            self._entities_dict_by_type[entity_type].append(query_results)

    def add_all_fetched_entities(self, query_results: List[SeqscapeEntityQueryAndResults]):
        if query_results:
            entity_type = query_results[0].fetched_entity_type
            self._entities_dict_by_type[entity_type].extend(query_results)

    def add_fetched_entities_by_association(self, query_results: SeqscapeEntityQueryAndResults) -> None:
        """
        This method adds a new entry in the dict of entities fetched from Seqscape in association with others.
        :param query_results: list[SeqscapeEntitiesFetchedBasedOnIds] to be added to the internal dict
        :return:
        """
        if query_results and not type(query_results) == SeqscapeEntityQueryAndResults:
            raise ValueError("Expected SeqscapeEntitiesFetched type and got: %s " % str(type(query_results)))
        if query_results:
            entity_type = (query_results.query_entity_type, query_results.fetched_entity_type)
            self._entities_fetched_by_association[entity_type].append(query_results)

    def get_fetched_entities_by_type(self, entity_type: str):
        return self._entities_dict_by_type[entity_type]

    def get_entities_by_type(self, entity_type: str):
        results = []
        for entities in self._entities_dict_by_type[entity_type]:
            results.extend(entities.entities_fetched)
        return results


    def get_entities_without_duplicates_by_entity_type(self, entity_type: str) -> List[NamedModel]:
        entities_by_type = self.get_entities_by_type(entity_type)
        all_entities = set(entities_by_type)
        return all_entities


    def get_all_fetched_entity_types(self) -> List[str]:
        return list(self._entities_dict_by_type.keys())

    def get_all_entities_from_query_results(self) -> List[NamedModel]:
        """
        Returns a list of SeqscapeEntitiesFetchedBasedOnIds for all the entity types concatenated together.
        """
        res = []
        for v in self._entities_dict_by_type.values():
            res.extend(v)
        return res


    def get_all_fetched_entities_by_association(self) -> List[SeqscapeEntityQueryAndResults]:
        return self._entities_fetched_by_association

    def get_all_fetched_entities_by_association_by_type(self, query_entity_type, fetched_entity_type):
        return self._entities_fetched_by_association[(query_entity_type, fetched_entity_type)]

    def get_all_entities_by_association_by_type(self, query_entity_type: str, fetched_entity_type:str) -> List[
        SeqscapeEntityQueryAndResults]:
        """
        Gets all the entities of type 'fetched_entity_type', fetched by 'query_entity_type'
        :param query_entity_type:
        :param fetched_entity_type:
        :return:
        """
        query_results = self._entities_fetched_by_association[(query_entity_type, fetched_entity_type)]
        res = []
        for v in query_results:
{'fraction_non_alphanumeric': 0.07477033521932226, 'fraction_numerical': 0.0015817971649327736, 'mean_word_length': 3.1280763435459567, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 33, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1688418', 'n_tokens_mistral': 4777, 'n_tokens_neox': 4711, 'n_words': 1232}