def _distance(self, targetevent, events):
		'''
			Find similar games(events) with naive distance
			todo: normalize to similar length
			return Game object with optimal game
		'''
		SCORE_INIT = 99999
		#Global scores
		bestscore = SCORE_INIT
		bestscore2 = SCORE_INIT
		game = Game('', '')
		for event in events:
			localresult1 = 0
			localresult2 = 0
			for targ in targetevent.data:
				tmin, tdescription = targ[0], targ[1]
				preres = list(map(lambda x: -1 if x[1] != tdescription else (abs(tmin - x[0])), event.data))
				res = abs(sum(preres))
				minuscount = len(list(filter(lambda x: x == -1, preres)))
				localresult1 += minuscount
				localresult2 += res
			if localresult1 < bestscore and localresult2 < bestscore2:
				bestscore = localresult1
				bestscore2 = localresult2
				game = event
		return game
    def _chooseDefenceCenter(self, team, opteam, num):
        """ Get optimal Defender to center """
        players = list(getPlayersFromTeamByPos(self.teamdata, team, 'D(C)'))
        params = ['TotalTackles', 'AerialWon', 'Rating','OffsidesWon','GameStarted',\
         'ShotsBlocked', LASTNAME]
        tomaxvalues = self._getParamValues(players, params)
        tominvalues = self._getParamValues(
            players, ['AerialLost', 'Dispossesed', 'Yellow', LASTNAME])
        if len(tomaxvalues) > 1:
            maxv = self._optimalPlayers(np.array(tomaxvalues), np.argmax, num,
                                        players)
        else:
            maxv = tomaxvalues[0][-1:]

        if len(tominvalues) > 1:
            minv = self._optimalPlayers(np.array(tominvalues), np.argmin, num,
                                        players)
        else:
            minv = tominvalues[0][-1:]

        #if same players both in maxv and minv append in result list
        data = list(set(maxv).intersection(set(minv)))
        if len(data) < num:
            return data + list(
                map(
                    lambda x: x[LASTNAME],
                    self._getFromAnotherPos(team, 'D(C)', num - len(data),
                                            data)))
        #self._opteamOptimal(self.fwparams, opteam, players)
        size = len(data)
        if size == 2: return data
        else: return data + list(filter(lambda x: x not in data, maxv))
	def mostFreqEvents(self, startmin,  endmin, *args, **kwargs):
		""" Get Most frequent events from startmin until endmin 
			sample - Get sample from n games
		"""
		if( isinstance(startmin, int) != True or isinstance(endmin, int) != True):
			raise LiveGameAnalysisException("Time need to be in int format")
		if(startmin > endmin):
			raise LiveGameAnalysisException("Starttime can't be greather then endtime")
		sample = kwargs.get('sample')
		if sample != None:
			return self._sampleCase(startmin, endmin, self.data, sample)
		preresult = []
		sampledata = kwargs.get('data')
		data = self.data if sampledata == None else sampledata
		for game in data:
			if len(data[game]) > 0:
				filtering = list(
					map(lambda x: x[1], 
					filter(lambda x: x[0] >= startmin and x[0] <= endmin,\
					self.data[game][0])))
				preresult += filtering
		if len(preresult) > 0:
			limit = kwargs.get('limit',0)
			count = Counter(preresult)
			lim = len(preresult) if limit == 0 else limit
			return count.most_common()[0:lim]
    def _distance(self, targetevent, events):
        '''
			Find similar games(events) with naive distance
			todo: normalize to similar length
			return Game object with optimal game
		'''
        SCORE_INIT = 99999
        #Global scores
        bestscore = SCORE_INIT
        bestscore2 = SCORE_INIT
        game = Game('', '')
        for event in events:
            localresult1 = 0
            localresult2 = 0
            for targ in targetevent.data:
                tmin, tdescription = targ[0], targ[1]
                preres = list(
                    map(
                        lambda x: -1 if x[1] != tdescription else
                        (abs(tmin - x[0])), event.data))
                res = abs(sum(preres))
                minuscount = len(list(filter(lambda x: x == -1, preres)))
                localresult1 += minuscount
                localresult2 += res
            if localresult1 < bestscore and localresult2 < bestscore2:
                bestscore = localresult1
                bestscore2 = localresult2
                game = event
        return game
    def mostFreqEvents(self, startmin, endmin, *args, **kwargs):
        """ Get Most frequent events from startmin until endmin 
			sample - Get sample from n games
		"""
        if (isinstance(startmin, int) != True
                or isinstance(endmin, int) != True):
            raise LiveGameAnalysisException("Time need to be in int format")
        if (startmin > endmin):
            raise LiveGameAnalysisException(
                "Starttime can't be greather then endtime")
        sample = kwargs.get('sample')
        if sample != None:
            return self._sampleCase(startmin, endmin, self.data, sample)
        preresult = []
        sampledata = kwargs.get('data')
        data = self.data if sampledata == None else sampledata
        for game in data:
            if len(data[game]) > 0:
                filtering = list(
                 map(lambda x: x[1],
                 filter(lambda x: x[0] >= startmin and x[0] <= endmin,\
                 self.data[game][0])))
                preresult += filtering
        if len(preresult) > 0:
            limit = kwargs.get('limit', 0)
            count = Counter(preresult)
            lim = len(preresult) if limit == 0 else limit
            return count.most_common()[0:lim]
  def initial_simplex(self):
    cfg0 = self.initial_simplex_seed()
    simplex = [cfg0]
    params = self.manipulator.parameters(cfg0)
    params = list(filter(lambda x: x.is_primitive(), params))
    if len(params) == 0:
      return simplex

    q = (((math.sqrt(len(params) + 1.0) - 1.0) / (len(params) * math.sqrt(2.0)))
         * self.initial_unit_edge_length)
    p = q + ((1.0 / math.sqrt(2.0)) * self.initial_unit_edge_length)

    base = [x.get_unit_value(cfg0) for x in params]
    for j in xrange(len(base)):
      if max(p, q) + base[j] > 1.0:
        #flip this dimension as we would overflow our [0,1] bounds
        base[j] *= -1.0

    for i in xrange(len(params)):
      simplex.append(self.manipulator.copy(cfg0))
      params[i].set_unit_value(simplex[-1], abs(base[i] + p))
      for j in xrange(i + 1, len(params)):
        params[j].set_unit_value(simplex[-1], abs(base[i] + q))

    return simplex
	def _chooseDefenceCenter(self, team, opteam, num):
		""" Get optimal Defender to center """
		players = list(getPlayersFromTeamByPos(self.teamdata, team, 'D(C)'))
		params = ['TotalTackles', 'AerialWon', 'Rating','OffsidesWon','GameStarted',\
		 'ShotsBlocked', LASTNAME]
		tomaxvalues = self._getParamValues(players, params)
		tominvalues = self._getParamValues(players,['AerialLost','Dispossesed','Yellow', LASTNAME])
		if len(tomaxvalues) > 1:
			maxv = self._optimalPlayers(np.array(tomaxvalues), np.argmax, num, players)
		else:
			maxv = tomaxvalues[0][-1:]

		if len(tominvalues) > 1:
			minv = self._optimalPlayers(np.array(tominvalues), np.argmin, num, players)
		else:
			minv = tominvalues[0][-1:]

		#if same players both in maxv and minv append in result list
		data = list(set(maxv).intersection(set(minv)))
		if len(data) < num:
			return data + list(map(lambda x: x[LASTNAME], self._getFromAnotherPos(team, 'D(C)', num-len(data), data)))
		#self._opteamOptimal(self.fwparams, opteam, players)
		size = len(data)
		if size == 2: return data
		else: return data + list(filter(lambda x: x not in data, maxv))
 def query(self, value, *args, **kwargs):
     if value == None:
         raise Exception("This query is empty")
     if self.calculation != None:
         matches = self.calculation.get()
         if isinstance(matches, MatchesData):
             afunc = lambda results: list(filter(lambda game: value(len(game)), \
              results))
             result = self._asyncCall(afunc, params=matches.result)
             return result
         if isinstance(matches, PlayerData):
             afunc = lambda results, val: list(filter(lambda x: val(x[0]), \
              results))
             return afunc(matches.data, value)
             #return self._asyncCall(afunc, params=(matches.data,value, )).get()
     else:
         print("WHEN CALCULATION IS ZERO", self.preresult)
	def query(self, value,*args,**kwargs):
		if value == None:
			raise Exception("This query is empty")
		if self.calculation != None:
			matches = self.calculation.get()
			if isinstance(matches, MatchesData):
				afunc = lambda results: list(filter(lambda game: value(len(game)), \
					results))
				result = self._asyncCall(afunc, params=matches.result)
				return result
			if isinstance(matches, PlayerData):
				afunc = lambda results, val: list(filter(lambda x: val(x[0]), \
					results))
				return afunc(matches.data, value)
				#return self._asyncCall(afunc, params=(matches.data,value, )).get()
		else:
			print("WHEN CALCULATION IS ZERO", self.preresult)
    def _opteamOptimal(self, params, opteam, teamdata):
        '''
			Best players from opposite team
		'''
        gs = 'GameStarted'
        opplayers = list(filter(lambda x:x[gs] > 0, \
         getPlayersFromTeamByPos(self.teamdata, opteam, 'FW')))
        #values = list(filter(lambda x: x[-1:][0] > 0, self._getParamValues(opplayers, params)))
        for v in params.keys():
            #print(opplayers)
            for player in teamdata:
                #preresult5 = list(F() << (_/player[gs]) << (filter, _ > 0))
                preresult = list(
                 map(_/player[gs],
                 filter(_ > 0, \
                 map(lambda x: player[x], params[v]))
                 ))
                print(preresult)
	def _opteamOptimal(self, params, opteam, teamdata):
		'''
			Best players from opposite team
		'''
		gs = 'GameStarted'
		opplayers = list(filter(lambda x:x[gs] > 0, \
			getPlayersFromTeamByPos(self.teamdata, opteam, 'FW')))
		#values = list(filter(lambda x: x[-1:][0] > 0, self._getParamValues(opplayers, params)))
		for v in params.keys():
			#print(opplayers)
			for player in teamdata:
				#preresult5 = list(F() << (_/player[gs]) << (filter, _ > 0))
				preresult = list(
					map(_/player[gs],
					filter(_ > 0, \
					map(lambda x: player[x], params[v]))
					))
				print(preresult)
	def event(self, query):
		if query in self._playerParams:
			teams = list(self.data.teams.keys())
			for team in teams:
				info = self.data.teams[team]
				result = list(filter(lambda x: x[LASTNAME] == self.target, info))
				if len(result) > 0:
					return result[0][query]
		return None
 def event(self, query):
     if query in self._playerParams:
         teams = list(self.data.teams.keys())
         for team in teams:
             info = self.data.teams[team]
             result = list(
                 filter(lambda x: x[LASTNAME] == self.target, info))
             if len(result) > 0:
                 return result[0][query]
     return None
	def _countTargetEventHelp(self, event, startmin, endmin):
		for name in self.data:
			evt = self.data[name]
			if len(evt) > 0:
				if endmin == 0 and startmin != 0:
					#Not tested!
					count_events = len(list(lambda x: x[1] ==  event and \
						x[0] <= startmin, evt[0]))
				count_events = len(list(filter(lambda x: x[1] == event, evt[0])))
				yield(evt[1], count_events)
