コード例 #1
0
ファイル: vst_rs.py プロジェクト: oscarcorreag/PhD-code
    def plan_subgroups(self, group):
        gs = len(group)
        if gs > self.S:
            raise (ValueError, "Group size must be at most S.")
        X = {}
        cost = {}
        J = {}
        OptPOI = {}
        OptCost = {}
        bestSubgrouping = {}
        bestDiv = {}
        for u in group:
            t_u = tuple([u])
            X[t_u], cost[t_u], J[t_u], OptPOI[t_u], OptCost[t_u] = self.find_nimp([u], {u: 0})

        for j in range(2, self.z + 1):
            for cmb in utils.comb(group, j):
                cmb = sorted(cmb)
                t_cmb = tuple(cmb)
                M = {t_cmb: []}
                OptCost[t_cmb] = sys.maxint
                OptPOI[t_cmb] = None
                bestDiv[t_cmb] = {}
                bestSubgrouping[t_cmb] = [None, None]
                cost[t_cmb] = {}
                for v in self.nodes:
                    cost[t_cmb][v] = sys.maxint
                combs1 = [[cmb[0]]]
                for x in range(1, j - 1):
                    for y in utils.comb(cmb[1:], x):
                        t = [cmb[0]]
                        t.extend(y)
                        combs1.append(t)
                for comb1 in combs1:
                    comb2 = sorted(list(set(cmb) - set(comb1)))
                    temp = OptCost[tuple(comb1)] + OptCost[tuple(comb2)]
                    if OptCost[t_cmb] > temp:
                        OptCost[t_cmb] = temp
                        bestSubgrouping[t_cmb] = [comb1, comb2]
                    XX = list(set(X[tuple(comb1)]).intersection(X[tuple(comb2)]))
                    for m in XX:
                        if m not in M[t_cmb]:
                            M[t_cmb].append(m)
                        temp = cost[tuple(comb1)][m] + cost[tuple(comb2)][m]
                        if cost[t_cmb][m] > temp:
                            cost[t_cmb][m] = temp
                            bestDiv[t_cmb][m] = [comb1, comb2]
                X[t_cmb], cost[t_cmb], J[t_cmb], p, temp = self.find_nimp(M[t_cmb], cost[t_cmb])
                if OptCost[t_cmb] > temp:
                    # It is better to ride-share than going independently.
                    OptCost[t_cmb] = temp
                    OptPOI[t_cmb] = p
                    bestSubgrouping[t_cmb] = [cmb, None]
        return OptCost, OptPOI, J, bestDiv, bestSubgrouping
コード例 #2
0
 def __create_subsets_e(set_):
     sets_e = [tuple([set_[0]])]
     l_set = len(set_)
     for x in range(1, l_set - 1):
         for y in comb(set_[1:], x):
             t = [set_[0]]
             t.extend(y)
             sets_e.append(tuple(t))
     return sets_e
コード例 #3
0
ファイル: pe53.py プロジェクト: kittttttan/pe
def pe53(limit=100):
    """
    >>> pe53()
    4075
    """
    cnt = 0
    for n in range(1, limit+1, 2):
        for r in range(1, (n >> 1) + 1):
            c = comb(n, r)
            if c > 1000000:
                cnt += 2
    for n in range(2, limit+1, 2):
        for r in range(1, (n >> 1) + 1):
            c = comb(n, r)
            if c > 1000000:
                if r == n >> 1:
                    cnt += 1
                else:
                    cnt += 2
    return cnt
コード例 #4
0
def pe53(limit=100):
    """
    >>> pe53()
    4075
    """
    cnt = 0
    for n in range(1, limit + 1, 2):
        for r in range(1, (n >> 1) + 1):
            c = comb(n, r)
            if c > 1000000:
                cnt += 2
    for n in range(2, limit + 1, 2):
        for r in range(1, (n >> 1) + 1):
            c = comb(n, r)
            if c > 1000000:
                if r == n >> 1:
                    cnt += 1
                else:
                    cnt += 2
    return cnt
コード例 #5
0
ファイル: vst_rs.py プロジェクト: oscarcorreag/PhD-code
 def divide_group_into_subgroups(self, group, OptCost):
     gs = len(group)
     if gs > self.S:
         raise (ValueError, "Group size must be at most S.")
     bestSubgrouping = {}
     for j in range(self.z + 1, gs + 1):
         for cmb in utils.comb(group, j):
             cmb = sorted(cmb)
             t_cmb = tuple(cmb)
             OptCost[t_cmb] = sys.maxint
             combs1 = [[cmb[0]]]
             bestSubgrouping[t_cmb] = [None, None]
             for x in range(1, j - 1):
                 for y in utils.comb(cmb[1:], x):
                     t = [cmb[0]]
                     t.extend(y)
                     combs1.append(t)
             for comb1 in combs1:
                 comb2 = sorted(list(set(cmb) - set(comb1)))
                 temp = OptCost[tuple(comb1)] + OptCost[tuple(comb2)]
                 if OptCost[t_cmb] > temp:
                     OptCost[t_cmb] = temp
                     bestSubgrouping[t_cmb] = [comb1, comb2]
     return OptCost, bestSubgrouping
コード例 #6
0
def count(digits_left, choices):
    if choices > 1:
        return sum(
            comb(digits_left, c) * count(digits_left - c, choices - 1)
            for c in range(min(digits_left + 1, repeat + 1)))
    return digits_left <= repeat
コード例 #7
0
from utils import catalan, comb

n = 12
res = 0
for i in range(1, n / 2 + 1):
    res += comb(n, i) * comb(n - i, i) / 2 - catalan(i) * comb(n, 2 * i)

