<commit_before>###########################################################################
#          (C) Vrije Universiteit, Amsterdam (the Netherlands)            #
#                                                                         #
# This file is part of AmCAT - The Amsterdam Content Analysis Toolkit     #
#                                                                         #
# AmCAT 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.                                              #
#                                                                         #
# AmCAT 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 AmCAT.  If not, see <http://www.gnu.org/licenses/>.  #
###########################################################################
from __future__ import unicode_literals

from collections import OrderedDict, defaultdict
from operator import itemgetter

from django.db.models import Q

from amcat.models import Medium, ArticleSet, Code
from amcat.tools.aggregate_orm.sqlobj import SQLObject, JOINS

POSTGRES_DATE_TRUNC_VALUES = [
    "microseconds",
    "milliseconds",
    "second",
    "minute",
    "hour",
    "day",
    "week",
    "month",
    "quarter",
    "year",
    "decade",
    "century",
    "millennium"
]

DATE_TRUNC_SQL = 'date_trunc(\'{interval}\', T_articles.date)'

__all__ = (
    "IntervalCategory",
    "MediumCategory",
    "ArticleSetCategory",
    "TermCategory",
    "SchemafieldCategory"
)

class Category(SQLObject):
    def aggregate(self, categories, value, rows):
        """
        Categories may aggregate rows further as they see fit. This can for example
        be used to implement codebook code aggregations.
        """
        return rows

    def get_objects(self, ids):
        return None

    def get_object(self, objects, id):
        return id

    def get_group_by(self):
        return next(iter(self.get_selects()))

    def get_column_names(self):
        """Returns names of columns when serializing to a flat format (csv)."""
        raise NotImplementedError("get_column_names() should be implemented by subclasses.")

    def get_column_values(self, obj):
        """Returns values for each column yielded by get_column_names() for an instance."""
        raise NotImplementedError("get_column_values() should be implemented by subclasses.")


class ModelCategory(Category):
    model = None

    def get_objects(self, ids):
        return self.model.objects.in_bulk(ids)

    def get_object(self, objects, id):
        return objects[id]

    def get_column_names(self):
        model_name = self.model.__name__.lower()
        return model_name + "_id", model_name + "_label"

    def get_column_values(self, obj):
        return obj.id, getattr(obj, obj.__label__)


class IntervalCategory(Category):
    joins_needed = ("codings", "coded_articles", "articles")

    def __init__(self, interval, **kwargs):
        super(IntervalCategory, self).__init__(**kwargs)

        if interval not in POSTGRES_DATE_TRUNC_VALUES:
            err_msg = "{} not a valid interval. Choose on of: {}"
            raise ValueError(err_msg.format(interval, POSTGRES_DATE_TRUNC_VALUES))

        self.interval = interval

    def get_selects(self):
        return [DATE_TRUNC_SQL.format(interval=self.interval)]

    def __repr__(self):
        return "<Interval: %s>" % self.interval

    def get_column_names(self):
        yield "date"

    def get_column_values(self, obj):
        """@type obj: datetime.datetime"""
        yield obj.isoformat()

class DuplicateLabelError(ValueError):
    pass

class InvalidReferenceError(ValueError):
    pass

class MediumCategory(ModelCategory):
    model = Medium
    joins_needed = ("codings", "coded_articles", "articles")

    def __init__(self, codebook=None):
        """
        Mediums can be aggregated using a codebook of the form:

        A
        - B
        - C
        D

        Mediums with the label A, B, or C will all be grouped under 'A'. D will not be considered,
        which is the same as just leaving it out.

        @param codebook: codebook to use for grouping
        @type codebook: Codebook
        """
        super(MediumCategory, self).__init__()
        self.codebook = codebook
        self.aggregation_map = {}

        if self.codebook is not None:
            self.codebook.cache()

            # Sanity check 1: labels must be unique
            labels = [c.label for c in self.codebook.codes]
            if len(set(labels)) != len(labels):
                dcount= defaultdict(int)
                for label in labels:
                    dcount[label] += 1
                duplicates = {l for l in labels if dcount[l] > 1}
                raise DuplicateLabelError("Duplicate labels in codebook {}: {}".format(codebook, duplicates))

            # Sanity check 2: labels must refer to mediums
            qfilter = Q()
            for label in labels:
                qfilter |= Q(name__iexact=label)
            mediums = Medium.objects.filter(qfilter)
            if mediums.distinct("id").count() != len(labels):
                real_labels = set(mediums.values_list("name", flat=True))
                error_message = "Some labels in {} did not refer to mediums: {}"
                raise InvalidReferenceError(error_message.format(self.codebook, set(labels) - real_labels))

            # Determine code -> code mapping
            root_map = {}
            for root_node in self.codebook.get_tree():<commit_msg>Fixed bug causing init error in MediumCategory<commit_after>###########################################################################
