Coverage for GuiTourneyGraphViewer.py: 0%
187 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-09-28 16:41 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2024-09-28 16:41 +0000
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
4#Copyright 2008-2011 Carl Gherardi
5#This program is free software: you can redistribute it and/or modify
6#it under the terms of the GNU Affero General Public License as published by
7#the Free Software Foundation, version 3 of the License.
8#
9#This program is distributed in the hope that it will be useful,
10#but WITHOUT ANY WARRANTY; without even the implied warranty of
11#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12#GNU General Public License for more details.
13#
14#You should have received a copy of the GNU Affero General Public License
15#along with this program. If not, see <http://www.gnu.org/licenses/>.
16#In the "official" distribution you can find the license in agpl-3.0.txt.
19from __future__ import print_function
20from __future__ import division
22from past.utils import old_div
23import os
24import sys
25from time import time
26from PyQt5.QtWidgets import QFrame, QScrollArea, QSplitter, QVBoxLayout, QMessageBox
27import Database
28import Filters
29import Charset
31try:
32 calluse = not 'matplotlib' in sys.modules
33 import matplotlib
34 if calluse:
35 try:
36 matplotlib.use('qt5agg')
37 except ValueError as e:
38 print(e)
39 from matplotlib.figure import Figure
40 from matplotlib.backends.backend_qt5agg import FigureCanvas
41 from matplotlib.font_manager import FontProperties
42 from numpy import arange, cumsum
43except ImportError as inst:
44 print(("""Failed to load libs for graphing, graphing will not function. Please install numpy and matplotlib if you want to use graphs."""))
45 print(("""This is of no consequence for other parts of the program, e.g. import and HUD are NOT affected by this problem."""))
46 print("ImportError: %s" % inst.args)
48class GuiTourneyGraphViewer(QSplitter):
50 def __init__(self, querylist, config, parent, colors, debug=True):
51 """Constructor for GraphViewer"""
52 QSplitter.__init__(self, parent)
53 self.sql = querylist
54 self.conf = config
55 self.debug = debug
56 self.parent = parent
57 self.colors = colors
58 self.db = Database.Database(self.conf, sql=self.sql)
60 filters_display = {
61 "Heroes": True,
62 "Sites": True,
63 "Games": False, # cash game
64 "Tourney": True,
65 "TourneyCat": True,
66 "TourneyLim": True,
67 "TourneyBuyin": True,
68 "Currencies": True,
69 "Limits": False,
70 "LimitSep": True,
71 "LimitType": True,
72 "Type": True,
73 "UseType": 'tour',
74 "Seats": False,
75 "SeatSep": True,
76 "Dates": True,
77 "Groups": False,
78 "Button1": True,
79 "Button2": True
80 }
82 self.filters = Filters.Filters(self.db, display=filters_display)
83 self.filters.registerButton1Name("Refresh Graph")
84 self.filters.registerButton1Callback(self.generateGraph)
85 self.filters.registerButton2Name("Export to File")
86 self.filters.registerButton2Callback(self.exportGraph)
88 scroll = QScrollArea()
89 scroll.setWidget(self.filters)
90 self.addWidget(scroll)
92 frame = QFrame()
93 frame.setStyleSheet(f'background-color: {self.colors["background"]}')
94 self.graphBox = QVBoxLayout()
95 frame.setLayout(self.graphBox)
96 self.addWidget(frame)
97 self.setStretchFactor(0, 0)
98 self.setStretchFactor(1, 1)
100 self.fig = None
101 self.canvas = None
103 self.db.rollback()
104 self.exportFile = None
106 def clearGraphData(self):
107 try:
108 if self.canvas:
109 self.graphBox.removeWidget(self.canvas)
110 except:
111 pass
113 if self.fig is not None:
114 self.fig.clear()
115 self.fig = Figure(figsize=(5.0, 4.0), dpi=100)
116 self.fig.patch.set_facecolor(self.colors["background"])
117 if self.canvas is not None:
118 self.canvas.destroy()
120 self.canvas = FigureCanvas(self.fig)
121 self.canvas.setParent(self)
123 def generateGraph(self, widget):
124 self.clearGraphData()
126 sitenos = []
127 playerids = []
129 sites = self.filters.getSites()
130 heroes = self.filters.getHeroes()
131 siteids = self.filters.getSiteIds()
133 games = self.filters.getGames()
134 names = ""
136 for site in sites:
137 sitenos.append(siteids[site])
138 _hname = Charset.to_utf8(heroes[site])
139 result = self.db.get_player_id(self.conf, site, _hname)
140 if result is not None:
141 playerids.append(int(result))
142 names = names + "\n" + _hname + " on " + site
144 if not sitenos:
145 print("No sites selected - defaulting to PokerStars")
146 self.db.rollback()
147 return
149 if not playerids:
150 print("No player ids found")
151 self.db.rollback()
152 return
154 self.ax = self.fig.add_subplot(111)
155 starttime = time()
156 green = self.getData(playerids, sitenos, games)
157 print("Graph generated in: %s" % (time() - starttime))
159 self.ax.set_xlabel("Tournaments", color=self.colors['foreground'])
160 self.ax.set_facecolor(self.colors['background'])
161 self.ax.tick_params(axis='x', colors=self.colors['foreground'])
162 self.ax.tick_params(axis='y', colors=self.colors['foreground'])
163 self.ax.spines['left'].set_color(self.colors['foreground'])
164 self.ax.spines['right'].set_color(self.colors['foreground'])
165 self.ax.spines['top'].set_color(self.colors['foreground'])
166 self.ax.spines['bottom'].set_color(self.colors['foreground'])
167 self.ax.set_ylabel("$", color=self.colors['foreground'])
168 self.ax.grid(color=self.colors['grid'], linestyle=':', linewidth=0.2)
169 if green is None or len(green) == 0:
170 self.ax.set_title("No Data for Player(s) Found", color=self.colors['foreground'])
171 green = ([0., 0., 0., 0., 500., 1000., 900., 800., 700., 600., 500., 400., 300., 200., 100., 0., 500., 1000., 1000., 1000., 1000., 1000., 1000., 1000., 1000., 1000., 1000., 1000., 1000., 1000., 875., 750., 625., 500., 375., 250., 125., 0., 0., 0., 0., 500., 1000., 900., 800., 700., 600., 500., 400., 300., 200., 100., 0., 500., 1000., 1000.])
173 self.ax.plot(green, color='green', label='Tournaments: %d\nProfit: $%.2f' % (len(green), green[-1]))
174 self.graphBox.addWidget(self.canvas)
175 self.canvas.show()
176 self.canvas.draw()
177 else:
178 self.ax.set_title("Tournament Results" + names, color=self.colors['foreground'])
179 self.ax.plot(green, color='green', label='Tournaments: %d\nProfit: $%.2f' % (len(green), green[-1]))
180 legend = self.ax.legend(loc='upper left', fancybox=True, shadow=True, prop=FontProperties(size='smaller'), facecolor=self.colors["background"], labelcolor=self.colors['foreground'])
181 self.graphBox.addWidget(self.canvas)
182 self.canvas.draw()
184 def getData(self, names, sites, Tourneys):
185 tmp = self.sql.query['tourneyGraphType']
186 start_date, end_date = self.filters.getDates()
187 tourneys = self.filters.getTourneyTypes()
188 tourneysCat = self.filters.getTourneyCat()
189 tourneysLim = self.filters.getTourneyLim()
190 tourneysBuyin = self.filters.getTourneyBuyin()
192 currencies = {'EUR': 'EUR', 'USD': 'USD', '': 'T$'}
193 currencytest = str(tuple(currencies.values()))
194 currencytest = currencytest.replace(",)", ")")
195 currencytest = currencytest.replace("u'", "'")
196 currencytest = "AND tt.currency in %s" % currencytest
198 nametest = str(tuple(names))
199 sitetest = str(tuple(sites))
200 tourneystest = str(tuple(tourneys))
201 tourneysCattest = str(tuple(tourneysCat))
202 tourneysLimtest = str(tuple(tourneysLim))
203 tourneysBuyintest = str(tuple(int(buyin.split(',')[0]) for buyin in tourneysBuyin if buyin != "None"))
204 tourneystest = tourneystest.replace('None', '"None"')
205 tourneysBuyintest = tourneysBuyintest.replace('None', '"None"')
207 tmp = tmp.replace("<player_test>", nametest)
208 tmp = tmp.replace("<site_test>", sitetest)
209 tmp = tmp.replace("<startdate_test>", start_date)
210 tmp = tmp.replace("<enddate_test>", end_date)
211 tmp = tmp.replace("<currency_test>", currencytest)
212 tmp = tmp.replace("<tourney_cat>", tourneysCattest)
213 tmp = tmp.replace("<tourney_lim>", tourneysLimtest)
214 tmp = tmp.replace("<tourney_buyin>", tourneysBuyintest)
215 tmp = tmp.replace("<tourney_test>", tourneystest)
216 tmp = tmp.replace(",)", ")")
218 print("DEBUG: sql query:", tmp)
220 self.db.cursor.execute(tmp)
221 winnings = self.db.cursor.fetchall()
222 self.db.rollback()
224 if len(winnings) == 0:
225 return None
227 green = [float(x[1]) for x in winnings]
228 greenline = cumsum(green)
229 return (old_div(greenline, 100))
233 def exportGraph(self):
234 if self.fig is None:
235 return
237 else:
238 path = os.getcwd()
239 path = path + '/graph.png'
240 self.fig.savefig(path)
241 msg = QMessageBox()
242 msg.setWindowTitle("FPDB 3 info")
243 mess = "Your graph is saved in " + path
244 msg.setText(mess)
245 msg.exec()
247if __name__ == "__main__":
248 import Configuration
249 config = Configuration.Config()
251 settings = {}
253 settings.update(config.get_db_parameters())
254 settings.update(config.get_import_parameters())
255 settings.update(config.get_default_paths())
257 from PyQt5.QtWidgets import QApplication, QMainWindow
258 app = QApplication([])
259 import SQL
260 sql = SQL.Sql(db_server=settings['db-server'])
262 colors = {
263 'background': '#19232D',
264 'foreground': '#9DA9B5',
265 'grid': '#4D4D4D',
266 'line_up': 'g',
267 'line_down': 'r'
268 }
270 i = GuiTourneyGraphViewer(sql, config, None, colors)
271 main_window = QMainWindow()
272 main_window.setCentralWidget(i)
273 main_window.show()
274 main_window.resize(1400, 800)
275 app.exec_()