print res
コード例 #8
0
ファイル: dreyfus.py プロジェクト: oscarcorreag/PhD-code
    def steiner_tree(self, terminals, consider_terminals=True):

        if len(terminals) > 0:
            q = terminals[0]
            set_c = sorted(terminals[1:])
        else:
            return

        for j in self.__graph:
            self.__steiner_distances[j] = {}
            for t in set_c:
                j_t = tuple(sorted(([j, t])))
                try:
                    self.__steiner_distances[j][tuple(
                        [t])] = [self.__graph.dist[j_t], t, (None, None)]
                except KeyError:
                    self.__steiner_distances[j][tuple(
                        [t])] = [sys.maxint, t, (None, None)]

        for m in range(2, len(set_c)):

            for set_d in comb(set_c, m):
                for i in self.__graph:
                    self.__steiner_distances[i][tuple(set_d)] = [
                        sys.maxint, None, (None, None)
                    ]

                sets_e = [[set_d[0]]]
                for x in range(1, m - 1):
                    for y in comb(set_d[1:], x):
                        t = [set_d[0]]
                        t.extend(y)
                        sets_e.append(t)

                for j in self.__graph:
                    u = sys.maxint
                    best_subsets = None
                    for set_e in sets_e:
                        set_f = sorted(list(set(set_d) - set(set_e)))
                        if len(set_f) > 0:
                            s = self.__steiner_distances[j][tuple(set_e)][0] + \
                                self.__steiner_distances[j][tuple(set_f)][0]
                        else:
                            s = self.__steiner_distances[j][tuple(set_e)][0]
                        if s < u:
                            u = s
                            best_subsets = (set_e, set_f)
                    for i in self.__graph:
                        i_j = tuple(sorted(([i, j])))
                        try:
                            dist = self.__graph.dist[i_j]
                        except KeyError:
                            dist = sys.maxint
                        if consider_terminals:
                            if dist + u < self.__steiner_distances[i][tuple(
                                    set_d)][0]:
                                self.__steiner_distances[i][tuple(set_d)] = [
                                    dist + u, j, best_subsets
                                ]
                        else:
                            if dist + u < self.__steiner_distances[i][tuple(
                                    set_d)][0] and j not in terminals:
                                self.__steiner_distances[i][tuple(set_d)] = [
                                    dist + u, j, best_subsets
                                ]

        sets_e = [[set_c[0]]]
        for x in range(1, len(set_c) - 1):
            for y in comb(set_c[1:], x):
                t = [set_c[0]]
                t.extend(y)
                sets_e.append(t)

        cost = sys.maxint
        if q not in self.__steiner_distances:
            self.__steiner_distances[q] = {
                tuple(set_c): [cost, None, (None, None)]
            }
        else:
            self.__steiner_distances[q][tuple(set_c)] = [
                cost, None, (None, None)
            ]
        for j in self.__graph:
            u = sys.maxint
            best_subsets = None
            for set_e in sets_e:
                set_f = sorted(list(set(set_c) - set(set_e)))
                if len(set_f) > 0:
                    s = self.__steiner_distances[j][tuple(set_e)][
                        0] + self.__steiner_distances[j][tuple(set_f)][0]
                else:
                    s = self.__steiner_distances[j][tuple(set_e)][0]
                if s < u:
                    u = s
                    best_subsets = (set_e, set_f)
            q_j = tuple(sorted(([q, j])))
            try:
                dist = self.__graph.dist[q_j]
            except KeyError:
                dist = sys.maxint
            if consider_terminals:
                if dist + u < cost:
                    cost = dist + u
                    self.__steiner_distances[q][tuple(set_c)] = [
                        cost, j, best_subsets
                    ]
            else:
                if dist + u < cost and j not in terminals:
                    cost = dist + u
                    self.__steiner_distances[q][tuple(set_c)] = [
                        cost, j, best_subsets
                    ]

        # Reconstruct the Steiner by backtracking
        steiner_tree, cost = self.__build_steiner_tree(q, set_c)

        return steiner_tree, cost
