Example #1
0
def goals(targetEvents, TeamAstring, TeamBstring, exportData, exportDataString,
          exportFullExplanation):

    goals = targetEvents['Goals']
    # To export:
    exportDataString.append('goalCount')
    exportData.append(float(len(goals)))
    exportFullExplanation.append('Number of goals per match.')

    exportDataString.append('goalCountA')
    goalCountA = sum([TeamAstring in i[1] for i in goals])
    exportData.append(float(goalCountA))
    exportFullExplanation.append('Number of goals by %s per match.' %
                                 TeamAstring)

    exportDataString.append('goalCountB')
    goalCountB = sum([TeamBstring in i[1] for i in goals])
    exportData.append(float(goalCountB))
    exportFullExplanation.append('Number of goals by %s per match.' %
                                 TeamBstring)

    exportDataString.append('goalsDelta')
    exportData.append(float(abs(goalCountA - goalCountB)))
    exportFullExplanation.append(
        'Absolute difference between number of goals scored by %s and %s.' %
        (TeamAstring, TeamBstring))

    safetyWarning.checkLengthExport(exportData, exportDataString,
                                    exportFullExplanation)
    return exportData, exportDataString, exportFullExplanation, targetEvents
Example #2
0
def turnovers(window, aggregateEvent, targetEvents, TeamAstring, TeamBstring,
              exportData, exportDataString, exportFullExplanation):
    turnoverCharacteristics = []

    if targetEvents['Turnovers'] != []:
        turnoverCharacteristics = []
        for eventInstant, eventID in targetEvents['Turnovers']:

            if eventInstant > window[0] and eventInstant <= window[1]:
                turnoverCharacteristics.append(eventID)

        # define outcome variables here
        turnoverCount = len(turnoverCharacteristics)
        turnoverCountA = len(
            [i for i in turnoverCharacteristics if TeamAstring in i])
        turnoverCountB = len(
            [i for i in turnoverCharacteristics if TeamBstring in i])
        turnoverDelta = abs(turnoverCountA - turnoverCountB)
    else:  # no 'possession' information, outcome should be missing
        # turnoverCount = None
        # turnoverCountA = None
        # turnoverCountB = None
        # turnoverDelta = None
        return exportData, exportDataString, exportFullExplanation

    # # To export:'
    exportDataString.append('turnoverCount')
    exportData.append(turnoverCount)
    exportFullExplanation.append('Number of turnovers per %s.' %
                                 aggregateEvent)

    exportDataString.append('turnoverCountA')
    exportData.append(turnoverCountA)
    exportFullExplanation.append('Number of turnovers by %s per %s.' %
                                 (TeamAstring, aggregateEvent))

    exportDataString.append('turnoverCountB')
    exportData.append(turnoverCountB)
    exportFullExplanation.append('Number of turnovers by %s per %s.' %
                                 (TeamBstring, aggregateEvent))

    exportDataString.append('turnoverDelta')
    exportData.append(turnoverDelta)
    exportFullExplanation.append(
        'Absolute difference between number of turnovers by %s and %s, per %s.'
        % (TeamAstring, TeamBstring, aggregateEvent))

    safetyWarning.checkLengthExport(exportData, exportDataString,
                                    exportFullExplanation)
    return exportData, exportDataString, exportFullExplanation
Example #3
0
def goals(rawDict, attributeDict, TeamAstring, TeamBstring, exportData,
          exportDataString, exportFullExplanation, targetEvents):
    count = 0
    goals = [i for i in attributeDict['Goal'] if i != '']

    goalsOut = np.ones((len(goals), 2), dtype='int') * -1

    for idx, i in enumerate(attributeDict['Goal']):
        if not i == '':
            goalsOut[count, 1] = rawDict['Time']['TsS'][idx]
            if TeamAstring in i:
                goalsOut[count, 0] = 0
                targetEvents['Goals'].append(
                    (float(rawDict['Time']['TsS'][idx]), TeamAstring))
            elif TeamBstring in i:
                goalsOut[count, 0] = 1
                targetEvents['Goals'].append(
                    (float(rawDict['Time']['TsS'][idx]), TeamBstring))
            else:
                warn('\n\nCould not recognize team:\n<<%s>>' % i)
            count = count + 1

    # To export:
    exportDataString.append('goalCount')
    exportData.append(float(len(goals)))
    exportFullExplanation.append('Number of goals per match.')

    exportDataString.append('goalCountA')
    goalCountA = sum([TeamAstring in i for i in goals])
    exportData.append(float(goalCountA))
    exportFullExplanation.append('Number of goals by %s per match.' %
                                 TeamAstring)

    exportDataString.append('goalCountB')
    goalCountB = sum([TeamBstring in i for i in goals])
    exportData.append(float(goalCountB))
    exportFullExplanation.append('Number of goals by %s per match.' %
                                 TeamBstring)

    exportDataString.append('goalsDelta')
    exportData.append(float(abs(goalCountA - goalCountB)))
    exportFullExplanation.append(
        'Absolute difference between number of goals scored by %s and %s.' %
        (TeamAstring, TeamBstring))

    safetyWarning.checkLengthExport(exportData, exportDataString,
                                    exportFullExplanation)
    return exportData, exportDataString, exportFullExplanation, targetEvents