#          (C) Vrije Universiteit, Amsterdam (the Netherlands)            #
#                                                                         #
# This file is part of AmCAT - The Amsterdam Content Analysis Toolkit     #
#                                                                         #
# AmCAT 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.                                              #
#                                                                         #
# AmCAT 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 AmCAT.  If not, see <http://www.gnu.org/licenses/>.  #
###########################################################################
from __future__ import unicode_literals

from collections import OrderedDict, defaultdict
from operator import itemgetter

from django.db.models import Q

from amcat.models import Medium, ArticleSet, Code
from amcat.tools.aggregate_orm.sqlobj import SQLObject, JOINS

POSTGRES_DATE_TRUNC_VALUES = [
    "microseconds",
    "milliseconds",
    "second",
    "minute",
    "hour",
    "day",
    "week",
    "month",
    "quarter",
    "year",
    "decade",
    "century",
    "millennium"
]

DATE_TRUNC_SQL = 'date_trunc(\'{interval}\', T_articles.date)'

__all__ = (
    "IntervalCategory",
    "MediumCategory",
    "ArticleSetCategory",
    "TermCategory",
    "SchemafieldCategory"
)

class Category(SQLObject):
    def aggregate(self, categories, value, rows):
        """
        Categories may aggregate rows further as they see fit. This can for example
        be used to implement codebook code aggregations.
        """
        return rows

    def get_objects(self, ids):
        return None

    def get_object(self, objects, id):
        return id

    def get_group_by(self):
        return next(iter(self.get_selects()))

    def get_column_names(self):
        """Returns names of columns when serializing to a flat format (csv)."""
        raise NotImplementedError("get_column_names() should be implemented by subclasses.")

    def get_column_values(self, obj):
        """Returns values for each column yielded by get_column_names() for an instance."""
        raise NotImplementedError("get_column_values() should be implemented by subclasses.")


class ModelCategory(Category):
    model = None

    def get_objects(self, ids):
        return self.model.objects.in_bulk(ids)

    def get_object(self, objects, id):
        return objects[id]

    def get_column_names(self):
        model_name = self.model.__name__.lower()
        return model_name + "_id", model_name + "_label"

    def get_column_values(self, obj):
        return obj.id, getattr(obj, obj.__label__)


class IntervalCategory(Category):
    joins_needed = ("codings", "coded_articles", "articles")

    def __init__(self, interval, **kwargs):
        super(IntervalCategory, self).__init__(**kwargs)

        if interval not in POSTGRES_DATE_TRUNC_VALUES:
            err_msg = "{} not a valid interval. Choose on of: {}"
            raise ValueError(err_msg.format(interval, POSTGRES_DATE_TRUNC_VALUES))

        self.interval = interval

    def get_selects(self):
        return [DATE_TRUNC_SQL.format(interval=self.interval)]

    def __repr__(self):
        return "<Interval: %s>" % self.interval

    def get_column_names(self):
        yield "date"

    def get_column_values(self, obj):
        """@type obj: datetime.datetime"""
        yield obj.isoformat()

class DuplicateLabelError(ValueError):
    pass

class InvalidReferenceError(ValueError):
    pass

class MediumCategory(ModelCategory):
    model = Medium
    joins_needed = ("codings", "coded_articles", "articles")

    def __init__(self, prefix=None, codebook=None):
        """
        Mediums can be aggregated using a codebook of the form:

        A
        - B
        - C
        D

        Mediums with the label A, B, or C will all be grouped under 'A'. D will not be considered,
        which is the same as just leaving it out.

        @param codebook: codebook to use for grouping
        @type codebook: Codebook
        """
        super(MediumCategory, self).__init__(prefix=prefix)
        self.codebook = codebook
        self.aggregation_map = {}

        if self.codebook is not None:
            self.codebook.cache()

            # Sanity check 1: labels must be unique
            labels = [c.label for c in self.codebook.codes]
            if len(set(labels)) != len(labels):
                dcount= defaultdict(int)
                for label in labels:
                    dcount[label] += 1
                duplicates = {l for l in labels if dcount[l] > 1}
                raise DuplicateLabelError("Duplicate labels in codebook {}: {}".format(codebook, duplicates))

            # Sanity check 2: labels must refer to mediums
            qfilter = Q()
            for label in labels:
                qfilter |= Q(name__iexact=label)
            mediums = Medium.objects.filter(qfilter)
            if mediums.distinct("id").count() != len(labels):
                real_labels = set(mediums.values_list("name", flat=True))
                error_message = "Some labels in {} did not refer to mediums: {}"
                raise InvalidReferenceError(error_message.format(self.codebook, set(labels) - real_labels))

            # Determine code -> code mapping
            root_map = {}
            for root_node in self.codebook.get_tree():
{'fraction_non_alphanumeric': 0.11138310893512852, 'fraction_numerical': 0.0008159934720522236, 'mean_word_length': 2.1966614501825767, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 32, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2542871', 'n_tokens_mistral': 3284, 'n_tokens_neox': 3110, 'n_words': 1010}