def getPlayersByParams(teamdatas, params):
    '''
		List of params for all players from all teams
	'''
    teams = list(teamdatas.keys())
    allparams = list(teamdatas[teams[0]][0].keys())
    for team in teams:
        for player in teamdatas[team]:
            yield (list(map(lambda y: player[y], \
             list(filter(lambda x: x in params, allparams)))))
def getPlayersByParams(teamdatas, params):
	'''
		List of params for all players from all teams
	'''
	teams = list(teamdatas.keys())
	allparams = list(teamdatas[teams[0]][0].keys())
	for team in teams:
		for player in teamdatas[team]:
			yield (list(map(lambda y: player[y], \
				list(filter(lambda x: x in params, allparams)))))
 def _countTargetEventHelp(self, event, startmin, endmin):
     for name in self.data:
         evt = self.data[name]
         if len(evt) > 0:
             if endmin == 0 and startmin != 0:
                 #Not tested!
                 count_events = len(list(lambda x: x[1] ==  event and \
                  x[0] <= startmin, evt[0]))
             count_events = len(
                 list(filter(lambda x: x[1] == event, evt[0])))
             yield (evt[1], count_events)
	def _sampleCase(self, startmin, endmin, data, size):
		""" Return random sample with size in data
			with 
		"""
		sto = list(map(lambda x: data[x], data))
		sampledata = np.random.choice(sto,size)
		result = []
		for game in sampledata:
			if len(game) > 0:
				result += list(
						map(lambda x: x[1], 
						filter(lambda x: x[0] >= startmin and x[0] <= endmin,\
						game[0])))
		return Counter(result).most_common()
 def initial_simplex(self):
   cfg0 = self.initial_simplex_seed()
   simplex = [cfg0]
   params = self.manipulator.parameters(cfg0)
   params = filter(lambda x: x.is_primitive(), params)
   for p in params:
     simplex.append(self.manipulator.copy(cfg0))
     v = p.get_unit_value(simplex[-1])
     if v <= 0.5:
       v += self.initial_unit_edge_length
     else:
       v -= self.initial_unit_edge_length
     p.set_unit_value(simplex[-1], v)
   return simplex
		def optimalInner(matr, func, num, players, res=set()):
			c = Counter(func(matr, axis=0)).most_common(num)
			result = set(map(lambda x: players[x[0]][LASTNAME], c))
			if len(result) == num: 
				res |= result
				return False, list(res)
			idxs = list(filter(lambda x: players[x][LASTNAME] in result, \
				range(len(players))))
			temp = matr.tolist()
			for i in idxs:
				del players[i]
				del temp[i]
			res |= result
			return True, (np.array(temp), func, num-len(result), players, res)
    def _sampleCase(self, startmin, endmin, data, size):
        """ Return random sample with size in data
			with 
		"""
        sto = list(map(lambda x: data[x], data))
        sampledata = np.random.choice(sto, size)
        result = []
        for game in sampledata:
            if len(game) > 0:
                result += list(
                  map(lambda x: x[1],
                  filter(lambda x: x[0] >= startmin and x[0] <= endmin,\
                  game[0])))
        return Counter(result).most_common()