Example #4
0
def goals(window, aggregateEvent, targetEvents, TeamAstring, TeamBstring,
          exportData, exportDataString, exportFullExplanation):

    if targetEvents['Goal'] != []:
        goals = []
        for eventInstant, eventID in targetEvents['Goal']:
            if eventInstant > window[0] and eventInstant <= window[1]:
                goals.append(eventID)

        goalCount = float(len(goals))
        goalCountA = float(sum([TeamAstring in i for i in goals]))
        goalCountB = float(sum([TeamBstring in i for i in goals]))
        goalsDelta = float(abs(goalCountA - goalCountB))

    else:  # no 'goals' information
        # goalCount = None
        # goalCountA = None
        # goalCountB = None
        # goalsDelta = None
        return exportData, exportDataString, exportFullExplanation

    # To export:
    exportDataString.append('goalCount')
    exportData.append(goalCount)
    exportFullExplanation.append('Number of goals per %s.' % aggregateEvent)

    exportDataString.append('goalCountA')
    exportData.append(goalCountA)
    exportFullExplanation.append('Number of goals by %s per %s.' %
                                 (TeamAstring, aggregateEvent))

    exportDataString.append('goalCountB')
    exportData.append(goalCountB)
    exportFullExplanation.append('Number of goals by %s per %s.' %
                                 (TeamBstring, aggregateEvent))

    exportDataString.append('goalsDelta')
    exportData.append(goalsDelta)
    exportFullExplanation.append(
        'Absolute difference between number of goals scored by %s and %s, per %s.'
        % (TeamAstring, TeamBstring, aggregateEvent))

    safetyWarning.checkLengthExport(exportData, exportDataString,
                                    exportFullExplanation)
    return exportData, exportDataString, exportFullExplanation
Example #5
0
def passes(rawDict, attributeDict, TeamAstring, TeamBstring, exportData,
           exportDataString, exportFullExplanation, possessionCharacteristics,
           targetEvents):
    overwriteOutput = False
    initLength = len(exportData)
    i = [
        idx for idx, val in enumerate(exportDataString)
        if val == 'possessionCount'
    ]

    possessionCount = exportData[i[0]]
    i = [
        idx for idx, val in enumerate(exportDataString)
        if val == 'possessionCountA'
    ]
    possessionCountA = exportData[i[0]]
    i = [
        idx for idx, val in enumerate(exportDataString)
        if val == 'possessionCountB'
    ]
    possessionCountB = exportData[i[0]]

    count = 0
    passes = [i for i in attributeDict['Pass'] if i != '']

    passOut = np.ones((len(passes), 2), dtype='int') * -1

    for idx, i in enumerate(attributeDict['Pass']):
        if not i == '':
            passOut[count, 1] = idx  #rawDict['Time']['TsS'][idx]
            if TeamAstring in i:
                passOut[count, 0] = 0
                targetEvents['Passes'].append(
                    (float(rawDict['Time']['TsS'][idx]), TeamAstring))
            elif TeamBstring in i:
                passOut[count, 0] = 1
                targetEvents['Passes'].append(
                    (float(rawDict['Time']['TsS'][idx]), TeamBstring))
            else:
                warn('\n\nCould not recognize team:\n<<%s>>' % i)
            if 'oal' in i:
                # ITS A GOAL NOT A PASS, so skip this file
                warn(
                    '\n!!!!!!!!!!!\nInconsistent data input: Goal was found in the passing column:\nEither improve code or clean up data.\n!!!!!!!!!!!'
                )
                overwriteOutput = True
                break
            count = count + 1

    # To export:
    exportDataString.append('passCount')
    exportData.append(float(len(passes)))
    passCountA = sum([TeamAstring in i for i in passes])
    exportFullExplanation.append('Number of passes per match.')

    exportDataString.append('passCountA')
    exportData.append(float(passCountA))
    passCountB = sum([TeamBstring in i for i in passes])
    exportFullExplanation.append('Number of passes by %s per match.' %
                                 TeamAstring)

    exportDataString.append('passCountB')
    exportData.append(float(passCountB))
    exportFullExplanation.append('Number of passes by %s per match.' %
                                 TeamBstring)

    exportDataString.append('passDelta')
    exportData.append(float(abs(passCountA - passCountB)))
    exportFullExplanation.append(
        'Absolute difference between number of passes scored by %s and %s.' %
        (TeamAstring, TeamBstring))

    ind = 0
    ConsecutivePasses = []
    PassessPossession = []

    for idx, i in enumerate(possessionCharacteristics):
        tmp = 0
        while passOut[ind][1] >= i[0]:  # after the start
            if passOut[ind][1] <= i[4]:  # before the end
                # print('found one',passOut[ind][1])
                tmp = tmp + 1
                # current pass falls within current
                if len(passOut) > ind + 1:
                    ind = ind + 1
                else:
                    break
            else:
                # pass belongs in next section
                break
        ConsecutivePasses.append(tmp)
        PassessPossession.append(i[2])

    if ConsecutivePasses == []:  # no passes detected, overwrite output
        overwriteOutput = True
        ConsecutivePasses = [0, 0]
        PassessPossession = [TeamAstring, TeamBstring]

    exportDataString.append('ConsecutivePassesMax')
    exportData.append(float(max(ConsecutivePasses)))
    exportFullExplanation.append(
        'Maximum number of consecutive passes during one possession per match.'
    )

    exportDataString.append('ConsecutivePassesMaxA')
    exportData.append(
        float(
            max([
                val for idx, val in enumerate(ConsecutivePasses)
                if PassessPossession[idx] == TeamAstring
            ])))
    exportFullExplanation.append(
        'Maximum number of consecutive passes during one possession by %s per match.'
        % TeamAstring)

    exportDataString.append('ConsecutivePassesMaxB')
    exportData.append(
        float(
            max([
                val for idx, val in enumerate(ConsecutivePasses)
                if PassessPossession[idx] == TeamBstring
            ])))
    exportFullExplanation.append(
        'Maximum number of consecutive passes during one possession by %s per match.'
        % TeamBstring)

    # Average per possession
    exportDataString.append('ConsecutivePassesAvg')
    exportData.append(float(sum(ConsecutivePasses) / possessionCount))
    exportFullExplanation.append(
        'Average number of consecutive passes during one possession by %s per match.'
        % TeamAstring)

    exportDataString.append('ConsecutivePassesAvgA')
    exportData.append(
        float(
            sum([
                val for idx, val in enumerate(ConsecutivePasses)
                if PassessPossession[idx] == TeamAstring
            ]) / possessionCountA))
    exportFullExplanation.append(
        'Average number of consecutive passes during one possession by %s per match.'
        % TeamAstring)

    exportDataString.append('ConsecutivePassesAvgB')
    exportData.append(
        float(
            sum([
                val for idx, val in enumerate(ConsecutivePasses)
                if PassessPossession[idx] == TeamBstring
            ]) / possessionCountB))
    exportFullExplanation.append(
        'Average number of consecutive passes during one possession by %s per match.'
        % TeamBstring)

    safetyWarning.checkLengthExport(exportData, exportDataString,
                                    exportFullExplanation)
    if overwriteOutput:
        warn('\nOutput replaced with 999')
        for idx, val in enumerate(exportData):
            if idx >= initLength:
                exportData[idx] = 999

    return exportData, exportDataString, exportFullExplanation, targetEvents, overwriteOutput


