mrnosuch

Clan XP Calculation

Oct 29th, 2023 (edited)
608
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.42 KB | Gaming | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3.  
  4. import sqlite3
  5. import datetime
  6.  
  7. local_db_path     = "/home/pi/Scripts/blastardbot/bot.db" # Prod
  8. # local_db_path     = "/home/pi/Scripts/blastardbot/bot-dev.db" # Dev
  9.  
  10.  
  11. class UpdateData():
  12.  
  13.     def __init__(self, player, slice_date):
  14.  
  15.         self.player = player
  16.         self.slice_date = slice_date
  17.         self.type = None
  18.         self.incremental = 0
  19.         self.estimated = 0
  20.         self.estimate_rate = None
  21.         self.calculated = 0
  22.         self.kills = 0
  23.         self.elapsed = 0
  24.  
  25.  
  26.  
  27. # What the columns mean:
  28.  
  29. # XPClan: Clan XP direct from the API
  30. # timeElapsed: seconds online in game for sample.
  31. # clanXPincremental: amount of XP earned in sample, as calculated
  32. # clanXPcalculated: total amount of clan XP earned as calculated
  33. # clanXPestimated: calculated estimated XP for capped members
  34. # clanXPestimateRate: this is either the rate used for clanXPestimated, or a rate equivalent to the calcuated rate.
  35.  
  36.  
  37. # Queries
  38.  
  39. # This query selects the samples that needs updating
  40. SELECT_FUTURE_SLICES = '''
  41. SELECT player, date, timeElapsed, XPClan, killsNPC
  42. FROM stats
  43. WHERE clanXPtype is NULL and timeElapsed is NOT NULL
  44. AND (clanXPdataStatus IS NULL or clanXPdataStatus != 'A')
  45. ORDER BY player, date;
  46. '''
  47.  
  48. # This query selects the previous sample for a sample being processed
  49. SELECT_PREV_SLICE = '''
  50. SELECT player, date, XPClan, clanXPtype, clanXPcalculated, timeElapsed, killsNPC
  51. FROM stats
  52. WHERE player = :player
  53. AND date < :slice_date
  54. AND clanXPtype != "X"
  55. AND (clanXPdataStatus IS NULL or clanXPdataStatus != 'A')
  56. ORDER BY date desc
  57. LIMIT 1;
  58. '''
  59.  
  60. # Used to update the sample in the database
  61. UPDATE_SLICE = '''
  62. UPDATE stats
  63. SET clanXPtype = :type,
  64.  clanXPincremental = :incremental,
  65.  clanXPestimated = :estimated,
  66.  clanXPestimateRate = :estimate_rate,
  67.  clanXPcalculated = :calculated,
  68.  killsIncremental = :kills,
  69.  timeElapsed = :elapsed
  70. WHERE player = :player
  71. AND date = :slice_date;
  72. '''
  73.  
  74. # To determine the estimated XP rate for a member
  75. SELECT_EST_RATE = '''
  76. SELECT
  77.    sum(clanXPestimateRate)/count(*) as 'estimated_rate'
  78. FROM
  79.    stats
  80. WHERE
  81.     player = :player
  82. AND
  83.    date >
  84.     (
  85.         SELECT
  86.             date(substr(max(date),1,10),'-90 days')
  87.         FROM
  88.             stats
  89.         WHERE
  90.             player=:player
  91.         AND
  92.             clanXPtype = "I"
  93.         AND
  94.             clanXPestimateRate IS NOT NULL
  95.         AND
  96.             date < :sample_date
  97.         )
  98. AND
  99.    date <= :sample_date
  100. AND
  101.    clanXPestimateRate IS NOT NULL;
  102. '''
  103.  
  104.  
  105. ### Config
  106.  
  107. # For calcuation estimated rates, we only include samples covering 0:30 - 4:00 of game play
  108. DURATION_MIN = 60*30 # 30 minutes
  109. DURATION_MAX = 60*60*4 # 4 hours
  110.  
  111. # Discount rates for estimated XP
  112. NORMAL_DISC_RATE   = 0.70  # Use this for elapsed time within MIN and MAX
  113. ATYPICAL_DISC_RATE = 0.25  # Use this for elapsed time outside of MIN and MAX
  114.  
  115.  
  116. # DB Utiity Functions
  117.  
  118. def get_rec(cursor, query, query_opts=None):
  119.  
  120.     result = None
  121.  
  122.     if query_opts is not None:
  123.         cursor.execute(query, query_opts)
  124.     else:
  125.         cursor.execute(query)
  126.  
  127.     row = cursor.fetchone()
  128.  
  129.     if row is not None:
  130.         result = dict(row)
  131.  
  132.     return result
  133.  
  134.  
  135. def query_db(cursor, query, query_opts=None):
  136.  
  137.     if query_opts is not None:
  138.         cursor.execute(query, query_opts)
  139.     else:
  140.         cursor.execute(query)
  141.  
  142.  
  143. def get_next_rec(cursor):
  144.  
  145.     result = None
  146.  
  147.     row = cursor.fetchone()
  148.  
  149.     if row is not None:
  150.         result = dict(row)
  151.  
  152.     return result
  153.  
  154.  
  155. def update_rec(cursor, query, update_opts=None):
  156.  
  157.     if update_opts is not None:
  158.         cursor.execute(query, update_opts)
  159.     else:
  160.         cursor.execute(query)
  161.  
  162.  
  163. #########################
  164. ###
  165. ### START OF MAIN ROUTINE
  166. ###
  167.  
  168.  
  169. # Open the database
  170.  
  171. db = sqlite3.connect(f"file:{local_db_path}", uri=True)
  172. db.row_factory = sqlite3.Row
  173.  
  174. # Start processing loop
  175.  
  176.     # Fetch player and date for a single first, oldest NULL clanXPtype row (TARGET_ROW)
  177.     # clanXPtype values:
  178.     #   N New
  179.     #   C Capped
  180.     #   R Reset
  181.     #   I Incremental (Normal)
  182.     #   X No activity (no time online)
  183.     #   Z Zero (no clan XP)
  184.     #   B Bugged (no XP earned)
  185.  
  186.     # First stats are slice 2020-01-29-23
  187.  
  188.     # Fetch single oldest clanXPtype row earlier than TARGET_ROW matching TARGET_ROW player
  189.  
  190.     # if none found, update TARGET_ROW with 0 earned, this is a baseline/first entry
  191.  
  192.     # if found, update TARGET_ROW with difference, if difference is 0 (non earned, check for CAP)
  193.  
  194.  
  195. # Load last on data for players
  196.  
  197. found = True
  198. table_available = True
  199.  
  200. cur = db.cursor()
  201. update_cur = db.cursor()
  202. prev_row_cur = db.cursor()
  203. est_cur = db.cursor()
  204.  
  205. query_db(cur, SELECT_FUTURE_SLICES)
  206.  
  207. while found and table_available:
  208.  
  209.     result = get_next_rec(cur)
  210.  
  211.     if result is None:
  212.  
  213.         found = False
  214.  
  215.     else:
  216.  
  217.         player = result['player']
  218.         pending_slice_date = result['date']
  219.         clan_xp = result['XPClan']
  220.         elapsed = result['timeElapsed']
  221.         total_kills = result['killsNPC']
  222.  
  223.         # These are the values we need to populate
  224.  
  225.         row_description = None
  226.         row_type = None
  227.  
  228.         update_data = UpdateData(player, pending_slice_date)
  229.  
  230.         if elapsed < 0:
  231.             elapsed = 0 # Correct for negative elapsed glitches
  232.        
  233.         update_data.elapsed = elapsed
  234.  
  235.         test_start = pending_slice_date
  236.         prev_result = get_rec(prev_row_cur, SELECT_PREV_SLICE, {'player': player, 'slice_date' : pending_slice_date})
  237.  
  238.         if prev_result is not None:
  239.            
  240.             prev_calculated = prev_result['clanXPcalculated']
  241.             prev_type = prev_result['clanXPtype']
  242.             if prev_type == "Z":
  243.                 prev_xp = prev_result['clanXPcalculated']
  244.             else:
  245.                 prev_xp = prev_result['XPClan']
  246.             prev_kills = prev_result['killsNPC']
  247.  
  248.             session_kills = total_kills - prev_kills
  249.  
  250.             update_data.kills = session_kills
  251.  
  252.             # Are we capped? Two ways to find out.
  253.  
  254.             # If the previous sample was capped and we have the same amount of XP as that, we are capped
  255.             # OR if we have the same XP as the previous row and we've spent time and had some kills (not perfect, but good enough)
  256.            
  257.             # Also there's a bug where some capped players go to zero and stay that way, and we need to flag
  258.             # them as capped and not just zero (which is otherwise a different bug)
  259.  
  260.             if (prev_xp == clan_xp or (clan_xp == 0 and prev_type == "C")) and elapsed > 0 and session_kills > 0 :
  261.  
  262.                 if (clan_xp < 2000000000 and clan_xp >0) or elapsed < 0:
  263.  
  264.                     update_data.type = "B"
  265.                     row_description = "Bugged"
  266.                     update_data.incremental = 0
  267.                     update_data.calculated = prev_calculated
  268.  
  269.                 else:
  270.  
  271.                     update_data.type = "C"
  272.                     row_description = "Capped"
  273.                     # We need to calculate ESTIMATED XP here.
  274.  
  275.                     disc_rate = NORMAL_DISC_RATE
  276.                     if elapsed < DURATION_MIN or elapsed > DURATION_MAX:
  277.                         disc_rate = ATYPICAL_DISC_RATE
  278.                    
  279.                     est_result = get_rec(est_cur, SELECT_EST_RATE, {'sample_date' : update_data.slice_date, 'player': player})
  280.                     est_rate = int(est_result['estimated_rate'] * disc_rate)
  281.                     est_xp = est_rate * elapsed
  282.                     update_data.estimate_rate = est_rate
  283.                     update_data.estimated = est_xp
  284.                     update_data.incremental = 0
  285.                     update_data.calculated = prev_calculated + est_xp
  286.  
  287.             else:
  288.  
  289.                 # Did someone get reset (leave and rejoin)? We can tell because the clan XP will drop below what it was (probably)
  290.  
  291.                 if prev_xp > clan_xp:
  292.  
  293.                     if clan_xp == 0:  # If it's zero, this is just a ZERO row
  294.  
  295.                         update_data.type = "Z"
  296.                         row_description = "Zero clan XP"
  297.                         update_data.incremental = 0
  298.                         update_data.calculated = prev_calculated + update_data.incremental
  299.  
  300.                     else: # Otherwise we have a member who was reset (left/joined)
  301.  
  302.                         update_data.type = "R"
  303.                         row_description = "Reset"
  304.                         update_data.incremental = clan_xp
  305.                         update_data.calculated = prev_calculated + update_data.incremental
  306.  
  307.                 else:
  308.  
  309.                     # Was the player not online at all?
  310.  
  311.                     if (elapsed == 0 or session_kills ==0) and (clan_xp - prev_xp) == 0:
  312.  
  313.                         update_data.type = "X"
  314.                         row_description = "No activity"
  315.                         update_data.calculated = prev_calculated
  316.  
  317.                     else: # There was some kind of activity for this sample
  318.  
  319.                         update_data.type ="I"
  320.                         row_description = "Incremental"
  321.                         update_data.incremental = clan_xp - prev_xp
  322.                         update_data.calculated = prev_calculated + update_data.incremental
  323.  
  324.                         # If this session is a more typical duration, we can calc the XP rate
  325.                         if elapsed >= DURATION_MIN and elapsed <= DURATION_MAX:
  326.                             # calculate xp rate
  327.                             update_data.estimate_rate = int(update_data.incremental / elapsed)
  328.  
  329.         else:
  330.  
  331.             # This member is new (i.e. first sample for the player)
  332.  
  333.             update_data.type = "N" # New
  334.             row_description = "New"
  335.             session_kills = total_kills
  336.             update_data.incremental = clan_xp
  337.             update_data.calculated = clan_xp
  338.             update_data.kills = session_kills
  339.             prev_xp = 0
  340.  
  341.             # We do not set an estimate_rate for new players
  342.  
  343.         display_rate = 0 # Just used for the console display
  344.  
  345.         if update_data.estimate_rate is not None:
  346.             display_rate = update_data.estimate_rate
  347.  
  348.         if update_data.estimated > 0:
  349.             xp_type="est"
  350.             xp_value = update_data.estimated
  351.         else:
  352.             xp_type="inc"
  353.             xp_value = update_data.incremental
  354.  
  355.         if update_data.type != "X":
  356.  
  357.             # We show samples with no activity without a linefeed on the console, so it's easier to read changes
  358.             print(f"  {player:<12}|{update_data.slice_date}|{update_data.type}|cxp: {clan_xp:>12,}|elap: {elapsed:>6,}|kills: {session_kills:>6,}|{xp_type} cxp: {xp_value:>11,}|calc cxp: {update_data.calculated:>12,}|est.rate: {display_rate:>6,}")
  359.  
  360.         else:
  361.  
  362.             print(f"  {player:<12}|{update_data.slice_date}|{update_data.type}|cxp: {clan_xp:>12,}|elap: {elapsed:>6,}|kills: {session_kills:>6,}|{xp_type} cxp: {xp_value:>11,}|calc cxp: {update_data.calculated:>12,}|est.rate: {display_rate:>6,}", end='\r', flush=True)
  363.  
  364.         # Save to the database!
  365.         update_rec(update_cur, UPDATE_SLICE, vars(update_data))
  366.  
  367.         db.commit()
  368.        
  369.         # We commit after each update so that any contention
  370.         # on the database with a lock will fail immediately
  371.         # We don't want this process locking the database for any duration,
  372.         # since it can resume after failure without issue on a subsequent run
  373.  
  374. db.close()
  375. print("")
  376. print("Complete.")
Advertisement
Add Comment
Please, Sign In to add comment