コード例 #9
0
    def steiner_tree(self,
                     h_l_sd=20,
                     h_l_hot_spots=3,
                     consider_terminals=False):
        #
        set_c = tuple(sorted(self.__terminals[1:]))
        t_tuples = [tuple([t]) for t in set_c]
        #
        for j in self.__nodes:
            self.__s_d[j] = {}
            for t in t_tuples:
                dist, d_t = self.__distances[tuple(sorted([j, t[0]]))]
                self.__s_d[j][t] = [[
                    dist, 0, dist, t[0], (None, None), d_t, d_t, d_t, d_t, 0
                ]]
        #
        for m in range(2, len(set_c)):
            #
            sets_d = [tuple(set_d) for set_d in comb(set_c, m)]
            for set_d in sets_d:
                # target_hot_spots = CandidatesList(h_l_hot_spots)
                for i in self.__nodes:
                    self.__s_d[i][set_d] = CandidatesList(h_l_sd)
                #
                sets_e = self.__create_subsets_e(set_d)
                #
                for j in self.__nodes:
                    u = sys.maxint
                    sets_e_f = None
                    d_ts = None
                    for set_e in sets_e:
                        set_f = tuple(sorted(list(set(set_d) - set(set_e))))
                        if len(set_f) > 0:
                            s = self.__s_d[j][set_e][0][0] + self.__s_d[j][
                                set_f][0][0]
                        else:
                            s = self.__s_d[j][set_e][0][0]
                        if s < u:
                            u = s
                            sets_e_f = (set_e, set_f)
                            d_ts = (self.__s_d[j][set_e][0][5],
                                    self.__s_d[j][set_f][0][5])
                    for i in self.__nodes:
                        try:
                            dist, d_t = self.__distances[tuple(sorted([i, j]))]
                        except KeyError:
                            dist = sys.maxint
                            d_t = 'N'
                        if consider_terminals:
                            cost = dist + u
                            # if cost < self.__steiner_distances[i][set_d][0][0]:
                            if cost < sys.maxint:
                                dd_t = 'E'
                                if d_t == 'N' and d_ts[0] == 'N' and d_ts[
                                        1] == 'N':
                                    dd_t = 'N'
                                self.__s_d[i][set_d].append([
                                    cost, u, dist, j, sets_e_f, dd_t, d_t,
                                    d_ts[0], d_ts[1], 0
                                ])
                                # dist_to_poi = self.__distances[tuple(sorted([self.__poi, i]))][0]
                                # target_hot_spots.append([dist_to_poi + cost, i])
                        else:
                            cost = dist + u
                            # if cost < self.__steiner_distances[i][set_d][0][0] and j not in self.__terminals:
                            if j not in self.__terminals and cost < sys.maxint:
                                dd_t = 'E'
                                if d_t == 'N' and d_ts[0] == 'N' and d_ts[
                                        1] == 'N':
                                    dd_t = 'N'
                                self.__s_d[i][set_d].append([
                                    cost, u, dist, j, sets_e_f, dd_t, d_t,
                                    d_ts[0], d_ts[1], 0
                                ])
                                # dist_to_poi = self.__distances[tuple(sorted([self.__poi, i]))][0]
                                # target_hot_spots.append([dist_to_poi + cost, i])

                target_hot_spots = CandidatesList(h_l_hot_spots)
                for i in self.__nodes:
                    cost = self.__s_d[i][set_d][0][0]
                    j = self.__s_d[i][set_d][0][3]
                    set_e, set_f = self.__s_d[i][set_d][0][4]
                    dist_to_poi = self.__distances[tuple(
                        sorted([self.__poi, i]))][0]
                    target_hot_spots.append([dist_to_poi + cost, i])
                    if j in self.__refs:
                        if set_e in self.__refs[j]:
                            self.__refs[j][set_e].add((i, set_d))
                        else:
                            self.__refs[j][set_e] = {(i, set_d)}
                        if set_f in self.__refs[j]:
                            self.__refs[j][set_f].add((i, set_d))
                        else:
                            self.__refs[j][set_f] = {(i, set_d)}
                    else:
                        self.__refs[j] = {
                            set_e: {(i, set_d)},
                            set_f: {(i, set_d)}
                        }

                # which is the best node for steiner tree between terminals in D and POI

                # print('-------------------------------------------------------')
                # print(set_d)
                # print('-------------------------------------------------------')
                # self.__print_target_hot_spots(target_hot_spots, set_d)
                # print('-------------------------------------------------------')
                # pdb.set_trace()
                self.__correct_i_s(target_hot_spots, set_d)
                self.__print_target_hot_spots(target_hot_spots, set_d)
                # print('-------------------------------------------------------')
        #
        sets_e = self.__create_subsets_e(set_c)
        #
        # cost = sys.maxint
        target_hot_spots = CandidatesList(h_l_hot_spots)
        self.__s_d[self.__poi][set_c] = CandidatesList(h_l_sd)
        for j in self.__nodes:
            u = sys.maxint
            sets_e_f = None
            d_ts = None
            for set_e in sets_e:
                set_f = tuple(sorted(list(set(set_c) - set(set_e))))
                if len(set_f) > 0:
                    s = self.__s_d[j][set_e][0][0] + self.__s_d[j][set_f][0][0]
                else:
                    s = self.__s_d[j][set_e][0][0]
                if s < u:
                    u = s
                    sets_e_f = (set_e, set_f)
                    d_ts = (self.__s_d[j][set_e][0][5],
                            self.__s_d[j][set_f][0][5])
            try:
                dist, d_t = self.__distances[tuple(sorted([self.__poi, j]))]
            except KeyError:
                dist = sys.maxint
                d_t = 'N'
            if consider_terminals:
                # if dist + u < cost:
                dd_t = 'E'
                if d_t == 'N' and d_ts[0] == 'N' and d_ts[1] == 'N':
                    dd_t = 'N'
                cost = dist + u
                if cost < sys.maxint:
                    self.__s_d[self.__poi][set_c].append([
                        cost, u, dist, j, sets_e_f, dd_t, d_t, d_ts[0],
                        d_ts[1], 0
                    ])
                    target_hot_spots.append([cost, self.__poi])
            else:
                cost = dist + u
                if j not in self.__terminals and cost < sys.maxint:
                    dd_t = 'E'
                    if d_t == 'N' and d_ts[0] == 'N' and d_ts[1] == 'N':
                        dd_t = 'N'
                    self.__s_d[self.__poi][set_c].append([
                        cost, u, dist, j, sets_e_f, dd_t, d_t, d_ts[0],
                        d_ts[1], 0
                    ])
                    target_hot_spots.append([cost, self.__poi])

        j = self.__s_d[self.__poi][set_c][0][3]
        set_e, set_f = self.__s_d[self.__poi][set_c][0][4]
        if j in self.__refs:
            if set_e in self.__refs[j]:
                self.__refs[j][set_e].add((self.__poi, set_c))
            else:
                self.__refs[j][set_e] = {(self.__poi, set_c)}
            if set_f in self.__refs[j]:
                self.__refs[j][set_f].add((self.__poi, set_c))
            else:
                self.__refs[j][set_f] = {(self.__poi, set_c)}
        else:
            self.__refs[j] = {
                set_e: {(self.__poi, set_c)},
                set_f: {(self.__poi, set_c)}
            }

        # print('-------------------------------------------------------')
        # print(set_c)
        # print('-------------------------------------------------------')
        # self.__print_target_hotspots(target_hot_spots, set_c)
        # print('-------------------------------------------------------')
        # pdb.set_trace()
        # self.__print_target_hot_spots(target_hot_spots, set_c)
        # pdb.set_trace()
        self.__correct_i_s(target_hot_spots, set_c)
        # print('-------------------------------------------------------')

        # #
        # while True:
        #     delta_cost = self.__steinerify(self.__poi, set_c)
        #     if delta_cost == 0:
        #         break
        #
        # Reconstruct the Steiner by backtracking
        steiner_tree = self.__build_steiner_tree(self.__poi, set_c)
        #
        return steiner_tree