#################################################################
#################################################################
Example #6
0
def possession(rawDict, attributeDict, TeamAstring, TeamBstring, exportData,
               exportDataString, exportFullExplanation, targetEvents):
    overwriteOutput = False
    initLength = len(exportData)

    possessionEvent = [
        (i, val) for i, val in enumerate(attributeDict['Possession/Turnover'])
        if val != ''
    ]
    possessionCharacteristics = []
    dt = []

    for idx, i in enumerate(possessionEvent):
        curFrame = i[0]  # frame
        curTime = rawDict['Time']['TsS'][i[0]]
        curStatus = i[1]
        # Determine per event who has possession from that frame onward

        if not idx == len(possessionEvent) - 1:
            currentPossessionDuration = rawDict['Time']['TsS'][
                possessionEvent[idx + 1][0] - 1] - curTime
            endPossession = possessionEvent[idx + 1][0] - 1
        else:
            currentPossessionDuration = None
            endPossession = None

        if 'Start' in curStatus:
            if TeamAstring in curStatus:
                # it's about Team A
                currentPossession = TeamAstring
            elif TeamBstring in curStatus:
                # it's about Team B
                currentPossession = TeamBstring
            else:
                # exception added:
                if curStatus == 'Start A possession ':
                    currentPossession = TeamAstring
                else:
                    warn('\nCouldnt identify possession.\n%s' % curStatus)

        elif 'End' in curStatus:
            currentPossessionDuration = None
            currentPossession = None

        elif 'Turnover' in curStatus:
            dt.append(
                float(rawDict['Time']['TsS'][curFrame + 1] -
                      rawDict['Time']['TsS'][curFrame])
            )  # a cheecky way to read frame rate from data
            if currentPossession == TeamAstring:
                currentPossession = TeamBstring
                targetEvents['Turnovers'].append(
                    (float(rawDict['Time']['TsS'][idx]), TeamAstring))
            elif currentPossession == TeamBstring:
                currentPossession = TeamAstring
                targetEvents['Turnovers'].append(
                    (float(rawDict['Time']['TsS'][idx]), TeamBstring))
            else:
                currentPossession = None

        else:
            # Based on next status
            if possessionEvent[idx +
                               1][1][0:8] == 'Turnover' and possessionEvent[
                                   idx + 1][1][-len(TeamAstring) -
                                               1:-1] == TeamAstring:
                # The next turnover goes to TeamA, so:
                currentPossession = TeamBstring
                warn(
                    '\nIndirectly assessed event (based on next event):\n<<%s>>\nas <<%s>>'
                    % (curStatus, currentPossession))

            elif possessionEvent[idx +
                                 1][1][0:8] == 'Turnover' and possessionEvent[
                                     idx + 1][1][-len(TeamBstring) -
                                                 1:-1] == TeamBstring:
                currentPossession = TeamAstring
                warn(
                    '\nIndirectly assessed event (based on next event):\n<<%s>>\nas <<%s>>'
                    % (curStatus, currentPossession))
            else:
                warn('\nCouldnt identify event:\n%s\n\n' % curStatus)
                currentPossession = None

        possessionCharacteristics.append([
            curFrame, curStatus, currentPossession, currentPossessionDuration,
            endPossession
        ])
        if curFrame == None:
            in1 = None
        else:
            in1 = float(rawDict['Time']['TsS'][curFrame])
        if endPossession == None:
            in2 = None
        else:
            in2 = float(rawDict['Time']['TsS'][endPossession])
        targetEvents['Possession'].append((in1, in2, currentPossession))

    # print(rawDict['Time']['TsS'])
    if dt == []:
        warn(
            '\n!!!!\nExisting attributes seem to be missing.\nCouldnt find turnovers to estimate dt.\nOutput set as 999.'
        )
        frameTime = 0.1
        overwriteOutput = True
    else:
        if round(sum(dt) / len(dt), 7) == round(dt[0], 7):
            # Safe to assume that:
            frameTime = dt[0]
        else:
            frameTime = round(sum(dt) / len(dt), 7)
            warn('\nNot sure about frameTime. Check that:\n frameTime = %f' %
                 frameTime)

    rawDict['Time']['TsS']
    attributeDict['currentPossession'] = [''] * len(rawDict['Time']['TsS'])
    # Allocate possession to timeseries attributes
    for i in range(len(possessionCharacteristics) - 1):
        for q in range(possessionCharacteristics[i][0],
                       possessionCharacteristics[i + 1][0]):
            attributeDict['currentPossession'][q] = possessionCharacteristics[
                i][2]

    # # To export:'
    exportDataString.append('turnoverCount')
    exportData.append(
        float(sum(['Turnover' in i[1] for i in possessionCharacteristics])))
    exportFullExplanation.append('Number of turnovers per match.')

    exportDataString.append('turnoverCountA')
    turnoverCountA = sum([
        'Turnover' in i[1] for i in possessionCharacteristics
        if i[2] == TeamAstring
    ])
    exportData.append(float(turnoverCountA))
    exportFullExplanation.append('Number of turnovers by %s per match.' %
                                 TeamAstring)

    exportDataString.append('turnoverCountB')
    turnoverCountB = sum([
        'Turnover' in i[1] for i in possessionCharacteristics
        if i[2] == TeamBstring
    ])
    exportData.append(float(turnoverCountB))
    exportFullExplanation.append('Number of turnovers by %s per match.' %
                                 TeamBstring)

    exportDataString.append('turnoverDelta')
    exportData.append(float(abs(turnoverCountA - turnoverCountB)))
    exportFullExplanation.append(
        'Absolute difference between number of turnovers scored by %s and %s.'
        % (TeamAstring, TeamBstring))

    # possessionCount in occurence (or frequency) in the whole trial
    exportDataString.append('possessionCount')
    possessionCount = sum([i[2] != None for i in possessionCharacteristics])
    exportData.append(float(possessionCount))
    exportFullExplanation.append(
        'Number of times a different team had possession per match.')

    exportDataString.append('possessionCountA')
    possessionCountA = sum(
        [i[2] == TeamAstring for i in possessionCharacteristics])
    exportData.append(float(possessionCountA))
    exportFullExplanation.append(
        'Number of times %s had possession per match.' % TeamAstring)

    exportDataString.append('possessionCountB')
    possessionCountB = sum(
        [i[2] == TeamBstring for i in possessionCharacteristics])
    exportData.append(float(possessionCountB))
    exportFullExplanation.append(
        'Number of times %s had possession per match.' % TeamBstring)

    exportDataString.append('possessionCountDelta')
    exportData.append(float(abs(possessionCountA - possessionCountB)))
    exportFullExplanation.append(
        'Absolute difference between number of possessions scored by %s and %s.'
        % (TeamAstring, TeamBstring))

    exportDataString.append('possessionCountNone')
    possessionCountNone = len(possessionCharacteristics) - possessionCount
    exportData.append(float(possessionCountNone))
    exportFullExplanation.append(
        'Number of times no team had possession per match.')

    # possessionDuration (in seconds) --> sum,std,avg,
    # Sum of the whole trial
    exportDataString.append('possessionDurationSum')
    possessionDurationSum = sum(
        [i[3] for i in possessionCharacteristics if i[3] != None])
    exportData.append(float(possessionDurationSum))
    exportFullExplanation.append(
        'Total duration (s) of possession per match by %s and %s.' %
        (TeamAstring, TeamBstring))

    exportDataString.append('possessionDurationSumA')
    possessionDurationSumA = sum([
        i[3] for i in possessionCharacteristics
        if i[3] != None and i[2] == TeamAstring
    ])
    exportData.append(float(possessionDurationSumA))
    exportFullExplanation.append(
        'Total duration (s) of possession per match by %s.' % TeamAstring)

    exportDataString.append('possessionDurationSumB')
    possessionDurationSumB = sum([
        i[3] for i in possessionCharacteristics
        if i[3] != None and i[2] == TeamBstring
    ])
    exportData.append(float(possessionDurationSumB))
    exportFullExplanation.append(
        'Total duration (s) of possession per match by %s.' % TeamBstring)

    exportDataString.append('possessionDurationSumNone')
    possessionDurationSumNone = sum(
        [None == i for i in attributeDict['currentPossession']]) * frameTime
    exportData.append(float(possessionDurationSumNone))
    exportFullExplanation.append(
        'Total duration (s) of no possession per match.')

    # Average duration of a possession (until turnover / ball loss / end game)
    if possessionCount == 0 and overwriteOutput:
        possessionCount = 1
        possessionCountA = 1
        possessionCountB = 1
        possessionCountNone = 1

    exportDataString.append('possessionDurationAvg')
    possessionDurationAvg = possessionDurationSum / possessionCount
    exportData.append(float(possessionDurationAvg))
    exportFullExplanation.append(
        'Average duration of a possession per match by %s and %s.' %
        (TeamAstring, TeamBstring))

    exportDataString.append('possessionDurationAvgA')
    possessionDurationAvgA = possessionDurationSumA / possessionCountA
    exportData.append(float(possessionDurationAvgA))
    exportFullExplanation.append(
        'Average duration of a possession per match by %s.' % TeamAstring)

    exportDataString.append('possessionDurationAvgB')
    possessionDurationAvgB = possessionDurationSumB / possessionCountB
    exportData.append(float(possessionDurationAvgB))
    exportFullExplanation.append(
        'Average duration of a possession per match by %s.' % TeamBstring)

    exportDataString.append('possessionDurationAvgNone')
    exportData.append(float(possessionDurationSumNone / possessionCountNone))
    exportFullExplanation.append(
        'Average duration (s) of no possession per match.')

    # Standard deviation of a possession
    exportDataString.append('possessionDurationStd')
    exportData.append(
        float(
            sum([
                abs(i[3] - possessionDurationAvg)
                for i in possessionCharacteristics if i[3] != None
            ]) / possessionCount))
    exportFullExplanation.append(
        'Standard deviation of the duration of a possession per match by %s and %s.'
        % (TeamAstring, TeamBstring))

    exportDataString.append('possessionDurationStdA')
    exportData.append(
        float(
            sum([
                abs(i[3] - possessionDurationAvgA)
                for i in possessionCharacteristics
                if i[3] != None and i[2] == TeamAstring
            ]) / possessionCountA))
    exportFullExplanation.append(
        'Standard deviation of the duration of a possession per match by %s.' %
        TeamAstring)

    exportDataString.append('possessionDurationStdB')
    exportData.append(
        float(
            sum([
                abs(i[3] - possessionDurationAvgB)
                for i in possessionCharacteristics
                if i[3] != None and i[2] == TeamBstring
            ]) / possessionCountB))
    exportFullExplanation.append(
        'Standard deviation of the duration of a possession per match by %s.' %
        TeamBstring)

    exportDataString.append('possessionDurationSumNone')
    exportData.append(
        None
    )  # incvonient to compute. No possessionCharacteristics[3] in for loop)
    exportFullExplanation.append(
        'Standard deviation of the duration (s) of no possession per match. NOTE: I did not (yet) compute this variable as it was somewhat annoying to do, and I dont think it is so interesting. Rens.'
    )

    safetyWarning.checkLengthExport(exportData, exportDataString,
                                    exportFullExplanation)

    if overwriteOutput:
        warn('\nOutput replaced with 999')
        for idx, val in enumerate(exportData):
            if idx >= initLength:
                exportData[idx] = 999

    return exportData, exportDataString, exportFullExplanation, possessionCharacteristics, targetEvents, overwriteOutput
