"""
This python file corresponds to the calculation of sub-optimality gaps
"""

import numpy as np
import collections
import itertools

from Pre_Functions import rev



# pos: the position effect vector
# v: the preference vector
# r: the revenue vector
# top_k: the number of top assortment and positioning pairs to display in terms of revenue
def Sub_Gap(pos,v,r,top_k):
    N = len(v)
    K = len(pos)
    count = collections.defaultdict(int)
    rev_to_ass = {}

    pos.sort(reverse = True)
    items = list(range(1,N+1))
    for k in range(1,K+1):
        for z in itertools.permutations(items, k):
            rev_z = rev(z,pos,v,r)
            if rev_z not in count:
                count[rev_z] = -1
            else:
                count[rev_z] -= 1
            rev_to_ass[(rev_z,count[rev_z])] = z

    c = 0
    opt = -1
    sub_opt = -1
    for i in sorted(rev_to_ass.keys(),reverse = True):
        c += 1
        if c == 1:
            opt = i[0]
        elif i[0] < opt and sub_opt == -1:
            sub_opt = i[0]
        if c <= top_k:
            print("Assortment and Positioning: ",rev_to_ass[i],"; Revenue: ",i)

    sub_gap = opt - sub_opt
    # print("Suboptimality Gap: ",sub_gap)
    return rev_to_ass, sub_gap