Exemple #22
0
    def _add_cheapest_travelcard(self, destination: Station, origin: Station, season_ticket: Optional[SeasonTicket]) -> JourneyCosts:

        possible_travelcards = self._get_possible_travelcards(destination, origin)

        filter_null_results = filter(lambda tc: tc is not None)

        cheapest: Pipe[Travelcard] = Pipe(possible_travelcards) >> \
            filter_null_results >> \
            sort(lambda tc: tc.annual_price) >> \
            first

        if cheapest.value is None:
            raise JourneyCostError("No travelcard found for {} to {}".format(origin.name, destination.name))

        return JourneyCosts(season_ticket, cheapest.value)
 def optimalInner(matr, func, num, players, res=set()):
     c = Counter(func(matr, axis=0)).most_common(num)
     result = set(map(lambda x: players[x[0]][LASTNAME], c))
     if len(result) == num:
         res |= result
         return False, list(res)
     idxs = list(filter(lambda x: players[x][LASTNAME] in result, \
      range(len(players))))
     temp = matr.tolist()
     for i in idxs:
         del players[i]
         del temp[i]
     res |= result
     return True, (np.array(temp), func, num - len(result), players,
                   res)
    def _getFromAnotherPos(self, team, pos, num, stored):
        """
		'plan b', get players from another positions
			in case when no players in the target pos.

			arguments:
			team - target team
			pos - current pos
			num - number of players needed
			stored - already chosen players

			return: list of players(raw)

			TODO: set ranking
		"""
        anotherpos = pos[0:pos.find('(')]
        return list(filter(lambda x: anotherpos in x['PositionShort'] and\
                          x[LASTNAME] not in stored
         , self.teamdata[team]))[0:num]
	def _getFromAnotherPos(self, team, pos, num, stored):
		"""
		'plan b', get players from another positions
			in case when no players in the target pos.

			arguments:
			team - target team
			pos - current pos
			num - number of players needed
			stored - already chosen players

			return: list of players(raw)

			TODO: set ranking
		"""
		anotherpos = pos[0:pos.find('(')]
		return list(filter(lambda x: anotherpos in x['PositionShort'] and\
							             x[LASTNAME] not in stored
			, self.teamdata[team]))[0:num]
	def runPlayer(self):
		self.ifParamsNotEmpty()
		findlastname = lambda name: list(filter(lambda x: name in x, self.preresult))
		result = []
		dictresult =[]
		value = self.value
		for team in self.useddata.keys():
			for player in self.useddata[team]:
				target = findlastname(player[LASTNAME])
				if len(target) > 0:
					res = list(target[0])
					if value in player:
						dictdata = {}
						dictdata[value] = player[value]
						dictdata['lastname'] = player[LASTNAME]
						res.append(player[value])
						result.append(res)
						dictresult.append(dictdata)
		return result 
 def runPlayer(self):
     self.ifParamsNotEmpty()
     findlastname = lambda name: list(
         filter(lambda x: name in x, self.preresult))
     result = []
     dictresult = []
     value = self.value
     for team in self.useddata.keys():
         for player in self.useddata[team]:
             target = findlastname(player[LASTNAME])
             if len(target) > 0:
                 res = list(target[0])
                 if value in player:
                     dictdata = {}
                     dictdata[value] = player[value]
                     dictdata['lastname'] = player[LASTNAME]
                     res.append(player[value])
                     result.append(res)
                     dictresult.append(dictdata)
     return result
 def getGames(self, name):
     """ Get games where contains 'name' (as team)"""
     teams = self.games.keys()
     return list(
         map(lambda m: self.games[m],
             filter(lambda x: name in x.split(), teams)))
 def _getBetweenMinutes(self, game, startmin, endmin):
     """ Get game between startmin and endmin """
     data, info = game
     return Game(list(reversed(list(filter(lambda x: x[0] >= startmin and \
      x[0] <= endmin, data)))), info)