Example #7
0
def passes(window, aggregateEvent, targetEvents, TeamAstring, TeamBstring,
           exportData, exportDataString, exportFullExplanation):

    # window = (80,90)
    if targetEvents['Passes'] != []:
        passes = []
        consecutivePasses = []
        for eventInstant, eventID, consecutiveEvents in targetEvents['Passes']:
            if eventInstant > window[0] and eventInstant <= window[1]:
                passes.append(eventID)
                consecutivePasses.append(consecutiveEvents)

        passCount = float(len(passes))
        passCountA = float(sum([TeamAstring in i for i in passes]))
        passCountB = float(sum([TeamBstring in i for i in passes]))
        passDelta = float(abs(passCountA - passCountB))

    else:  # no 'passes' information
        # passCount = None
        # passCountA = None
        # passCountB = None
        # passDelta = None
        return exportData, exportDataString, exportFullExplanation

    if targetEvents['Passes'] != [] and targetEvents['Possession'] != []:
        consecutivePassesPerPossession = []
        consecutivePassesPerPossessionA = []
        consecutivePassesPerPossessionB = []
        tmp = 1
        for idx, val in enumerate(consecutivePasses):
            consecutivePassesPerPossession.append(tmp)
            if passes[idx] == TeamAstring:
                consecutivePassesPerPossessionA.append(tmp)
            elif passes[idx] == TeamBstring:
                consecutivePassesPerPossessionB.append(tmp)
            else:
                warn('\nERROR: Could not identify whose possession: <<%s>>' %
                     passes[idx])

            if idx == len(consecutivePasses) - 1:  # last one
                break
            if val != consecutivePasses[idx + 1]:  # new possession
                tmp = 1
            else:
                tmp = tmp + 1

        if consecutivePassesPerPossession != []:
            maxConsecutivePasses = max(consecutivePassesPerPossession)
            avgConsecutivePasses = sum(consecutivePassesPerPossession) / len(
                consecutivePassesPerPossession)
            stdConsecutivePasses = sum([
                abs(i - avgConsecutivePasses)
                for i in consecutivePassesPerPossession
            ]) / len(consecutivePassesPerPossession)
        else:
            maxConsecutivePasses = None
            avgConsecutivePasses = None
            stdConsecutivePasses = None

        if consecutivePassesPerPossessionA != []:
            maxConsecutivePassesA = max(consecutivePassesPerPossessionA)
            avgConsecutivePassesA = sum(consecutivePassesPerPossessionA) / len(
                consecutivePassesPerPossessionA)
            stdConsecutivePassesA = sum([
                abs(i - avgConsecutivePassesA)
                for i in consecutivePassesPerPossessionA
            ]) / len(consecutivePassesPerPossessionA)
        else:
            maxConsecutivePassesA = None
            avgConsecutivePassesA = None
            stdConsecutivePassesA = None

        if consecutivePassesPerPossessionB != []:
            maxConsecutivePassesB = max(consecutivePassesPerPossessionB)
            avgConsecutivePassesB = sum(consecutivePassesPerPossessionB) / len(
                consecutivePassesPerPossessionB)
            stdConsecutivePassesB = sum([
                abs(i - avgConsecutivePassesB)
                for i in consecutivePassesPerPossessionB
            ]) / len(consecutivePassesPerPossessionB)
        else:
            maxConsecutivePassesB = None
            avgConsecutivePassesB = None
            stdConsecutivePassesB = None
    else:
        maxConsecutivePasses = None
        maxConsecutivePassesA = None
        maxConsecutivePassesB = None
        avgConsecutivePasses = None
        avgConsecutivePassesA = None
        avgConsecutivePassesB = None
        stdConsecutivePasses = None
        stdConsecutivePassesA = None
        stdConsecutivePassesB = None

    # To export:
    # Pass counts
    exportDataString.append('passCount')
    exportData.append(passCount)
    exportFullExplanation.append('Number of passes per %s.' % aggregateEvent)

    exportDataString.append('passCountA')
    exportData.append(passCountA)
    exportFullExplanation.append('Number of passes by %s per %s.' %
                                 (TeamAstring, aggregateEvent))

    exportDataString.append('passCountB')
    exportData.append(passCountB)
    exportFullExplanation.append('Number of passes by %s per %s.' %
                                 (TeamBstring, aggregateEvent))

    exportDataString.append('passDelta')
    exportData.append(passDelta)
    exportFullExplanation.append(
        'Absolute difference between number of passes by %s and %s.' %
        (TeamAstring, TeamBstring))

    # Consecutive passes
    # Counts
    exportDataString.append('maxConsecutivePasses')
    exportData.append(maxConsecutivePasses)
    exportFullExplanation.append(
        'Maximum number of consecutive passes per %s.' % aggregateEvent)

    exportDataString.append('maxConsecutivePassesA')
    exportData.append(maxConsecutivePassesA)
    exportFullExplanation.append(
        'Maximum number of consecutive passes (during a possession) by %s per %s.'
        % (TeamAstring, aggregateEvent))

    exportDataString.append('maxConsecutivePassesB')
    exportData.append(maxConsecutivePassesB)
    exportFullExplanation.append(
        'Maximum number of consecutive passes (during a possession) by %s per %s.'
        % (TeamBstring, aggregateEvent))

    # Average per event
    exportDataString.append('avgConsecutivePasses')
    exportData.append(avgConsecutivePasses)
    exportFullExplanation.append(
        'Average number of consecutive passes (during a possession) per %s.' %
        aggregateEvent)

    exportDataString.append('avgConsecutivePassesA')
    exportData.append(avgConsecutivePassesA)
    exportFullExplanation.append(
        'Average number of consecutive passes (during a possession) by %s per %s.'
        % (TeamAstring, aggregateEvent))

    exportDataString.append('avgConsecutivePassesB')
    exportData.append(avgConsecutivePassesB)
    exportFullExplanation.append(
        'Average number of consecutive passes (during a possession) by %s per %s.'
        % (TeamBstring, aggregateEvent))

    # Std per event
    exportDataString.append('stdConsecutivePasses')
    exportData.append(stdConsecutivePasses)
    exportFullExplanation.append(
        'Standard deviation of number of consecutive passes (during a possession) per %s.'
        % aggregateEvent)

    exportDataString.append('stdConsecutivePassesA')
    exportData.append(stdConsecutivePassesA)
    exportFullExplanation.append(
        'Standard deviation of number of consecutive passes (during a possession) by %s per %s.'
        % (TeamAstring, aggregateEvent))

    exportDataString.append('stdConsecutivePassesB')
    exportData.append(stdConsecutivePasses)
    exportFullExplanation.append(
        'Standard deviation of number of consecutive passes (during a possession) by %s per %s.'
        % (TeamBstring, aggregateEvent))

    safetyWarning.checkLengthExport(exportData, exportDataString,
                                    exportFullExplanation)
    return exportData, exportDataString, exportFullExplanation


