Пример #1
0
    def predict(self, X):
        y = np.zeros(len(X))
        for i,x in enumerate(X): # test points
            sd = SortedDict() # distance -> class
            for j,xt in enumerate(self.X): # training points
                d = np.linalg.norm(x - xt)
                # print d, sd
                if len(sd) < self.k:
                        sd[d] = self.y[j]
                else:
                    last = sd.viewkeys()[-1]
                    if d < last:
                        del sd[last]
                        sd[d] = self.y[j]
            # print "sd:", sd

            # vote
            votes = {}
            # print "viewvalues:", sd.viewvalues()
            for v in sd.viewvalues():
                # print "v:", v
                votes[v] = votes.get(v,0) + 1
            # print "votes:", votes, "true:", Ytest[i]
            max_votes = 0
            max_votes_class = -1
            for v,count in votes.iteritems():
                if count > max_votes:
                    max_votes = count
                    max_votes_class = v
            y[i] = max_votes_class
        return y
Пример #2
0
 def predict(self, X):
     y = np.zeros(len(X))
     for i, x in enumerate(X):  # test points
         sd = SortedDict()  # distance -> class
         for j, xt in enumerate(self.X):  # training points
             d = np.linalg.norm(x - xt)
             # print d, sd
             if len(sd) < self.k:
                 sd[d] = self.y[j]
             else:
                 last = sd.viewkeys()[-1]
                 if d < last:
                     del sd[last]
                     sd[d] = self.y[j]
         # print "sd:", sd
         # vote
         votes = {}
         # print "viewvalues:", sd.viewvalues()
         for v in sd.viewvalues():
             # print "v:", v
             votes[v] = votes.get(v, 0) + 1
         # print "votes:", votes, "true:", Ytest[i]
         max_votes = 0
         max_votes_class = -1
         for v, count in votes.iteritems():
             if count > max_votes:
                 max_votes = count
                 max_votes_class = v
         y[i] = max_votes_class
     return y
Пример #3
0
from random import choice
from itertools import cycle
from sortedcontainers import SortedDict
from collections import OrderedDict

players = {1: 'a', 2: 'b', 3: 'c'}

sd = SortedDict(players)

print(sd)
sd.index('a')
sdc = cycle(sd.viewvalues())

print(next(sdc))
sd.pop(2)
print(next(sdc))

print(next(sdc))

# class Players(OrderedDict):
# 	def __iter__(self):
# 		return iter(self.values())

# 	def __next__(self):
# 		return