def getPlayer(teamdata, lastname):
	""" 
	teamdata - dict with all teams
	Return target player from team by last name """
	return list(filter(lambda x: x[LASTNAME] == lastname, teamdata))[0]
 def extractInfo(self, data, targteam):
     result = list(filter(lambda x: x[2].find(targteam) != -1, data))
     rating = self._getRating(result)
     minuts = list(self._getGamesUntilMinute(25))
	def _innerFilter(self, func, elements):
		""" 
			Filtering elements from datastore(self.data) or from already prepared (data)
		"""
		return list(filter(func, elements))
	def extractInfo(self, data, targteam):
		result = list(filter(lambda x: x[2].find(targteam) != -1, data))
		rating = self._getRating(result)
		minuts = list(self._getGamesUntilMinute(25))
 def _filterUsed(self, players, stored):
     """ Reject players wich alread in stored """
     return list(filter(lambda x: x[LASTNAME] not in stored, players))
	def getGames(self, name):
		""" Get games where contains 'name' (as team)"""
		teams = self.games.keys()
		return list(map(lambda m: self.games[m], filter(lambda x: name in x.split(), teams)))
	def _filterUsed(self, players, stored):
		""" Reject players wich alread in stored """
		return list(filter(lambda x: x[LASTNAME] not in stored, players))