コード例 #10
0
 def steiner_tree(self, qi=10, consider_terminals=False):
     #
     set_c = sorted(self.__terminals[1:])
     #
     for j in self.__nodes:
         self.__steiner_distances[j] = {}
         for t in set_c:
             distance, d_type = self.__distances[tuple(sorted([j, t]))]
             self.__steiner_distances[j][tuple([t])] = [
                 distance, 0, distance, t, (None, None), d_type, d_type,
                 d_type, d_type
             ]
     #
     for m in range(2, len(set_c)):
         #
         sets_d = [tuple(c) for c in comb(set_c, m)]
         for set_d in sets_d:
             for i in self.__nodes:
                 self.__steiner_distances[i][set_d] = [
                     sys.maxint, 0, sys.maxint, None, (None, None), None,
                     None, None, None
                 ]
             #
             sets_e = [tuple([set_d[0]])]
             for x in range(1, m - 1):
                 for y in comb(set_d[1:], x):
                     t = [set_d[0]]
                     t.extend(y)
                     sets_e.append(tuple(t))
             #
             j_subsets_ef = {}
             for j in self.__nodes:
                 j_subsets_ef[j] = []
                 for set_e in sets_e:
                     set_f = tuple(sorted(list(set(set_d) - set(set_e))))
                     u_e = self.__steiner_distances[j][set_e][0]
                     u_f = 0
                     t_e = self.__steiner_distances[j][set_e][5]
                     t_f = 'N'
                     if len(set_f) > 0:
                         u_f = self.__steiner_distances[j][set_f][0]
                         t_f = self.__steiner_distances[j][set_f][5]
                     j_subsets_ef[j].append(
                         [set_e, set_f, u_e, u_f, t_e, t_f])
             #
             temp = []
             for i in self.__nodes:
                 dist_to_poi = self.__distances[tuple(
                     sorted([self.__poi, i]))][0]
                 for j in self.__nodes:
                     try:
                         dist, t_dist = self.__distances[tuple(
                             sorted([i, j]))]
                     except KeyError:
                         dist = sys.maxint
                         t_dist = 'N'
                     for j_subset_ef in j_subsets_ef[j]:
                         set_e = j_subset_ef[0]
                         set_f = j_subset_ef[1]
                         u_e = j_subset_ef[2]
                         u_f = j_subset_ef[3]
                         t_e = j_subset_ef[4]
                         t_f = j_subset_ef[5]
                         temp.append([
                             dist_to_poi + dist + u_e + u_f, i, j, set_e,
                             set_f
                         ])
             temp.sort()
             print(len(temp))
             print(temp[0:11])
             pdb.set_trace()
コード例 #11
0
    def steiner_tree(self):
        #
        set_c = tuple(sorted(self.__terminals))
        t_tuples = [tuple([t]) for t in set_c]
        #
        ms = {t: s - 1 for t, s in self.__max_stops.iteritems()}
        bs = {t: s == 0 for t, s in ms.iteritems()}
        #
        temp_list = list(self.__nodes)
        temp_list.remove(self.__poi)
        for j in temp_list:
            self.__s_d[j] = {}
            for t_ in t_tuples:
                t = t_[0]
                try:
                    self.__s_d[j][t_] = [
                        self.__dist[tuple(sorted([j, t]))], t, (None, None), {
                            t: ms[t]
                        }, bs[t]
                    ]
                except KeyError:
                    self.__s_d[j][t_] = [
                        sys.maxint, t, (None, None), {
                            t: ms[t]
                        }, bs[t]
                    ]
        #
        j = self.__poi
        self.__s_d[j] = {}
        for t_ in t_tuples:
            t = t_[0]
            try:
                self.__s_d[j][t_] = \
                    [self.__dist[tuple(sorted([j, t]))], t, (None, None), {t: self.__max_stops[t]}, False]
            except KeyError:
                self.__s_d[j][t_] = [
                    sys.maxint, t, (None, None), {
                        t: self.__max_stops[t]
                    }, False
                ]
        #
        for m in range(2, len(set_c) + 1):
            #
            sets_d = [tuple(set_d) for set_d in comb(set_c, m)]
            for set_d in sets_d:
                #
                if m < len(set_c):
                    for i in self.__nodes:
                        self.__s_d[i][set_d] = [
                            sys.maxint, None, (None, None), None, False
                        ]
                else:
                    self.__s_d[self.__poi][set_c] = [
                        sys.maxint, None, (None, None), None, False
                    ]
                #
                sets_e = self.__create_subsets_e(set_d)
                #
                for j in self.__nodes:
                    u = sys.maxint
                    best_subsets = None
                    burnt = False
                    for set_e in sets_e:
                        set_f = tuple(sorted(list(set(set_d) - set(set_e))))
                        if len(set_f) > 0:
                            s = self.__s_d[j][set_e][0] + self.__s_d[j][set_f][
                                0]
                        else:
                            s = self.__s_d[j][set_e][0]
                        if s < u:
                            burnt = False
                            if self.__s_d[j][set_e][4] or self.__s_d[j][set_f][
                                    4]:
                                burnt = True
                            u = s
                            best_subsets = (set_e, set_f)
                    temp_list = list(self.__nodes)
                    ms = None
                    if best_subsets is not None:
                        ms = self.__s_d[j][best_subsets[0]][3].copy()
                        ms.update(self.__s_d[j][best_subsets[1]][3])
                    if m == len(set_c) or j == self.__poi:
                        temp_list = [self.__poi]
                    else:
                        if burnt:
                            temp_list = [self.__poi, j]
                        elif ms is not None:
                            ms = {t: s - 1 for t, s in ms.iteritems()}
                            if 0 in ms.values():
                                burnt = True
                    for i in temp_list:
                        try:
                            dist = self.__dist[tuple(sorted([i, j]))]
                        except KeyError:
                            dist = sys.maxint
                        if dist + u < self.__s_d[i][set_d][0]:
                            self.__s_d[i][set_d] = [
                                dist + u, j, best_subsets, ms, burnt
                            ]

        # Reconstruct the Steiner by backtracking
        steiner_tree = self.__build_steiner_tree_bactracking(self.__poi, set_c)

        return steiner_tree