# 	def choose_starting_player(self):
# 		self.players = list(self.values())
# 		starting_player = choice(list(self.values()))
# 		self.i = list(self.items())
# 		print(self.i)
Пример #4
0
class App(GUI, InputHandler):
    def __init__(self):
        self.running = True
        pg.init()
        self.screen = pg.display.set_mode(SCREENSIZE)
        pg.display.set_caption("Mensch ärgere dich nicht! :)")
        self.boardsize = self.screen.get_height()
        self.boardorigin = (self.boardsize // 2, self.boardsize // 2)

        self.background = pg.Surface(self.screen.get_size()).convert()
        self.background.fill(BG_COLOR)
        self.screen.blit(self.background, (0, 0))

        # Init spritegroups
        self.allfields = NumberedGroup()
        self.boardfields = NumberedGroup()
        self.homefields = NumberedGroup()
        self.allmeeples = NumberedGroup()
        self.die_group = pg.sprite.GroupSingle()
        self.allsprites = AllSpritesGroup()

    def pregame_menu(self):
        """Set up the participating players and choose a random starting player
		"""
        self.players = SortedDict({
            _id: Player(_id, **config)
            for _id, config in player_default_config.items()
        })
        self.players_cycle = cycle(self.players.viewvalues())
        # set random starting player and synchronize the cycle
        self.active_player = choice(self.players.values())
        while next(self.players_cycle) != self.active_player:
            continue

    def on_execute(self):
        GUI.__init__(self)
        self.allfields.add(self.boardfields, self.homefields)
        self.allsprites.add(self.allmeeples, self.die)
        while self.running:
            if len(self.players) <= 1:
                self.running = False
            if self.active_player.meeples_out == 4:
                self.active_player.number_throws = 3
            else:
                self.active_player.number_throws = 1
            print(self.active_player.name, "am Zug!")
            while self.active_player.number_throws > 0:
                for event in pg.event.get():
                    self.on_event(event)
                self.on_loop()
                self.render()
            if self.active_player.meeples_home == 4:
                print("Glückwunsch! {} hat gewonnen".format(
                    self.active_player.name))
                del self.active_player
            self.active_player = next(self.players_cycle)

    def on_loop(self):
        self.active_player.meeples.update()

    def render(self):
        self.background.fill(BG_COLOR)
        self.screen.blit(self.background, (0, 0))
        self.allfields.draw(self.screen)
        self.allmeeples.draw(self.screen)
        self.die_group.draw(self.screen)
        pg.display.flip()
Пример #5
0
def WalkTrap(curr_infilename, t, indir, outdir):
    outfilename = '%s_t%s_output' % (curr_infilename, t)
    calcfilename = '%s_t%s_calc' % (curr_infilename, t)
    txt = '.txt'

    infilename = indir + curr_infilename + txt
    outfilename = outdir + outfilename + txt
    calcfilename = outdir + calcfilename + txt

    global outfile
    global calcfile
    outfile = open(outfilename, 'w')
    calcfile = open(calcfilename, 'w')

    print_no_newline('!IMPORTANT! -> t = %s\n\n' % t)

    # retrieve the graph with self-edges, total number of vertices and mapping to original indices
    (G, n, reverse_mapping) = load_graph(infilename)
    rangen = range(n)
    P_t = get_P_t(G, t, rangen)  # the Pt matrix from the question set and
    Deg = dict()  # degree of each vertex
    Ccard = dict(
    )  # the mapping of community indices to their respective cardinality
    CDP_t = dict(
    )  # the mapping of community indices to their respective D^-(1/2)*P_t_C.
    Cneig = dict(
    )  # the mapping of community indices to their "neighbour" communities (ones who share a direct edge to them)
    C1C2_to_sigma = dict(
    )  # the mapping of two adjacent community indices to their respective sigma (assumed to be unique enough!)
    unsorted_sigma_to_C1C2 = dict(
    )  # a mapping of sigmas (updated with new values regularly)
    merge_order = [
    ]  # a list of tuples in set merge order ((C1,C2) means C1 and C2 were merged to C1)

    print_with_timestep('Calculating D and smaller things...')

    for v in rangen:
        Ccard[v] = 1.0
        Deg[v] = len(G[v]) - 1
        Cneig[v] = set()
        for elem in G[v]:
            Cneig[v].add(elem)
        Cneig[v].remove(v)  # remove the redundant "self" element from the set

    print_with_timestep('Calculating D and DP_t...')
    D = dict()
    for v in rangen:
        D[v] = 1.0 / sqrt(Deg[v] + 1)

    visual_counter = 0
    for v in rangen:
        visual_counter = increment_visual_counter(visual_counter, 0)
        pt = P_t[v, :]
        indexes = pt.indices
        data = pt.data
        CDP_t[v] = SparseVec(indices=[], value=defaultdict(lambda: 0.0))
        for (pos, index) in enumerate(indexes):
            CDP_t[v].indices.append(index)
            CDP_t[v].value[index] = data[pos] * D[index]
        CDP_t[v].indices.sort()

    increment_visual_counter(visual_counter, 1)
    print_with_timestep('Finished calculating D and DP_t...')

    print_with_timestep('Explicitly delete G, P_t and Deg...')
    # explicitly get rid of G to cut down on memory
    for v in rangen:
        G[v] = None
    del G
    del P_t
    del Deg
    print_with_timestep('Finished deleting G, P_t and Deg...')

    print_with_timestep('Setting up the structures...')
    visual_counter = 0
    for C1 in rangen:
        for C2 in Cneig[C1]:
            visual_counter = increment_visual_counter(visual_counter, 0)

            if not (C1, C2) in C1C2_to_sigma and C1 < C2:
                sigmaC1C2 = delta_sigma_C1C2(n, Ccard[C1], Ccard[C2],
                                             CDP_t[C1], CDP_t[C2])
                C1C2_to_sigma[(C1, C2)] = sigmaC1C2
                if sigmaC1C2 not in unsorted_sigma_to_C1C2:
                    unsorted_sigma_to_C1C2[sigmaC1C2] = SortedSet()
                unsorted_sigma_to_C1C2[sigmaC1C2].add((C1, C2))

    increment_visual_counter(visual_counter, 1)
    sigma_to_C1C2 = SortedDict(
        unsorted_sigma_to_C1C2
    )  # a constantly sorted mapping of sigmas (updated with new values regularly)

    visual_counter = 0
    # iterate through all merges
    print_with_timestep('About to start the algo...')
    rangen1 = range(n - 1)
    for _ in rangen1:
        visual_counter = increment_visual_counter(visual_counter, 0)

        # select the minimum element in the sorted set, record and remove it
        if len(sigma_to_C1C2.viewvalues()) == 0:
            break
        (C1, C2) = sigma_to_C1C2.viewvalues()[0][0]
        sigmaC1C2 = C1C2_to_sigma[(C1, C2)]
        merge_order.append((C1, C2, sigmaC1C2))
        del C1C2_to_sigma[(C1, C2)]
        del sigma_to_C1C2[sigmaC1C2][0]
        if len(sigma_to_C1C2[sigmaC1C2]) <= 0:
            del sigma_to_C1C2[sigmaC1C2]

        # calculate the values for the new community
        DP_t_C3 = SparseVec(indices=sorted_union(CDP_t[C1].indices,
                                                 CDP_t[C2].indices),
                            value=defaultdict(lambda: 0.0))
        c1card = Ccard[C1]
        c2card = Ccard[C2]
        cardC3 = Ccard[C1] + Ccard[C2]
        for index in DP_t_C3.indices:
            DP_t_C3.value[index] = (c1card * CDP_t[C1].value[index] +
                                    c2card * CDP_t[C2].value[index]) / cardC3

        # determine which tuples need updating and resolve maintenance things
        updatePoints = [C1, C2]
        oldkeyMap = dict()  # saved mapping of old keys to sigmas
        updatePairs = set()
        for A in updatePoints:
            neighbours = Cneig[A]
            for B in neighbours:
                oldkey = get_min_pair(A, B)
                if oldkey == (C1, C2):
                    continue
                newkey = oldkey
                if A == C2:
                    newkey = get_min_pair(C1, B)
                remove_elem(sigma_to_C1C2, C1C2_to_sigma, oldkeyMap, oldkey)
                if not (newkey, B) in updatePairs:
                    updatePairs.add((newkey, B))
                if (A == C2):
                    Cneig[B].remove(C2)
                    Cneig[B].add(C1)

        # update the sigma mappings
        for (newpair, C) in updatePairs:
            newsigma = delta_sigma_C3C(Ccard, C1, C2, C, oldkeyMap, sigmaC1C2,
                                       CDP_t, DP_t_C3, n)
            add_elem(sigma_to_C1C2, C1C2_to_sigma, newpair, newsigma)

        # finally update the relevant values of the sets
        CDP_t[C1] = DP_t_C3
        del CDP_t[C2]
        neigC3 = Cneig[C1].union(Cneig[C2])
        neigC3.remove(C1)
        neigC3.remove(C2)
        Cneig[C1] = neigC3
        del Cneig[C2]
        Ccard[C1] = cardC3
        del Ccard[C2]

    increment_visual_counter(visual_counter, 1)
    print_with_timestep('Algo completed...')

    print_no_newline('\n')
    print_with_timestep('Merging order:')
    for (idx, (a, b, sigma)) in enumerate(merge_order):
        print_no_newline('%s: [%s, %s, %s]\n' % (idx, a, b, sigma))

    # compute the optimal partitioning according to metric eta
    sigma_prev = 0
    max_eta = 0
    max_iter = 0
    for (idx, (a, b, sigma)) in enumerate(merge_order):
        if idx == 0:
            sigma_prev = sigma
        else:
            eta = sigma / sigma_prev
            if eta > max_eta:
                max_eta = eta
                max_iter = idx
            sigma_prev = sigma

    sets = SortedDict()
    for i in rangen:
        sets[i] = SortedSet()
        sets[i].add(reverse_mapping[i])

    range_max_iter = range(max_iter)
    for i in range_max_iter:
        (a, b, sigma) = merge_order[i]
        sets[a] = sets[a].union(sets[b])
        del sets[b]

    print_no_newline('\n')
    print_with_timestep('Optimal solution (eta = %s, max_iter = %s):' %
                        (max_eta, max_iter))
    for idx in sets:
        range_sets_idx = range(len(sets[idx]))
        for i in range_sets_idx:
            print_calcfile(str(sets[idx][i]))
            if i < len(sets[idx]) - 1:
                print_calcfile(' ')
        print_calcfile('\n')

    # fancy_plot(n, merge_order, reverse_mapping)

    outfile.close()
    calcfile.close()
Пример #6
0
class DotMap(MutableMapping):

    def __init__(self, *args, **kwargs):
        self._map = SortedDict()
        if args:
            d = args[0]
            if type(d) is dict:
                for k, v in self.__call_items(d):
                    if type(v) is dict:
                        v = DotMap(v)
                    self._map[k] = v
        if kwargs:
            for k, v in self.__call_items(kwargs):
                self._map[k] = v

    @staticmethod
    def __call_items(obj):
        if hasattr(obj, 'iteritems') and ismethod(getattr(obj, 'iteritems')):
            return obj.iteritems()
        else:
            return obj.items()

    def items(self):
        return self.iteritems()

    def iteritems(self):
        return self.__call_items(self._map)

    def __iter__(self):
        return self._map.__iter__()

    def __setitem__(self, k, v):
        self._map[k] = v

    def __getitem__(self, k):
        if k not in self._map:
            # automatically extend to new DotMap
            self[k] = DotMap()
        return self._map[k]

    def __setattr__(self, k, v):
        if k == '_map':
            super(DotMap, self).__setattr__(k, v)
        else:
            self[k] = v

    def __getattr__(self, k):
        if k == '_map':
            return self._map
        else:
            return self[k]

    def __delattr__(self, key):
        return self._map.__delitem__(key)

    def __contains__(self, k):
        return self._map.__contains__(k)

    def __str__(self):
        items = []
        for k, v in self.__call_items(self._map):
            items.append('{0}={1}'.format(k, repr(v)))
        out = 'DotMap({0})'.format(', '.join(items))
        return out

    def __repr__(self):
        return str(self)

    def to_dict(self):
        d = {}
        for k, v in self.items():
            if type(v) is DotMap:
                v = v.to_dict()
            d[k] = v
        return d

    def pprint(self):
        pprint(self.to_dict())

    # proper dict subclassing
    def values(self):
        return self._map.values()

    @staticmethod
    def parse_other(other):
        if type(other) is DotMap:
            return other._map
        else:
            return other

    def __cmp__(self, other):
        other = DotMap.parse_other(other)
        return self._map.__cmp__(other)

    def __eq__(self, other):
        other = DotMap.parse_other(other)
        if not isinstance(other, dict):
            return False
        return self._map.__eq__(other)

    def __ge__(self, other):
        other = DotMap.parse_other(other)
        return self._map.__ge__(other)

    def __gt__(self, other):
        other = DotMap.parse_other(other)
        return self._map.__gt__(other)

    def __le__(self, other):
        other = DotMap.parseOther(other)
        return self._map.__le__(other)

    def __lt__(self, other):
        other = DotMap.parse_other(other)
        return self._map.__lt__(other)

    def __ne__(self, other):
        other = DotMap.parse_other(other)
        return self._map.__ne__(other)

    def __delitem__(self, key):
        return self._map.__delitem__(key)

    def __len__(self):
        return self._map.__len__()

    def copy(self):
        return self

    def get(self, key, default=None):
        return self._map.get(key, default)

    def has_key(self, key):
        return key in self._map

    def iterkeys(self):
        return self._map.iterkeys()

    def itervalues(self):
        return self._map.itervalues()

    def keys(self):
        return self._map.keys()

    def pop(self, key, default=None):
        return self._map.pop(key, default)

    def setdefault(self, key, default=None):
        return self._map.setdefault(key, default)

    def viewitems(self):
        if version_info.major == 2 and version_info.minor >= 7:
            return self._map.viewitems()
        else:
            return self._map.items()

    def viewkeys(self):
        if version_info.major == 2 and version_info.minor >= 7:
            return self._map.viewkeys()
        else:
            return self._map.keys()

    def viewvalues(self):
        if version_info.major == 2 and version_info.minor >= 7:
            return self._map.viewvalues()
        else:
            return self._map.values()

    @classmethod
    def fromkeys(cls, seq, value=None):
        d = DotMap()
        d._map = SortedDict.fromkeys(seq, value)
        return d