"""

flagmatic 2

Copyright (c) 2012, E. R. Vaughan. All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1) Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

2) Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Further development of Flagmatic is supported by ERC.
http://cordis.europa.eu/project/rcn/104324_en.html
"""

# the following are already functions in Sage-8.6+
from sage.arith.all import binomial
from sage.combinat.all import Tuples, Combinations
from sage.rings.all import Integer, RationalField

from .construction import *
from .three_graph_flag import *


class RandomGraphConstruction(Construction):
    r"""
    Inherits from `Construction`_.

    Provides an object that represents the limit object of the following construction:
    Take a random 2-graph `G` on `n` vertices, where each edge appears with probability
    :math:`1/2` and use it to make a 3-graph `H` on the same vertex set, by placing a 3-edge in
    H if and only if the three vertices induce an odd number of edges in G.	:math:`\pi`
    """

    def __init__(self):

        self._field = RationalField()
        self._flag_cls = ThreeGraphFlag

    def subgraph_densities(self, n):

        if n < 0:
            raise ValueError

        tg = ThreeGraphFlag()
        return self._induced_flags(n, tg, [])

    def zero_eigenvectors(self, tg, flags):

        rows = set()
        for p in Tuples([0, 1], binomial(tg.n, 2)):
            edges = []
            c = 0
            for i in range(1, tg.n + 1):
                for j in range(1, i):
                    if p[c] == 1:
                        edges.append((j, i))
                    c += 1
            graphs = self._induced_flags(flags[0].n, tg, edges)
            row = [0 for f in flags]
            for pair in graphs:
                g, den = pair
                for i in range(len(flags)):
                    if g.is_labelled_isomorphic(flags[i]):
                        row[i] = den
                        break
            rows.add(tuple(row))

        return matrix_of_independent_rows(self._field, list(rows), len(flags))

    def _induced_flags(self, n, tg, type_edges):

        flag_counts = {}
        flags = []
        total = 0

        for p in Tuples([0, 1], binomial(n, 2) - binomial(tg.n, 2)):

            edges = list(type_edges)

            c = 0
            for i in range(tg.n + 1, n + 1):
                for j in range(1, i):
                    if p[c] == 1:
                        edges.append((j, i))
                    c += 1

            ig = ThreeGraphFlag()
            ig.n = n
            ig.t = tg.n

            for s in Combinations(list(range(1, n + 1)), 3):
                ind_edges = [e for e in edges if e[0] in s and e[1] in s]
                if len(ind_edges) == 1 or len(ind_edges) == 3:
                    ig.add_edge(s)

            it = ig.induced_subgraph(list(range(1, tg.n + 1)))
            if tg.is_labelled_isomorphic(it):
                ig.make_minimal_isomorph()

                ghash = hash(ig)
                if ghash in flag_counts:
                    flag_counts[ghash] += 1
                else:
                    flags.append(ig)
                    flag_counts[ghash] = 1

            total += 1

        return [(f, flag_counts[hash(f)] / Integer(total)) for f in flags]