コード例 #12
0
    def steiner_tree(self, history_length=10, consider_terminals=False):
        #
        set_c = sorted(self.__terminals[1:])
        #
        for j in self.__nodes:
            self.__steiner_distances[j] = {}
            for t in set_c:
                # self.__steiner_distances[j][tuple([t])] = CandidatesList(history_length)
                distance, d_type = self.__distances[tuple(sorted([j, t]))]
                # self.__steiner_distances[j][tuple([t])].append([distance, t, (None, None), distance, 0, d_type])
                self.__steiner_distances[j][tuple([t])] = [
                    distance, 0, distance, t, (None, None), d_type, d_type,
                    d_type, d_type
                ]
        #
        for m in range(2, len(set_c)):
            #
            for set_d in comb(set_c, m):
                candidates = CandidatesList(history_length)
                for i in self.__nodes:
                    self.__steiner_distances[i][tuple(set_d)] = [
                        sys.maxint, 0, sys.maxint, None, (None, None), None,
                        None, None, None
                    ]
                    # self.__steiner_distances[i][tuple(set_d)] = CandidatesList(history_length)
                #
                sets_e = [[set_d[0]]]
                for x in range(1, m - 1):
                    for y in comb(set_d[1:], x):
                        t = [set_d[0]]
                        t.extend(y)
                        sets_e.append(t)
                #
                # Do it with nodes j \in best hotspots for subsets of D
                for j in self.__nodes:
                    u = sys.maxint
                    best_subsets = None
                    d_types = None
                    for set_e in sets_e:
                        set_f = sorted(list(set(set_d) - set(set_e)))
                        if len(set_f) > 0:
                            s = self.__steiner_distances[j][tuple(set_e)][0] + \
                                self.__steiner_distances[j][tuple(set_f)][0]
                        else:
                            s = self.__steiner_distances[j][tuple(set_e)][0]
                        if s < u:
                            u = s
                            best_subsets = (set_e, set_f)
                            d_types = (
                                self.__steiner_distances[j][tuple(set_e)][5],
                                self.__steiner_distances[j][tuple(set_f)][5])
                    for i in self.__nodes:
                        try:
                            dist, d_type = self.__distances[tuple(
                                sorted([i, j]))]
                        except KeyError:
                            dist = sys.maxint
                            d_type = 'N'
                        if consider_terminals:
                            cost = dist + u
                            if cost < self.__steiner_distances[i][tuple(
                                    set_d)][0]:
                                dd_type = 'E'
                                if d_type == 'N' and d_types[
                                        0] == 'N' and d_types[1] == 'N':
                                    dd_type = 'N'
                                self.__steiner_distances[i][tuple(set_d)] = [
                                    cost, u, dist, j, best_subsets, dd_type,
                                    d_type, d_types[0], d_types[1]
                                ]
                                dist_to_poi = self.__distances[tuple(
                                    sorted([self.__poi, i]))][0]
                                candidates.append([
                                    dist_to_poi + cost, cost, dist, i, j,
                                    dd_type, d_type, d_types[0], d_types[1],
                                    best_subsets
                                ])
                        else:
                            cost = dist + u
                            if cost < self.__steiner_distances[i][tuple(
                                    set_d)][0] and j not in self.__terminals:
                                dd_type = 'E'
                                if d_type == 'N' and d_types[
                                        0] == 'N' and d_types[1] == 'N':
                                    dd_type = 'N'
                                self.__steiner_distances[i][tuple(set_d)] = [
                                    cost, u, dist, j, best_subsets, dd_type,
                                    d_type, d_types[0], d_types[1]
                                ]
                                dist_to_poi = self.__distances[tuple(
                                    sorted([self.__poi, i]))][0]
                                candidates.append([
                                    dist_to_poi + cost, cost, dist, i, j,
                                    dd_type, d_type, d_types[0], d_types[1],
                                    best_subsets
                                ])

                # which is the best node for steiner tree between terminals in D and POI
                # pdb.set_trace()
                print(
                    '-------------------------------------------------------')
                print(set_d)
                print(
                    '-------------------------------------------------------')
                print(candidates)
                print(
                    '-------------------------------------------------------')
                self.__stabilize_candidates_set(candidates, set_d)

        sets_e = [[set_c[0]]]
        for x in range(1, len(set_c) - 1):
            for y in comb(set_c[1:], x):
                t = [set_c[0]]
                t.extend(y)
                sets_e.append(t)
        #
        cost = sys.maxint
        candidates = CandidatesList(history_length)
        if self.__poi not in self.__steiner_distances:
            self.__steiner_distances[self.__poi] = {
                tuple(set_c):
                [cost, 0, cost, None, (None, None), None, None, None, None]
            }
        else:
            self.__steiner_distances[self.__poi][tuple(set_c)] = [
                cost, 0, cost, None, (None, None), None, None, None, None
            ]
        #
        for j in self.__nodes:
            u = sys.maxint
            best_subsets = None
            d_types = None
            for set_e in sets_e:
                set_f = sorted(list(set(set_c) - set(set_e)))
                if len(set_f) > 0:
                    s = self.__steiner_distances[j][tuple(set_e)][0] + \
                        self.__steiner_distances[j][tuple(set_f)][0]
                else:
                    s = self.__steiner_distances[j][tuple(set_e)][0]
                if s < u:
                    u = s
                    best_subsets = (set_e, set_f)
                    d_types = (self.__steiner_distances[j][tuple(set_e)][5],
                               self.__steiner_distances[j][tuple(set_f)][5])
            try:
                dist, d_type = self.__distances[tuple(sorted([self.__poi, j]))]
            except KeyError:
                dist = sys.maxint
                d_type = 'N'
            if consider_terminals:
                if dist + u < cost:
                    dd_type = 'E'
                    if d_type == 'N' and d_types[0] == 'N' and d_types[
                            1] == 'N':
                        dd_type = 'N'
                    cost = dist + u
                    self.__steiner_distances[self.__poi][tuple(set_c)] = [
                        cost, u, dist, j, best_subsets, dd_type, d_type,
                        d_types[0], d_types[1]
                    ]
                    candidates.append([
                        dist + cost, cost, dist, self.__poi, j, dd_type,
                        d_type, d_types[0], d_types[1], best_subsets
                    ])
            else:
                if dist + u < cost and j not in self.__terminals:
                    dd_type = 'E'
                    if d_type == 'N' and d_types[0] == 'N' and d_types[
                            1] == 'N':
                        dd_type = 'N'
                    cost = dist + u
                    self.__steiner_distances[self.__poi][tuple(set_c)] = [
                        cost, u, dist, j, best_subsets, dd_type, d_type,
                        d_types[0], d_types[1]
                    ]
                    candidates.append([
                        dist + cost, cost, dist, self.__poi, j, dd_type,
                        d_type, d_types[0], d_types[1], best_subsets
                    ])

        # pdb.set_trace()
        print('-------------------------------------------------------')
        print(set_c)
        print('-------------------------------------------------------')
        print(candidates)
        print('-------------------------------------------------------')
        self.__stabilize_candidates_set(candidates, set_c)

        # #
        # while True:
        #     delta_cost = self.__steinerify(self.__poi, set_c)
        #     if delta_cost == 0:
        #         break
        #
        # Reconstruct the Steiner by backtracking
        steiner_tree = self.__build_steiner_tree_bactracking(self.__poi, set_c)
        #
        return steiner_tree