def getPlayersFromTeamByPos(teamsdata, team, pos):
	""" Return all players in target pos.
	For example all forwards from team """
	return list(filter(lambda x: x['positionshort'] == pos, teamsdata[team]))
 def cfg_to_str(self, cfg):
   params = list(filter(Parameter.is_primitive,
                        self.manipulator.parameters(cfg)))
   params.sort(key=_.name)
   return str(tuple([x.get_unit_value(cfg) for x in params]))
    def _innerFilter(self, func, elements):
        """ 
			Filtering elements from datastore(self.data) or from already prepared (data)
		"""
        return list(filter(func, elements))
Exemple #40
0
 def inner(self):
     return head(filter(bool, map(fn, self.comments.all())))
	def _getBetweenMinutes(self, game, startmin, endmin):
		""" Get game between startmin and endmin """
		data, info = game
		return Game(list(reversed(list(filter(lambda x: x[0] >= startmin and \
			x[0] <= endmin, data)))), info)
Exemple #42
0
 def test_filter_withList(self):
     out = list(iters.filter(_ < 10, [1, 2, 11]))
     self.assertEqual([1, 2], out)
     self.assertEqual(list, type(out))
def getPlayersFromTeamByPos(teamsdata, team, pos):
    """ Return all players in target pos.
	For example all forwards from team """
    return list(filter(lambda x: x['positionshort'] == pos, teamsdata[team]))
Exemple #44
0
 def test_filter_withTuple(self):
     out = tuple(iters.filter(_ < 10, (1, 2, 11)))
     self.assertEqual((1, 2), out)
     self.assertEqual(tuple, type(out))
 def cfg_to_str(self, cfg):
   params = list(filter(Parameter.is_primitive,
                        self.manipulator.parameters(cfg)))
   params.sort(key=_.name)
   return str(tuple(map(lambda x: x.get_unit_value(cfg), params)))
def getPlayer(teamdata, lastname):
    """ 
	teamdata - dict with all teams
	Return target player from team by last name """
    return list(filter(lambda x: x[LASTNAME] == lastname, teamdata))[0]