# def passes2(rowswithinrange,aggregateEvent,possessionCharacteristics,rawDict,attributeDict,TeamAstring,TeamBstring,exportData,exportDataString,exportFullExplanation):

# 	i = [idx for idx,val in enumerate(exportDataString) if val == 'possessionCount']
# 	possessionCount = exportData[i[0]]
# 	i = [idx for idx,val in enumerate(exportDataString) if val == 'possessionCountA']
# 	possessionCountA = exportData[i[0]]
# 	i = [idx for idx,val in enumerate(exportDataString) if val == 'possessionCountB']
# 	possessionCountB = exportData[i[0]]

# 	## TO DO: CHANGE this to not use attributeDict['Pass']
# 	passInfo = [attributeDict['Pass'][j] for j in rowswithinrange]
# 	passes = [i for i in passInfo if i != '']

# 	passOut = np.ones((len(passes),2),dtype='int')*-1
# 	count = 0
# 	for idx,i in enumerate(passInfo):
# 		if not i == '':
# 			passOut[count,1] = idx
# 			if TeamAstring in i:
# 				passOut[count,0] = 0
# 			elif TeamBstring in i:
# 				passOut[count,0] = 1
# 			else:
# 				warn('\n\nCould not recognize team:\n<<%s>>' %i)
# 			if 'oal' in i:
# 				# ITS A GOAL NOT A PASS, so skip this file
# 				warn('\n!!!!!!!!!!!\nInconsistent data input: Goal was found in the passing column:\nEither improve code or clean up data.\n!!!!!!!!!!!')
# 				overwriteOutput = True
# 				break
# 			count = count + 1