コード例 #13
0
ファイル: 267.py プロジェクト: crazymerlyn/code
from math import log, ceil
from utils import comb


last = 0
guess = 0.5
stepsize = 1e-6

def n_successes(guess):
    return (9 - log(1- guess, 10) * 1000) / (log(1 + 2 * guess, 10) - log(1 - guess, 10))

def fdiff(guess):
    e = 1e-6
    return (n_successes(guess + e) - n_successes(guess)) / e

while abs(last - guess) > 1e-12:
    last = guess
    guess -= fdiff(guess) * stepsize

successes = int(ceil(n_successes(guess)))

res = 0
for i in range(successes, 1001):
    res += comb(1000, i)

print "%.12f" % (res / 2.0 ** 1000)

コード例 #14
0
def possibs(same, total):
    res = 0
    for ncorrect in range(1, same + 1):
        res += comb(same, ncorrect) * factorial(total - ncorrect) * (
            1 if ncorrect % 2 else -1)
    return res
コード例 #15
0
from utils import comb
from math import factorial
from decimal import Decimal


def possibs(same, total):
    res = 0
    for ncorrect in range(1, same + 1):
        res += comb(same, ncorrect) * factorial(total - ncorrect) * (
            1 if ncorrect % 2 else -1)
    return res


print(
    Decimal(comb(25, 3) * (factorial(97) - possibs(22, 97))) / factorial(100))
コード例 #16
0
def find_high_combo_boards_fix_first_row(fixed_first_row):
    # input example: fixed_in_first_row = (,) or (0,) or (1, 2, 4), ...

    # if this fixed_first_row has been calculated, read the file and return it
    filename = output_folder + 'fixed-{}.json'.format('-'.join(
        map(str, fixed_first_row)))
    if os.path.isfile(filename):
        print(filename + ' exists. skip calculating.')
        with open(filename, 'r') as in_file:
            data = json.load(in_file)  # , object_pairs_hook=OrderedDict
            return data

    b = Board()
    main_color = b.main_color

    may_be_symmetric = (
        fixed_first_row == b.calc_symmetric_positions(fixed_first_row))
    if may_be_symmetric:
        calced_pos_ints = set()

    fixed_orb_count = len(fixed_first_row)
    not_fixed_orb_count = other_orb_count - len(fixed_first_row)
    total_combs = comb(24, not_fixed_orb_count)
    print('total_combinations:', total_combs)

    other_orb_max_psbl_combos = other_orb_count // 3

    found_board_count = 0
    combo_to_board_count = defaultdict(int)
    comb_counter = 0

    print_interval = 1000000 // len(other_orb_unique_color_perms)

    boards = []

    start = time.time()
    for pos_tail in combinations(range(6, 30), not_fixed_orb_count):
        comb_counter += 1
        if comb_counter % print_interval == 0:
            proportion = comb_counter / total_combs
            elapsed_time = time.time() - start
            remaining_time = elapsed_time / proportion * (1 - proportion)
            print(
                'fixed: {}, {:.2f} %, comb: {}, found: {}, elapsed: {:.1f}, remaining: {:.1f}'
                .format(fixed_first_row, proportion * 100, comb_counter,
                        found_board_count, elapsed_time, remaining_time))

        # other_orb_positions
        pos = fixed_first_row + pos_tail
        if may_be_symmetric:
            pos_int = b.positions_to_int(pos)
            sym_pos_int = b.calc_symmetric_positions_int(pos)
            if sym_pos_int in calced_pos_ints:
                continue
            else:
                calced_pos_ints.add(pos_int)

        main_orb_max_combos = b.count_main_orb_max_combos(pos)
        if main_orb_max_combos + other_orb_max_psbl_combos < combo_threshold:
            continue

        for colors in other_orb_unique_color_perms:
            other_orb_max_combos = b.calc_other_orb_max_combos(pos, colors)
            max_combos = main_orb_max_combos + other_orb_max_combos
            if max_combos < combo_threshold:
                continue

            b.set_sparse_board(pos, colors)
            combos, drop_times = b.count_combos()

            combo_count = len(combos)
            main_combo_count = sum(color == main_color
                                   for color, matched in combos)
            main_matched_count = sum(matched for color, matched in combos
                                     if color == main_color)

            if combo_count >= combo_threshold:
                found_board_count += 1
                combo_to_board_count[combo_count] += 1
                boards.append({
                    'combo_count': combo_count,
                    'main_combo_count': main_combo_count,
                    'main_matched_count': main_matched_count,
                    'drop_times': drop_times,
                    'combos': combos,
                    'board': b.get_output_board()
                })

    data = {'combo_to_board_count': combo_to_board_count, 'boards': boards}
    # filename = output_folder + 'fixed-{}.json'.format('-'.join(map(str, fixed_first_row)))
    with open(filename, 'w') as out_file:
        json.dump(data, out_file, separators=(',', ':'))

    return data
コード例 #17
0
ファイル: dreyfus_imr.py プロジェクト: oscarcorreag/PhD-code
    def steiner_tree(self, consider_terminals=False):
        #
        set_c = tuple(sorted(self.__terminals[1:]))
        t_tuples = [tuple([t]) for t in set_c]
        #
        for j in self.__nodes:
            self.__s_d[j] = {}
            for t in t_tuples:
                try:
                    self.__s_d[j][t] = [
                        self.__dist[tuple(sorted([j, t[0]]))], t[0],
                        (None, None)
                    ]
                except KeyError:
                    self.__s_d[j][t] = [sys.maxint, t[0], (None, None)]
        #
        for m in range(2, len(set_c)):
            #
            sets_d = [tuple(set_d) for set_d in comb(set_c, m)]
            for set_d in sets_d:
                #
                for i in self.__nodes:
                    self.__s_d[i][set_d] = [sys.maxint, None, (None, None)]
                #
                sets_e = self.__create_subsets_e(set_d)
                #
                for j in self.__nodes:
                    u = sys.maxint
                    best_subsets = None
                    for set_e in sets_e:
                        set_f = tuple(sorted(list(set(set_d) - set(set_e))))
                        if len(set_f) > 0:
                            s = self.__s_d[j][set_e][0] + self.__s_d[j][set_f][
                                0]
                        else:
                            s = self.__s_d[j][set_e][0]
                        if s < u:
                            u = s
                            best_subsets = (set_e, set_f)
                    for i in self.__nodes:
                        try:
                            dist = self.__dist[tuple(sorted([i, j]))]
                        except KeyError:
                            dist = sys.maxint
                        if consider_terminals:
                            if dist + u < self.__s_d[i][set_d][0]:
                                self.__s_d[i][set_d] = [
                                    dist + u, j, best_subsets
                                ]
                        else:
                            if dist + u < self.__s_d[i][set_d][
                                    0] and j not in self.__terminals[1:]:
                                self.__s_d[i][set_d] = [
                                    dist + u, j, best_subsets
                                ]
        #
        sets_e = self.__create_subsets_e(set_c)
        #
        cost = sys.maxint
        if self.__poi not in self.__s_d:
            self.__s_d[self.__poi] = {set_c: [cost, None, (None, None)]}
        else:
            self.__s_d[self.__poi][set_c] = [cost, None, (None, None)]
        #
        for j in self.__nodes:
            u = sys.maxint
            best_subsets = None
            for set_e in sets_e:
                set_f = tuple(sorted(list(set(set_c) - set(set_e))))
                if len(set_f) > 0:
                    s = self.__s_d[j][set_e][0] + self.__s_d[j][set_f][0]
                else:
                    s = self.__s_d[j][set_e][0]
                if s < u:
                    u = s
                    best_subsets = (set_e, set_f)
            try:
                dist = self.__dist[tuple(sorted([self.__poi, j]))]
            except KeyError:
                dist = sys.maxint
            if consider_terminals:
                if dist + u < cost:
                    cost = dist + u
                    self.__s_d[self.__poi][set_c] = [cost, j, best_subsets]
            else:
                if dist + u < cost and j not in self.__terminals[1:]:
                    cost = dist + u
                    self.__s_d[self.__poi][set_c] = [cost, j, best_subsets]

        # Reconstruct the Steiner by backtracking
        steiner_tree = self.__build_steiner_tree_bactracking(self.__poi, set_c)

        if self.__contract_graph:
            self.__decontract_steiner_tree(steiner_tree)

        return steiner_tree