# 	# To export:
# 	exportDataString.append('passCount')
# 	exportData.append(float(len(passes)))
# 	passCountA = sum([TeamAstring in i for i in passes])
# 	exportFullExplanation.append('Number of passes per %s.' %aggregateEvent)

# 	exportDataString.append('passCountA')
# 	exportData.append(float(passCountA))
# 	passCountB = sum([TeamBstring in i for i in passes])
# 	exportFullExplanation.append('Number of passes by %s per %s.' %(TeamAstring,aggregateEvent))

# 	exportDataString.append('passCountB')
# 	exportData.append(float(passCountB))
# 	exportFullExplanation.append('Number of passes by %s per %s.' %(TeamBstring,aggregateEvent))

# 	exportDataString.append('passDelta')
# 	exportData.append(float(abs(passCountA - passCountB)))
# 	exportFullExplanation.append('Absolute difference between number of passes scored by %s and %s.' %(TeamAstring,TeamBstring))

# 	ind = 0
# 	ConsecutivePasses = []
# 	PassessPossession = []

# 	for idx,i in enumerate(possessionCharacteristics):
# 		tmp = 0
# 		if len(passOut) != 0: # Skip this if there were no passess during the current possession
# 			while passOut[ind][1] >= i[0]: # after the start
# 				if passOut[ind][1] <= i[4]: # before the end
# 					tmp = tmp + 1
# 					# current pass falls within current
# 					if len(passOut) > ind+1:
# 						ind = ind + 1
# 					else:
# 						break
# 				else:
# 					# pass belongs in next section
# 					break
# 		ConsecutivePasses.append(tmp)
# 		PassessPossession.append(i[2])