コード例 #18
0
    def steiner_tree(self, consider_terminals=False):
        #
        set_c = tuple(sorted(self.__terminals[1:]))
        t_tuples = [tuple([t]) for t in set_c]
        #
        for j in self.__nodes:
            self.__s_d[j] = {}
            for t in t_tuples:
                pair_nodes = tuple(sorted([j, t[0]]))
                try:
                    entry_node = None
                    if j in self.__graph.contracted_regions:
                        path = self.__paths[pair_nodes]
                        if len(path) > 1:
                            if path.index(j) == len(path) - 1:
                                entry_node = path[len(path) - 2]
                            else:
                                entry_node = path[1]
                        else:
                            # pdb.set_trace()
                            pass
                    self.__s_d[j][t] = [self.__dist[pair_nodes], t[0], (None, None), entry_node]
                except KeyError:
                    self.__s_d[j][t] = [sys.maxint, t[0], (None, None), None]
        #
        for m in range(2, len(set_c)):
            #
            sets_d = [tuple(set_d) for set_d in comb(set_c, m)]
            for set_d in sets_d:
                #
                for i in self.__nodes:
                    self.__s_d[i][set_d] = [sys.maxint, None, (None, None)]
                #
                sets_e = self.__create_subsets_e(set_d)
                #
                for j in self.__nodes:
                    u = sys.maxint
                    best_subsets = None
                    for set_e in sets_e:
                        set_f = tuple(sorted(list(set(set_d) - set(set_e))))
                        if len(set_f) > 0:
                            s = self.__s_d[j][set_e][0] + self.__s_d[j][set_f][0]
                        else:
                            s = self.__s_d[j][set_e][0]
                        #
                        if s < u:
                            u = s
                            best_subsets = (set_e, set_f)
                    for i in self.__nodes:
                        pair_nodes = tuple(sorted([i, j]))
                        # d_n1_n3 = d_n2_n3 = 0
                        d1 = d2 = d3 = 0
                        try:
                            dist = self.__dist[pair_nodes]
                            if j in self.__graph.contracted_regions and best_subsets is not None:
                                e_n_1 = self.__s_d[j][best_subsets[0]][3]
                                e_n_2 = self.__s_d[j][best_subsets[1]][3]
                                path = self.__paths[pair_nodes]
                                dropped_edges = self.__graph[j][2]['dropped_edges']
                                dist_paths = self.__graph[j][2]['dist_paths']
                                n1 = dropped_edges[e_n_1]
                                n2 = dropped_edges[e_n_2]
                                if len(path) > 1:
                                    if path.index(j) == len(path) - 1:
                                        e_n_3 = path[len(path) - 2]
                                    else:
                                        e_n_3 = path[1]
                                    n3 = dropped_edges[e_n_3]
                                    dr = DreyfusIMR(self.__graph.contracted_regions[j][0], terminals=[n1, n2, n3],
                                                    contract_graph=False)
                                    st = dr.steiner_tree()
                                    d1, _ = st.compute_total_weights()
                                    # # Use the medoid to compute the internal distance.
                                    # if self.__use_medoid:
                                    #     medoid = self.__graph.contracted_regions[j][4]
                                    #     d1 = dist_paths[0][tuple(sorted([n1, medoid]))]
                                    #     d2 = dist_paths[0][tuple(sorted([n2, medoid]))]
                                    #     d3 = dist_paths[0][tuple(sorted([n3, medoid]))]
                                    # else:
                                    #     d1 = dist_paths[0][tuple(sorted([n1, n3]))]
                                    #     d2 = dist_paths[0][tuple(sorted([n2, n3]))]
                                # elif j == i:
                                #     d1 = dist_paths[0][tuple(sorted([n1, n2]))]
                        except KeyError:
                            dist = sys.maxint
                        cost = dist + u + d1 + d2 + d3
                        if consider_terminals:
                            if cost < self.__s_d[i][set_d][0]:
                                self.__s_d[i][set_d] = [cost, j, best_subsets]
                                #####################IMPORTANT: NOT COMPLETELY IMPLEMENTED!!!#####################
                        else:
                            if cost < self.__s_d[i][set_d][0] and j not in self.__terminals:
                                entry_node = None
                                if i in self.__graph.contracted_regions:
                                    try:
                                        path = self.__paths[pair_nodes]
                                        if path.index(i) == len(path) - 1:
                                            entry_node = path[len(path) - 2]
                                        else:
                                            entry_node = path[1]
                                    except KeyError:
                                        pass
                                self.__s_d[i][set_d] = [cost, j, best_subsets, entry_node]
        #
        sets_e = self.__create_subsets_e(set_c)
        #
        if self.__poi not in self.__s_d:
            self.__s_d[self.__poi] = {set_c: [sys.maxint, None, (None, None), None]}
        else:
            self.__s_d[self.__poi][set_c] = [sys.maxint, None, (None, None), None]
        #
        for j in self.__nodes:
            u = sys.maxint
            best_subsets = None
            for set_e in sets_e:
                set_f = tuple(sorted(list(set(set_c) - set(set_e))))
                if len(set_f) > 0:
                    s = self.__s_d[j][set_e][0] + self.__s_d[j][set_f][0]
                else:
                    s = self.__s_d[j][set_e][0]
                if s < u:
                    u = s
                    best_subsets = (set_e, set_f)
            pair_nodes = tuple(sorted([self.__poi, j]))
            # d_n1_n3 = d_n2_n3 = 0
            d1 = d2 = d3 = 0
            try:
                dist = self.__dist[pair_nodes]
                if j in self.__graph.contracted_regions and best_subsets is not None:
                    e_n_1 = self.__s_d[j][best_subsets[0]][3]
                    e_n_2 = self.__s_d[j][best_subsets[1]][3]
                    path = self.__paths[pair_nodes]
                    if len(path) > 1:
                        if path.index(j) == len(path) - 1:
                            e_n_3 = path[len(path) - 2]
                        else:
                            e_n_3 = path[1]
                        dropped_edges = self.__graph[j][2]['dropped_edges']
                        dist_paths = self.__graph[j][2]['dist_paths']
                        n1 = dropped_edges[e_n_1]
                        n2 = dropped_edges[e_n_2]
                        n3 = dropped_edges[e_n_3]
                        dr = DreyfusIMR(self.__graph.contracted_regions[j][0], terminals=[n1, n2, n3], contract_graph=False)
                        st = dr.steiner_tree()
                        d1, _ = st.compute_total_weights()
                        # Use the medoid to compute the internal distance.
                        # if self.__use_medoid:
                        #     medoid = self.__graph.contracted_regions[j][4]
                        #     d1 = dist_paths[0][tuple(sorted([n1, medoid]))]
                        #     d2 = dist_paths[0][tuple(sorted([n2, medoid]))]
                        #     d3 = dist_paths[0][tuple(sorted([n3, medoid]))]
                        # else:
                        #     d1 = dist_paths[0][tuple(sorted([n1, n3]))]
                        #     d2 = dist_paths[0][tuple(sorted([n2, n3]))]
            except KeyError:
                dist = sys.maxint
            cost = dist + u + d1 + d2 + d3
            if consider_terminals:
                if cost < self.__s_d[self.__poi][set_c][0]:
                    self.__s_d[self.__poi][set_c] = [cost, j, best_subsets]
                    #####################IMPORTANT: NOT COMPLETELY IMPLEMENTED!!!#####################
            else:
                if cost < self.__s_d[self.__poi][set_c][0] and j not in self.__terminals:
                    self.__s_d[self.__poi][set_c] = [cost, j, best_subsets, None]

        # Reconstruct the Steiner by backtracking
        steiner_tree = self.__build_steiner_tree_bactracking(self.__poi, set_c)

        if self.__contract_graph:
            self.__decontract_steiner_tree(steiner_tree)

        return steiner_tree