# 	if ConsecutivePasses == [] or ConsecutivePasses == [0] or possessionCount == 0: # no passes detected, overwrite output
# 		ConsecutivePassesAvg = None
# 		overwriteOutput = True # might be obsolete
# 		PassessPossession = [TeamAstring,TeamBstring] # might be obsolete
# 	else:
# 		ConsecutivePassesAvg = float(sum(ConsecutivePasses) / possessionCount)

# 	exportDataString.append('ConsecutivePassesMax')
# 	exportData.append(float(max(ConsecutivePasses)))
# 	exportFullExplanation.append('Maximum number of consecutive passes during one possession per %s.' %aggregateEvent)

# 	exportDataString.append('ConsecutivePassesMaxA')
# 	consPassesA = [val for idx,val in enumerate(ConsecutivePasses) if PassessPossession[idx] == TeamAstring]
# 	if consPassesA == [] or possessionCountA == 0:
# 		consPassesA = [0]
# 		ConsecutivePassesAvgA = None
# 	else:
# 		ConsecutivePassesAvgA = float(sum([val for idx,val in enumerate(ConsecutivePasses) if PassessPossession[idx] == TeamAstring]) / possessionCountA)
# 	exportData.append(float(max(consPassesA)))
# 	exportFullExplanation.append('Maximum number of consecutive passes during one possession by %s per %s.' %(TeamAstring,aggregateEvent))

# 	exportDataString.append('ConsecutivePassesMaxB')
# 	consPassesB = [val for idx,val in enumerate(ConsecutivePasses) if PassessPossession[idx] == TeamBstring]
# 	if consPassesB == [] or possessionCountB == 0:
# 		consPassesB = [0]
# 		ConsecutivePassesAvgB = None
# 	else:
# 		ConsecutivePassesAvgB = float(sum([val for idx,val in enumerate(ConsecutivePasses) if PassessPossession[idx] == TeamBstring]) / possessionCountB)
# 	exportData.append(float(max(consPassesB)))
# 	exportFullExplanation.append('Maximum number of consecutive passes during one possession by %s per %s.' %(TeamBstring,aggregateEvent))

# 	# Average per possession
# 	exportDataString.append('ConsecutivePassesAvg')
# 	exportData.append(ConsecutivePassesAvg)
# 	exportFullExplanation.append('Average number of consecutive passes during one possession by %s per %s.' %(TeamAstring,aggregateEvent))

# 	exportDataString.append('ConsecutivePassesAvgA')
# 	exportData.append(ConsecutivePassesAvgA)
# 	exportFullExplanation.append('Average number of consecutive passes during one possession by %s per %s.' %(TeamAstring,aggregateEvent))

# 	exportDataString.append('ConsecutivePassesAvgB')
# 	exportData.append(ConsecutivePassesAvgB)
# 	exportFullExplanation.append('Average number of consecutive passes during one possession by %s per %s.' %(TeamBstring,aggregateEvent))

# 	safetyWarning.checkLengthExport(exportData,exportDataString,exportFullExplanation)

# 	return exportData,exportDataString,exportFullExplanation
# #################################################################
# #################################################################
Example #8
0
def possessions(window, aggregateEvent, targetEvents, TeamAstring, TeamBstring,
                exportData, exportDataString, exportFullExplanation):
    possessionCharacteristics = []
    if targetEvents['Possession'] != []:
        possessionCharacteristics = []
        for eventInstantEnd, eventID, eventInstantStart in targetEvents[
                'Possession']:
            if eventInstantStart == None or eventInstantEnd == None:
                # No possession window defined. Skip this event.
                # NB: This might make all the 'None' possession statistics obsolete.
                continue
            if eventInstantStart >= window[0] and eventInstantEnd <= window[1]:
                possDur = eventInstantEnd - eventInstantStart  # current possession duration
                possessionCharacteristics.append((possDur, eventID))

        # define outcome variables here
        possessionCount = sum(
            [i[1] != None for i in possessionCharacteristics])
        possessionCountA = sum(
            [i[1] == TeamAstring for i in possessionCharacteristics])
        possessionCountB = sum(
            [i[1] == TeamBstring for i in possessionCharacteristics])
        possessionCountDelta = abs(possessionCountA - possessionCountB)
        possessionCountNone = sum(
            [i[1] == None for i in possessionCharacteristics])

        possessionDurationSum = sum(i[0] for i in possessionCharacteristics)
        possessionDurationSumA = sum(i[0] for i in possessionCharacteristics
                                     if i[1] == TeamAstring)
        possessionDurationSumB = sum(i[0] for i in possessionCharacteristics
                                     if i[1] == TeamBstring)
        possessionDurationSumNone = sum(i[0] for i in possessionCharacteristics
                                        if i[1] == None)

        if possessionCount != 0:
            possessionDurationAvg = possessionDurationSum / possessionCount
            possessionDurationStd = sum(
                abs(i[0] - possessionDurationAvg)
                for i in possessionCharacteristics
                if i[1] != None) / possessionCount
        else:
            possessionDurationAvg = None
            possessionDurationStd = None

        if possessionCountA != 0:
            possessionDurationAvgA = possessionDurationSumA / possessionCountA
            possessionDurationStdA = sum(
                abs(i[0] - possessionDurationAvgA)
                for i in possessionCharacteristics
                if i[1] == TeamAstring) / possessionCountA
        else:
            possessionDurationAvgA = None
            possessionDurationStdA = None

        if possessionCountB != 0:
            possessionDurationAvgB = possessionDurationSumB / possessionCountB
            possessionDurationStdB = sum(
                abs(i[0] - possessionDurationAvgB)
                for i in possessionCharacteristics
                if i[1] == TeamBstring) / possessionCountB
        else:
            possessionDurationAvgB = None
            possessionDurationStdB = None

        if possessionCountNone != 0:
            possessionDurationAvgNone = possessionDurationSumNone / possessionCountNone
            possessionDurationStdNone = sum(
                abs(i[0] - possessionDurationAvgNone)
                for i in possessionCharacteristics
                if i[1] == None) / possessionCountNone
        else:
            possessionDurationAvgNone = None
            possessionDurationStdNone = None

    else:  # no 'possession' information
        # define missing outcome variables here
        # possessionCount = None
        # possessionCountA = None
        # possessionCountB = None
        # possessionCountDelta = None
        # possessionCountNone = None

        # possessionDurationSum = None
        # possessionDurationSumA = None
        # possessionDurationSumB = None
        # possessionDurationSumNone = None

        # possessionDurationAvg = None
        # possessionDurationAvgA = None
        # possessionDurationAvgB = None
        # possessionDurationAvgNone = None

        # possessionDurationStd = None
        # possessionDurationStdA = None
        # possessionDurationStdB = None
        # possessionDurationStdNone = None
        return exportData, exportDataString, exportFullExplanation

    # # To export:'
    # possessionCount in occurence (or frequency) in the whole trial
    exportDataString.append('possessionCount')
    exportData.append(possessionCount)
    exportFullExplanation.append(
        'Number of full possessions per %s. NB: <full> refers to from the start until the end of a possession.'
        % aggregateEvent)

    exportDataString.append('possessionCountA')
    exportData.append(possessionCountA)
    exportFullExplanation.append(
        'Number full possession %s had per %s. NB: <full> refers to from the start until the end of a possession.'
        % (TeamAstring, aggregateEvent))

    exportDataString.append('possessionCountB')
    exportData.append(possessionCountB)
    exportFullExplanation.append(
        'Number full possession %s had per %s. NB: <full> refers to from the start until the end of a possession.'
        % (TeamBstring, aggregateEvent))

    exportDataString.append('possessionCountDelta')
    exportData.append(possessionCountDelta)
    exportFullExplanation.append(
        'Absolute difference between number of full possessions by %s and %s, per %s. NB: <full> refers to from the start until the end of a possession.'
        % (TeamAstring, TeamBstring, aggregateEvent))

    exportDataString.append('possessionCountNone')
    exportData.append(possessionCountNone)
    exportFullExplanation.append(
        'Number of times no team had possession per %s.' % aggregateEvent)

    # possessionDuration (in seconds) --> sum,std,avg,
    exportDataString.append('possessionDurationSum')
    exportData.append(possessionDurationSum)
    exportFullExplanation.append(
        'Total duration (s) of full possessions by %s and %s, per %s. NB: <full> refers to from the start until the end of a possession.'
        % (TeamAstring, TeamBstring, aggregateEvent))

    exportDataString.append('possessionDurationSumA')
    exportData.append(possessionDurationSumA)
    exportFullExplanation.append(
        'Total duration (s) of full possessions per %s by %s. NB: <full> refers to from the start until the end of a possession.'
        % (aggregateEvent, TeamAstring))

    exportDataString.append('possessionDurationSumB')
    exportData.append(possessionDurationSumB)
    exportFullExplanation.append(
        'Total duration (s) of full possessions per %s by %s. NB: <full> refers to from the start until the end of a possession.'
        % (aggregateEvent, TeamBstring))

    exportDataString.append('possessionDurationSumNone')
    exportData.append(possessionDurationSumNone)
    exportFullExplanation.append(
        'Total duration (s) of no possession per %s. NB: <full> refers to from the start until the end of a possession.'
        % aggregateEvent)

    # Average duration of a possession (until turnover / ball loss / end game)
    exportDataString.append('possessionDurationAvg')
    exportData.append(possessionDurationAvg)
    exportFullExplanation.append(
        'Average duration of a full possession per %s by %s and %s. NB: <full> refers to from the start until the end of a possession.'
        % (aggregateEvent, TeamAstring, TeamBstring))

    exportDataString.append('possessionDurationAvgA')
    exportData.append(possessionDurationAvgA)
    exportFullExplanation.append(
        'Average duration of a full possession per %s by %s. NB: <full> refers to from the start until the end of a possession.'
        % (aggregateEvent, TeamAstring))

    exportDataString.append('possessionDurationAvgB')
    exportData.append(possessionDurationAvgB)
    exportFullExplanation.append(
        'Average duration of a full possession per %s by %s. NB: <full> refers to from the start until the end of a possession.'
        % (aggregateEvent, TeamBstring))

    exportDataString.append('possessionDurationAvgNone')
    exportData.append(possessionDurationAvgNone)
    exportFullExplanation.append(
        'Average duration (s) of no possession per %s.' % aggregateEvent)

    # Standard deviation of a possession
    exportDataString.append('possessionDurationStd')
    exportData.append(possessionDurationStd)
    exportFullExplanation.append(
        'Standard deviation of the duration of a full possession per %s by %s and %s. NB: <full> refers to from the start until the end of a possession.'
        % (aggregateEvent, TeamAstring, TeamBstring))

    exportDataString.append('possessionDurationStdA')
    exportData.append(possessionDurationStdA)
    exportFullExplanation.append(
        'Standard deviation of the duration of a full possession per %s by %s. NB: <full> refers to from the start until the end of a possession.'
        % (aggregateEvent, TeamAstring))

    exportDataString.append('possessionDurationStdB')
    exportData.append(possessionDurationStdB)
    exportFullExplanation.append(
        'Standard deviation of the duration of a full possession per %s by %s. NB: <full> refers to from the start until the end of a possession.'
        % (aggregateEvent, TeamBstring))

    exportDataString.append('possessionDurationStdNone')
    exportData.append(possessionDurationStdNone)
    exportFullExplanation.append(
        'Standard deviation of the duration (s) of no possession per %s.' %
        aggregateEvent)

    safetyWarning.checkLengthExport(exportData, exportDataString,
                                    exportFullExplanation)

    return exportData, exportDataString, exportFullExplanation