Exemplo n.º 1
0
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.setWindowTitle("Self Spy")
        self.spy = 0
        self.setWindowFlag(Qt.WindowTitleHint)
        self.resize(1000, 900)
        self.setStyleSheet("background-color: #F0DFF7;")

        self.highGroundLayout = QHBoxLayout()

        self.clock = Clock()
        self.focusChart = PieChart()

        self.highGroundLayout.addWidget(self.clock)
        self.highGroundLayout.addWidget(self.focusChart)

        self.focusLayout = Focus(self.focusName, self.focusTime)
        self.activeLayout = Active(self.activeName, self.activeTime)

        self.middleLayout = QHBoxLayout()
        self.middleLayout.addLayout(self.focusLayout)
        self.middleLayout.addLayout(self.activeLayout)

        self.layout.addLayout(self.highGroundLayout)
        self.layout.addLayout(self.middleLayout)

        widget = QWidget()
        widget.setLayout(self.layout)
        self.setCentralWidget(widget)
Exemplo n.º 2
0
    def __init__(self, parent, **optional_arguments):
        tkinter.LabelFrame.__init__(self,
                                    parent,
                                    text=optional_arguments['text'])
        self.colors = None

        # setup default parameters and then process optional arguments
        self.field_count = default_field_count
        self.process_optional_arguments(optional_arguments)

        # setup the table showing initial balance, current balance, and expenditure totals
        self.totals_table: TableWidget = None
        self.load_total_amounts()

        # sets up a separator between the two tables
        separator = Separator(self)
        separator.grid(row=0, column=1, sticky="NS")

        # setup the table showing spending by category
        self.category_table: TableWidget = None
        self.load_spending_by_category()

        # setup the pie chart
        self.pie_chart = PieChart(self)
        self.pie_chart.grid(row=1, columnspan=3)

        self.load_table_data(None, None, None)
Exemplo n.º 3
0
def make_pie_chart(title, labels, values):
    try:
        pie_chart = PieChart(title, labels, values)
        pie_chart.give_graph()
    except (ValueError, IndexError):
        print("Incorrect arguments in pie chart")
    else:
        print("Pie Chart Made!")
Exemplo n.º 4
0
class MainWindow(QMainWindow):
    focusName = ['-', '-', '-', '-', '-']
    focusTime = ['00:00:00', '00:00:00', '00:00:00', '00:00:00', '00:00:00']
    activeName = ['-', '-', '-', '-', '-']
    activeTime = ['00:00:00', '00:00:00', '00:00:00', '00:00:00', '00:00:00']
    layout = QVBoxLayout()
    fileToRead = 'temp.csv'
    running = True

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.setWindowTitle("Self Spy")
        self.spy = 0
        self.setWindowFlag(Qt.WindowTitleHint)
        self.resize(1000, 900)
        self.setStyleSheet("background-color: #F0DFF7;")

        self.highGroundLayout = QHBoxLayout()

        self.clock = Clock()
        self.focusChart = PieChart()

        self.highGroundLayout.addWidget(self.clock)
        self.highGroundLayout.addWidget(self.focusChart)

        self.focusLayout = Focus(self.focusName, self.focusTime)
        self.activeLayout = Active(self.activeName, self.activeTime)

        self.middleLayout = QHBoxLayout()
        self.middleLayout.addLayout(self.focusLayout)
        self.middleLayout.addLayout(self.activeLayout)

        self.layout.addLayout(self.highGroundLayout)
        self.layout.addLayout(self.middleLayout)

        widget = QWidget()
        widget.setLayout(self.layout)
        self.setCentralWidget(widget)

    def closeEvent(self, event):
        self.running = False

    def initSpy(self):
        self.spy = Spy(self)

    def updateWindow(self, focusName, focusTime, activeName, activeTime,
                     focusPath):
        self.focusLayout.updateName(focusName)
        sleep(0.5)
        self.focusLayout.updateTime(focusTime)
        sleep(0.5)
        self.activeLayout.updateName(activeName)
        sleep(0.5)
        self.activeLayout.updateTime(activeTime)
        sleep(1.25)
        self.focusChart.chartUpdate(focusPath)
Exemplo n.º 5
0
 def get_pie_chart(self, title, labels, values):
     try:
         pie_chart = PieChart(title, labels, values)
         pie_chart.give_graph()
     except (ValueError, IndexError):
         print("Incorrect arguments in pie chart")
         return False
     else:
         print("Pie Chart Made!")
         return True
Exemplo n.º 6
0
 def change_vistype(self, target_vis): 
     keywords = self.vis_object.keywords
     #currentvis==BarChart 
     if isinstance(self.vis_object, BarChart) and target_vis=="ColumnChart":
         self.vis_object = ColumnChart(self.vis_object.dataframe, self.vis_object.get_y_encoding(), self.vis_object.get_x_encoding(), keywords)
     elif isinstance(self.vis_object, BarChart) and target_vis=="PieChart":
         self.vis_object = PieChart(self.vis_object.dataframe, self.vis_object.get_x_encoding(), self.vis_object.get_y_encoding(), keywords)
     elif isinstance(self.vis_object, BarChart) and target_vis=="ScatterPlot":
         self.vis_object = ScatterPlot(self.vis_object.dataframe, self.vis_object.get_x_encoding(), self.vis_object.get_y_encoding(), keywords)
     #currentvis==ColumnChart 
     if isinstance(self.vis_object, ColumnChart) and target_vis=="BarChart":
         self.vis_object = BarChart(self.vis_object.dataframe, self.vis_object.get_y_encoding(), self.vis_object.get_x_encoding(), keywords)
     elif isinstance(self.vis_object, ColumnChart) and target_vis=="PieChart":
         self.vis_object = BarChart(self.vis_object.dataframe, self.vis_object.get_y_encoding(), self.vis_object.get_x_encoding(), keywords)
     elif isinstance(self.vis_object, ColumnChart) and target_vis=="ScatterPlot":
         self.vis_object = ScatterPlot(self.vis_object.dataframe, self.vis_object.get_x_encoding(), self.vis_object.get_y_encoding(), keywords)
     #currentvis==PieChart
     if isinstance(self.vis_object, PieChart) and target_vis=="BarChart":
         self.vis_object = BarChart(self.vis_object.dataframe, self.vis_object.get_color_encoding(), self.vis_object.get_theta_encoding(), keywords)
     elif isinstance(self.vis_object, PieChart) and target_vis=="ColumnChart":
         self.vis_object = BarChart(self.vis_object.dataframe, self.vis_object.get_theta_encoding(), self.vis_object.get_color_encoding(), keywords)
     elif isinstance(self.vis_object, PieChart) and target_vis=="ScatterPlot":
         self.vis_object = ScatterPlot(self.vis_object.dataframe, self.vis_object.get_theta_encoding(), self.vis_object.get_color_encoding(), keywords) 
     #currentvis=Scatterplot 
     if isinstance(self.vis_object, ScatterPlot) and target_vis=="ColumnChart":
         if self.vis_object.get_y_encoding()["type"] == "nominal" and self.vis_object.get_x_encoding()["type"] == "quantitative":
                  x_encoding = self.vis_object.get_x_encoding()
                  x_encoding["aggregate"] = "sum"
                  self.vis_object = ColumnChart(self.vis_object.dataframe, x_encoding,self.vis_object.get_y_encoding(), keywords)
         elif self.vis_object.get_x_encoding()["type"] == "nominal" and self.vis_object.get_y_encoding()["type"] == "quantitative":
                 y_encoding = self.vis_object.get_y_encoding()
                 y_encoding["aggregate"] = "sum"
                 self.vis_object = ColumnChart(self.vis_object.dataframe, y_encoding, self.vis_object.get_x_encoding(), keywords)
         else: 
             self.vis_object = BarChart(self.vis_object.dataframe, self.vis_object.get_x_encoding(), self.vis_object.get_y_encoding(), keywords)
     elif isinstance(self.vis_object, ScatterPlot) and target_vis=="PieChart":
         if self.vis_object.get_x_encoding()["type"] == "nominal" and self.vis_object.get_y_encoding()["type"] == "quantitative":
                  y_encoding = self.vis_object.get_y_encoding()
                  y_encoding["aggregate"] = "sum"
                  self.vis_object = PieChart(self.vis_object.dataframe, self.vis_object.get_x_encoding(), y_encoding, keywords)
         elif self.vis_object.get_y_encoding()["type"] == "nominal" and self.vis_object.get_x_encoding()["type"] == "quantitative":
                 x_encoding = self.vis_object.get_x_encoding()
                 x_encoding["aggregate"] = "sum"
                 self.vis_object = PieChart(self.vis_object.dataframe, x_encoding, self.vis_object.get_y_encoding(), keywords)
     elif isinstance(self.vis_object, ScatterPlot) and target_vis=="BarChart":
         if self.vis_object.get_x_encoding()["type"] == "nominal" and self.vis_object.get_y_encoding()["type"] == "quantitative":
                  y_encoding = self.vis_object.get_y_encoding()
                  y_encoding["aggregate"] = "sum"
                  self.vis_object = BarChart(self.vis_object.dataframe, self.vis_object.get_x_encoding(), y_encoding, keywords)
         elif self.vis_object.get_y_encoding()["type"] == "nominal" and self.vis_object.get_x_encoding()["type"] == "quantitative":
                 x_encoding = self.vis_object.get_x_encoding()
                 x_encoding["aggregate"] = "sum"
                 self.vis_object = BarChart(self.vis_object.dataframe, x_encoding, self.vis_object.get_y_encoding(), keywords)
         else: 
             self.vis_object = BarChart(self.vis_object.dataframe, self.vis_object.get_x_encoding(), self.vis_object.get_y_encoding(), keywords)
Exemplo n.º 7
0
 def open(self, caller, *largs, **kwargs):
     self.piechart_box.clear_widgets()
     if caller.labelling:
         in_data = {
             "Approved": (caller.nb_approved, [.19, .80, .84, 1]),
             "Not approved":
             (caller.nb_documents - caller.nb_approved, [.83, .86, .89, 1])
         }
         boxlayout = BoxLayout(orientation='vertical')
         box = BoxLayout(size_hint_y=0.9)
         box.add_widget(PieChart(in_data=in_data))
         boxlayout.add_widget(box)
         boxlayout.add_widget(
             Label(text="Labelling",
                   size_hint_y=0.1,
                   halign='center',
                   valign='middle',
                   font_size=25))
         self.piechart_box.add_widget(boxlayout)
     if caller.classification:
         colors = [[randint(10, 50) / 50 for i in range(3)] + [1]]
         in_data = {"Unclassified": (caller.nb_documents, colors[0])}
         for _class in list(caller.class_directory.values()):
             new_col = [randint(10, 50) / 50 for i in range(3)] + [1]
             limit = 0
             while True in [dist(new_col, col) < 0.3
                            for col in colors] and limit < 10:
                 new_col = [randint(10, 50) / 50 for i in range(3)] + [1]
                 limit += 1
             colors.append(new_col)
             in_data[_class.name] = (len(_class.batch), new_col)
             in_data["Unclassified"] = (in_data["Unclassified"][0] -
                                        len(_class.batch),
                                        in_data["Unclassified"][1])
         _temp = in_data["Unclassified"]
         del in_data["Unclassified"]
         in_data["Unclassified"] = _temp
         boxlayout = BoxLayout(orientation='vertical')
         box = BoxLayout(size_hint_y=0.9)
         box.add_widget(PieChart(in_data=in_data))
         boxlayout.add_widget(box)
         boxlayout.add_widget(
             Label(text="Classification",
                   size_hint_y=0.1,
                   halign='center',
                   valign='middle',
                   font_size=25))
         self.piechart_box.add_widget(boxlayout)
     super(ProjectPopup, self).open(*largs, **kwargs)
Exemplo n.º 8
0
def nl4dv_query():
    if request.method == "POST":
        post_data = (request.get_json())
        nl4dv_results = nl4dv_output_parser(
            nl4dvQueryAnalyzerFinancialsDataset(post_data[0]))
        #decide which object to create
        if nl4dv_results["vis_type"] == "bar":
            bar_chart = BarChart(working_dataframe,
                                 nl4dv_results["encoding"]["x"],
                                 nl4dv_results["encoding"]["y"])
            final_vis = VisHandler(bar_chart)
            print(final_vis.serialize_object())
        if nl4dv_results["vis_type"] == "arc":
            pie_chart = PieChart(working_dataframe,
                                 nl4dv_results["encoding"]["color"],
                                 nl4dv_results["encoding"]["theta"])
            final_vis = VisHandler(pie_chart)
        if nl4dv_results["vis_type"] == "point":
            print(nl4dv_results)
            scatter_plot = ScatterPlot(working_dataframe,
                                       nl4dv_results["encoding"]["x"],
                                       nl4dv_results["encoding"]["y"])
            final_vis = VisHandler(scatter_plot)
            print(final_vis.jsonify_vis())
        return ({
            'values': final_vis.jsonify_vis(),
            'specs': final_vis.serialize_object()
        })
Exemplo n.º 9
0
    def makeTotals(self, date, showPie=False, printme=False):
        self.read(date)

        kC_total = 0
        carb_total = Carb(0, 0, 0)
        protein_total = 0
        fat_total = 0

        if len(self.foodlog) == 0:
            INFO("nothing logged for date: %s" % date)
            prevD = previousDay(ymd2secs(date.split('/')))
            if ynprompt("Print day before that (%s)? " % prevD):
                return self.makeTotals(prevD, showPie, printme)

        if printme:
            INFO('\n' * 10)
            Yemek.printFullHeader()

        after_L_head = False
        after_6_head = False

        for y in self.foodlog:
            scyem = y.scaled()

            kC_total += scyem.kC
            carb_total.add(scyem.carb)
            protein_total += scyem.prot
            fat_total += scyem.fat

            if printme:
                if not (after_L_head) and (y.hour >= 12):
                    print('        ===== Lunch ====', file=sys.stderr)
                    after_L_head = True
                if not (after_6_head) and (y.hour >= 18):
                    print('        ===== Dinner ====', file=sys.stderr)
                    after_6_head = True
                print(scyem.printout(), file=sys.stderr)

        self.pie = PieChart(carb_total,
                            protein_total,
                            fat_total,
                            kC_total,
                            self.macrofile,
                            Yemek.buffer - 8,
                            8,
                            printme=showPie)

        return kC_total, carb_total, protein_total, fat_total
Exemplo n.º 10
0
def deserialize_object(final_vis_data):
    if final_vis_data["type"] == "BarChart":
        bar_chart = BarChart(working_dataframe, final_vis_data["x_encoding"],
                             final_vis_data["y_encoding"],
                             final_vis_data["keywords"])
        return VisHandler(bar_chart)
    if final_vis_data["type"] == "ColumnChart":
        column_chart = ColumnChart(working_dataframe,
                                   final_vis_data["x_encoding"],
                                   final_vis_data["y_encoding"],
                                   final_vis_data["keywords"])
        return VisHandler(column_chart)
    if final_vis_data["type"] == "PieChart":
        pie_chart = PieChart(working_dataframe,
                             final_vis_data["color_encoding"],
                             final_vis_data["theta_encoding"],
                             final_vis_data["keywords"])
        return VisHandler(pie_chart)
    if final_vis_data["type"] == "ScatterPlot":
        scatter_plot = ScatterPlot(working_dataframe,
                                   final_vis_data["x_encoding"],
                                   final_vis_data["y_encoding"],
                                   final_vis_data["keywords"])
        return VisHandler(scatter_plot)
Exemplo n.º 11
0
 def test_pie_build(self):
     pie_chart = PieChart('pie title', ['one', 'two'], [1, 2])
     self.assertTrue(pie_chart.give_graph())
Exemplo n.º 12
0
 def test_pie_values(self):
     pie_chart = PieChart('pie title', ['one', 'two'], [1, 2])
     self.assertEqual(pie_chart.test_values(), [1, 2])
Exemplo n.º 13
0
class DataVisualizer(tkinter.LabelFrame):
    def __init__(self, parent, **optional_arguments):
        tkinter.LabelFrame.__init__(self,
                                    parent,
                                    text=optional_arguments['text'])
        self.colors = None

        # setup default parameters and then process optional arguments
        self.field_count = default_field_count
        self.process_optional_arguments(optional_arguments)

        # setup the table showing initial balance, current balance, and expenditure totals
        self.totals_table: TableWidget = None
        self.load_total_amounts()

        # sets up a separator between the two tables
        separator = Separator(self)
        separator.grid(row=0, column=1, sticky="NS")

        # setup the table showing spending by category
        self.category_table: TableWidget = None
        self.load_spending_by_category()

        # setup the pie chart
        self.pie_chart = PieChart(self)
        self.pie_chart.grid(row=1, columnspan=3)

        self.load_table_data(None, None, None)

    def process_optional_arguments(self, optional_arguments):
        if 'field_count' in optional_arguments.keys():
            self.field_count = optional_arguments['field_count']

    def load_spending_by_category(self):
        self.category_table = TableWidget(self,
                                          2,
                                          self.field_count,
                                          head_font=default_table_head_font,
                                          entry_font=default_entry_font,
                                          entry_justify_list=["right", "left"],
                                          head_justify_list=["right", "left"])
        self.category_table.hide_config_buttons()
        self.category_table.set_header_values(['Category', 'Amount'])
        self.category_table.grid(row=0, column=2)

    def load_total_amounts(self):
        self.totals_table = TableWidget(
            self,
            3,
            1,
            entry_font=default_entry_font,
            entry_justify=["left"],
            head_justify_list=["right", "right", "right"],
            invert_axis=True)
        self.totals_table.hide_config_buttons()
        self.totals_table.set_header_values(
            ["Initial Total", "Expenditure Total", "Current Total"])
        self.totals_table.grid(row=0, column=0)

    def load_table_data(self, expenditures_by_type: [[]], initial_balances,
                        current_balances):
        self.load_expenditure_data(expenditures_by_type)
        self.load_totals_data(initial_balances, expenditures_by_type,
                              current_balances)
        self.update_colors()

    def load_expenditure_data(self, expenditures_by_type: [[]]):
        if expenditures_by_type is not None and expenditures_by_type != []:
            labels = []
            values = []
            table = []
            for row_index in range(len(expenditures_by_type)):
                labels.append(expenditures_by_type[row_index][0])
                values.append(expenditures_by_type[row_index][1])
                table.append([
                    expenditures_by_type[row_index][0],
                    TableWidget.format_as_currency(
                        expenditures_by_type[row_index][1])
                ])
            self.category_table.load_table_data(table)
            self.pie_chart.construct_pie_chart(
                labels, values, text_col=self.pie_chart.label_text_col)
        else:
            self.category_table.clear_labels()
            self.pie_chart.construct_empty_chart()

    def load_totals_data(self, initial_balances, expenditures_by_type,
                         current_balances):
        if expenditures_by_type is not None and expenditures_by_type != []:
            total_spending = 0
            for row in expenditures_by_type:
                total_spending += row[1]
            spending_text = TableWidget.format_as_currency(total_spending)
            self.totals_table.set_value(spending_text, 0, 1)
        else:
            self.totals_table.set_value("-", 0, 1)

        if initial_balances is not None and initial_balances != []:
            total_initial_balance = 0
            for balance in initial_balances:
                total_initial_balance += balance[2]
            initial_text = TableWidget.format_as_currency(
                total_initial_balance)
            self.totals_table.set_value(initial_text, 0, 0)
        else:
            self.totals_table.set_value("-", 0, 0)

        if current_balances is not None and current_balances != []:
            total_current_balance = 0
            for balance in current_balances:
                total_current_balance += balance[2]
            current_text = TableWidget.format_as_currency(
                total_current_balance)
            self.totals_table.set_value(current_text, 0, 2)
        else:
            self.totals_table.set_value("-", 0, 2)

    def set_colors(self, color_dict: {str: str}):
        self.colors = color_dict
        self.update_colors()

    def update_colors(self):
        if self.colors is not None:
            self.config(bg=self.colors['bg_col'], fg=self.colors['text_col'])
            self.pie_chart.set_colors(self.colors['pie_chart_colors'])
            self.category_table.set_colors(
                self.colors['category_table_colors'])
            self.totals_table.set_colors(self.colors['totals_table_colors'])
Exemplo n.º 14
0
	def __init__(self, dataPath, version) :
		QtGui.QDialog.__init__(self)
		self.setWindowTitle(self.tr("enVote %1 - Votation simulator").arg(version))
		self._dataPath = dataPath
		files = sorted(glob.glob(self.dataPath("*")))
		if not files :
			QtGui.QMessageBox.critical(self,
				self.tr("Error loading data"),
				self.tr("The application is unable to find out the data set"))
			raise RuntimeError("The application is unable to find the data set")

		self.cases = sorted([
			(os.path.splitext(os.path.basename(name))[0], Simulador.Resultats(file(name)))
			for name in files
			])
	
		self.currentCase = 0
		self.case = None

		colors = dict(
			abstencion="darkgrey",
			blancos="white",
			nulos="#F44",
			CiU="blue",
			CIU="blue",
			PP="cyan",
			ERC="orange",
			ESQUERRA="orange",
			** {
			"PSOE" : "red",
			"PSC" : "red",
			"PSC-PSOE" : "red",
			"ICV-EUiA" : "green",
			"IC-V" : "green",
			"IC" : "green",
			"IC-EV" : "green",
			"IU" : "green",
			"PSUC" : "green",
			"PSUC-PCE" : "green",
			})

		layout = QtGui.QVBoxLayout()
		self.setLayout(layout)

		chartLayout = QtGui.QGridLayout()
		layout.addLayout(chartLayout)

		self.votesChart = PieChart()
		self.votesChart.setToolTip(self.tr("Whole census"))
		chartLayout.addWidget(self.votesChart,0,0)
		self.votesChart.setSectorColors(colors)

		self.candidaturesChart = PieChart()
		self.candidaturesChart.setToolTip(self.tr("Just votes to candidatures"))
		chartLayout.addWidget(self.candidaturesChart, 0,1)
		self.candidaturesChart.setSectorColors(colors)

		self.sconsChart = PieChart()
		self.sconsChart.setToolTip(self.tr("Hondt distribution (legal)"))
		chartLayout.addWidget(self.sconsChart,0,2)
		self.sconsChart.setSectorColors(colors)

		self.proportionalChart = PieChart()
		self.proportionalChart.setToolTip(self.tr("Hamilton distribution (proportional)"))
		chartLayout.addWidget(self.proportionalChart, 0,3)
		self.proportionalChart.setSectorColors(colors)

		titleBox = QtGui.QHBoxLayout()
		layout.addLayout(titleBox)
		self.title = QtGui.QComboBox()
		titleBox.addWidget(self.title)
		self.title.setToolTip(self.tr("Current case being displayed"))
		self.title.addItems([name for name, case in self.cases])
		self.title.currentIndexChanged.connect(self.titleChanged)
		titleBox.addWidget(QtGui.QWidget()) # spacer
		prevButton = QtGui.QPushButton(self.tr("&Previous"))
		prevButton.setToolTip(self.tr("Switch to the previous case"))
		titleBox.addWidget(prevButton)
		nextButton = QtGui.QPushButton(self.tr("&Next"))
		nextButton.setToolTip(self.tr("Switch to the next case"))
		titleBox.addWidget(nextButton)

		buttonBox = QtGui.QHBoxLayout()
		layout.addLayout(buttonBox)
		self._from = QtGui.QComboBox()
		self._from.setToolTip(self.tr("Vote transfer origin"))
		self._to = QtGui.QComboBox()
		self._to.setToolTip(self.tr("Vote transfer destination"))
		transfer = QtGui.QPushButton(self.tr("&Transfer"))
		transfer.setToolTip(self.tr("Transfer votes"))
		invert = QtGui.QPushButton(self.tr("&Invert"))
		invert.setToolTip(self.tr("Swap transfer sides"))
		self._tranferSize = QtGui.QSpinBox()
		self._tranferSize.setToolTip(self.tr("Number of votes to be transferred"))
		self._tranferSize.setMinimum(1)
		self._tranferSize.setMaximum(1000000)
		self._tranferSize.setValue(10000)
		self._tranferSize.setSuffix(self.tr(" votes"))
		arrow = QtGui.QLabel("->")
		arrow.setSizePolicy(
			QtGui.QSizePolicy.Fixed,
			QtGui.QSizePolicy.Fixed,
			)
		buttonBox.addWidget(self._from)
		buttonBox.addWidget(arrow)
		buttonBox.addWidget(self._to)
		buttonBox.addWidget(self._tranferSize)
		buttonBox.addWidget(transfer)
		buttonBox.addWidget(invert)
		buttonBox.addWidget(QtGui.QWidget()) # spacer

		copyButton = QtGui.QPushButton(self.tr("&Save As"))
		copyButton.setToolTip(self.tr("Save a copy the current case with a new name"))
		buttonBox.addWidget(copyButton)
		resetButton = QtGui.QPushButton(self.tr("&Reset"))
		resetButton.setToolTip(self.tr("Restore the case to the latest saved state"))
		buttonBox.addWidget(resetButton)
		saveButton = QtGui.QPushButton(self.tr("&Save"))
		saveButton.setToolTip(self.tr("Save the changes done to the case"))
		buttonBox.addWidget(saveButton)

		statLayout = QtGui.QHBoxLayout()
		layout.addLayout(statLayout)
		def label() :
			label=QtGui.QLabel()
			statLayout.addWidget(label)
			return label
		self.censusLabel = label()
		self.abstentionLabel = label()
		self.nullLabel = label()
		self.blankLabel = label()
		self.thresholdLabel = label()
		self.seatsLabel = label()
		self.seatsSpiner = QtGui.QSpinBox()
		self.seatsSpiner.setMinimum(1)
		self.seatsSpiner.setMaximum(99999)
		statLayout.addWidget(self.seatsSpiner)

		self.restLabelHondt = QtGui.QLabel()
		layout.addWidget(self.restLabelHondt)
		self.restLabelProportional = QtGui.QLabel()
		layout.addWidget(self.restLabelProportional)

		transfer.clicked.connect(self.transfer)
		invert.clicked.connect(self.invertTransfer)
		nextButton.clicked.connect(self.nextDatabase)
		prevButton.clicked.connect(self.previousDatabase)
		saveButton.clicked.connect(self.save)
		resetButton.clicked.connect(self.reset)
		copyButton.clicked.connect(self.copy)
		self.votesChart.sectorLeftClicked.connect(self.selectFrom)
		self.votesChart.sectorRightClicked.connect(self.selectTo)
		self.candidaturesChart.sectorLeftClicked.connect(self.selectFrom)
		self.candidaturesChart.sectorRightClicked.connect(self.selectTo)
		self.proportionalChart.sectorLeftClicked.connect(self.selectFrom)
		self.proportionalChart.sectorRightClicked.connect(self.selectTo)
		self.sconsChart.sectorLeftClicked.connect(self.selectFrom)
		self.sconsChart.sectorRightClicked.connect(self.selectTo)

		self.seatsSpiner.valueChanged.connect(self.changeSeats)

		self.hondtTable = HondtTable()
		layout.addWidget(self.hondtTable)

		self.updateDatabase()
Exemplo n.º 15
0
class Envoter(QtGui.QDialog) :
	def __init__(self, dataPath, version) :
		QtGui.QDialog.__init__(self)
		self.setWindowTitle(self.tr("enVote %1 - Votation simulator").arg(version))
		self._dataPath = dataPath
		files = sorted(glob.glob(self.dataPath("*")))
		if not files :
			QtGui.QMessageBox.critical(self,
				self.tr("Error loading data"),
				self.tr("The application is unable to find out the data set"))
			raise RuntimeError("The application is unable to find the data set")

		self.cases = sorted([
			(os.path.splitext(os.path.basename(name))[0], Simulador.Resultats(file(name)))
			for name in files
			])
	
		self.currentCase = 0
		self.case = None

		colors = dict(
			abstencion="darkgrey",
			blancos="white",
			nulos="#F44",
			CiU="blue",
			CIU="blue",
			PP="cyan",
			ERC="orange",
			ESQUERRA="orange",
			** {
			"PSOE" : "red",
			"PSC" : "red",
			"PSC-PSOE" : "red",
			"ICV-EUiA" : "green",
			"IC-V" : "green",
			"IC" : "green",
			"IC-EV" : "green",
			"IU" : "green",
			"PSUC" : "green",
			"PSUC-PCE" : "green",
			})

		layout = QtGui.QVBoxLayout()
		self.setLayout(layout)

		chartLayout = QtGui.QGridLayout()
		layout.addLayout(chartLayout)

		self.votesChart = PieChart()
		self.votesChart.setToolTip(self.tr("Whole census"))
		chartLayout.addWidget(self.votesChart,0,0)
		self.votesChart.setSectorColors(colors)

		self.candidaturesChart = PieChart()
		self.candidaturesChart.setToolTip(self.tr("Just votes to candidatures"))
		chartLayout.addWidget(self.candidaturesChart, 0,1)
		self.candidaturesChart.setSectorColors(colors)

		self.sconsChart = PieChart()
		self.sconsChart.setToolTip(self.tr("Hondt distribution (legal)"))
		chartLayout.addWidget(self.sconsChart,0,2)
		self.sconsChart.setSectorColors(colors)

		self.proportionalChart = PieChart()
		self.proportionalChart.setToolTip(self.tr("Hamilton distribution (proportional)"))
		chartLayout.addWidget(self.proportionalChart, 0,3)
		self.proportionalChart.setSectorColors(colors)

		titleBox = QtGui.QHBoxLayout()
		layout.addLayout(titleBox)
		self.title = QtGui.QComboBox()
		titleBox.addWidget(self.title)
		self.title.setToolTip(self.tr("Current case being displayed"))
		self.title.addItems([name for name, case in self.cases])
		self.title.currentIndexChanged.connect(self.titleChanged)
		titleBox.addWidget(QtGui.QWidget()) # spacer
		prevButton = QtGui.QPushButton(self.tr("&Previous"))
		prevButton.setToolTip(self.tr("Switch to the previous case"))
		titleBox.addWidget(prevButton)
		nextButton = QtGui.QPushButton(self.tr("&Next"))
		nextButton.setToolTip(self.tr("Switch to the next case"))
		titleBox.addWidget(nextButton)

		buttonBox = QtGui.QHBoxLayout()
		layout.addLayout(buttonBox)
		self._from = QtGui.QComboBox()
		self._from.setToolTip(self.tr("Vote transfer origin"))
		self._to = QtGui.QComboBox()
		self._to.setToolTip(self.tr("Vote transfer destination"))
		transfer = QtGui.QPushButton(self.tr("&Transfer"))
		transfer.setToolTip(self.tr("Transfer votes"))
		invert = QtGui.QPushButton(self.tr("&Invert"))
		invert.setToolTip(self.tr("Swap transfer sides"))
		self._tranferSize = QtGui.QSpinBox()
		self._tranferSize.setToolTip(self.tr("Number of votes to be transferred"))
		self._tranferSize.setMinimum(1)
		self._tranferSize.setMaximum(1000000)
		self._tranferSize.setValue(10000)
		self._tranferSize.setSuffix(self.tr(" votes"))
		arrow = QtGui.QLabel("->")
		arrow.setSizePolicy(
			QtGui.QSizePolicy.Fixed,
			QtGui.QSizePolicy.Fixed,
			)
		buttonBox.addWidget(self._from)
		buttonBox.addWidget(arrow)
		buttonBox.addWidget(self._to)
		buttonBox.addWidget(self._tranferSize)
		buttonBox.addWidget(transfer)
		buttonBox.addWidget(invert)
		buttonBox.addWidget(QtGui.QWidget()) # spacer

		copyButton = QtGui.QPushButton(self.tr("&Save As"))
		copyButton.setToolTip(self.tr("Save a copy the current case with a new name"))
		buttonBox.addWidget(copyButton)
		resetButton = QtGui.QPushButton(self.tr("&Reset"))
		resetButton.setToolTip(self.tr("Restore the case to the latest saved state"))
		buttonBox.addWidget(resetButton)
		saveButton = QtGui.QPushButton(self.tr("&Save"))
		saveButton.setToolTip(self.tr("Save the changes done to the case"))
		buttonBox.addWidget(saveButton)

		statLayout = QtGui.QHBoxLayout()
		layout.addLayout(statLayout)
		def label() :
			label=QtGui.QLabel()
			statLayout.addWidget(label)
			return label
		self.censusLabel = label()
		self.abstentionLabel = label()
		self.nullLabel = label()
		self.blankLabel = label()
		self.thresholdLabel = label()
		self.seatsLabel = label()
		self.seatsSpiner = QtGui.QSpinBox()
		self.seatsSpiner.setMinimum(1)
		self.seatsSpiner.setMaximum(99999)
		statLayout.addWidget(self.seatsSpiner)

		self.restLabelHondt = QtGui.QLabel()
		layout.addWidget(self.restLabelHondt)
		self.restLabelProportional = QtGui.QLabel()
		layout.addWidget(self.restLabelProportional)

		transfer.clicked.connect(self.transfer)
		invert.clicked.connect(self.invertTransfer)
		nextButton.clicked.connect(self.nextDatabase)
		prevButton.clicked.connect(self.previousDatabase)
		saveButton.clicked.connect(self.save)
		resetButton.clicked.connect(self.reset)
		copyButton.clicked.connect(self.copy)
		self.votesChart.sectorLeftClicked.connect(self.selectFrom)
		self.votesChart.sectorRightClicked.connect(self.selectTo)
		self.candidaturesChart.sectorLeftClicked.connect(self.selectFrom)
		self.candidaturesChart.sectorRightClicked.connect(self.selectTo)
		self.proportionalChart.sectorLeftClicked.connect(self.selectFrom)
		self.proportionalChart.sectorRightClicked.connect(self.selectTo)
		self.sconsChart.sectorLeftClicked.connect(self.selectFrom)
		self.sconsChart.sectorRightClicked.connect(self.selectTo)

		self.seatsSpiner.valueChanged.connect(self.changeSeats)

		self.hondtTable = HondtTable()
		layout.addWidget(self.hondtTable)

		self.updateDatabase()


	def changeSeats(self, seats) :
		print "Value changed"
		if self._updatingSeatsSpinner : return
		self.case.representants = self.seatsSpiner.value()
		self.case.recomputeSeats()
		self.updateViews()

	def dataPath(self, name) :
		return os.path.join(self._dataPath, name+".csv")

	def reset(self) :
		name, case = self.cases[self.currentCase]
		dataFile = file(self.dataPath(name))
		self.cases[self.currentCase] = (name, Simulador.Resultats(dataFile))

		self.updateDatabase()

	def selectFrom(self, candidature) :
		index = self._from.findText(candidature)
		if index < 0 : return
		self._from.setCurrentIndex(index)

	def selectTo(self, candidature) :
		index = self._to.findText(candidature)
		if index < 0 : return
		self._to.setCurrentIndex(index)

	def copy(self) :
		name, case = self.cases[self.currentCase]
		newName, ok = QtGui.QInputDialog.getText(self,
			self.tr("Copy Data Set as"),
			self.tr("Give a new name for the copied case"),
			QtGui.QLineEdit.Normal,
			name+self.tr("-copy","default file suffix"))
		if not ok : return
		newName = str(newName)
		dataFile = file(self.dataPath(newName), "w")
		case.save(dataFile)
		dataFile = file(self.dataPath(newName), "r")
		self.cases.append((newName, Simulador.Resultats(dataFile)))
		self.currentCase=len(self.cases)-1
		self.title.addItem(newName)
		self.title.setCurrentIndex(self.currentCase)

	def save(self) :
		name, case = self.cases[self.currentCase]
		dataFile = file(self.dataPath(name), "w")
		case.save(dataFile)

	def previousDatabase(self) :
		self.currentCase -= 1
		self.currentCase %= len(self.cases)
	
		self.title.setCurrentIndex(self.currentCase)
		
	def nextDatabase(self) :
		self.currentCase += 1
		self.currentCase %= len(self.cases)

		self.title.setCurrentIndex(self.currentCase)

	def titleChanged(self, current) :
		self.currentCase = current

		self.updateDatabase()

	def transfer(self) :
		vots = self.case.vots
		fromOption = str(self._from.currentText())
		toOption = str(self._to.currentText())
		transferSize = min(vots[fromOption], self._tranferSize.value())
		vots[fromOption] -= transferSize
		vots[toOption] += transferSize
		self.case.recomputeSeats()
		self.updateViews()

	def invertTransfer(self) :
		fromOption = self._from.currentIndex()
		toOption = self._to.currentIndex()
		self._from.setCurrentIndex(toOption)
		self._to.setCurrentIndex(fromOption)

	def updateDatabase(self) :
		name, self.case = self.cases[self.currentCase]
		print "Changint to", name
		options = sorted(self.case.vots.keys())
		self._to.clear()
		self._to.addItems(options)
		self._from.clear()
		self._from.addItems(options)
		self.updateViews()

	def updateViews(self) :

		print "Computing proportional"
		toCandidatures = dict((
			(party, votes) 
			for party, votes in self.case.vots.iteritems()
			if party not in [
				'abstencion',
				'blancos',
				'nulos',
				]
			))

		print "Computing Seats"
		s = Simulador.Simulador(self.case.representants, **self.case.vots)
		scons = self.case.scons
		if not sum(self.case.scons.values()) :
			scons = s.repartiment(self.case.representants)
		proportional = s.repartimentProporcional(self.case.representants)
		integer = s.repartimentSencer(self.case.representants)
		restosHondt = [
			(party, scons[party] - integer[party])
			for party in s.partidos()
			if scons[party] != integer[party]
			]
		restosProportional = [
			(party, proportional[party] - integer[party])
			for party in s.partidos()
			if proportional[party] != integer[party]
			]
		self.restLabelHondt.setText(
			self.tr("Rests Hondt: ")+ ("".join([" %s: %+i"%rest for rest in sorted(restosHondt)])))
		self.restLabelProportional.setText(
			self.tr("Rests Hamilton: ")+ ("".join([" %s: %+i"%rest for rest in sorted(restosProportional)])))

		print "Updating Pies"
		self.votesChart.setSectorDescriptions(self.case.descripcions)
		self.votesChart.setSectorValues(**self.case.vots)
		self.candidaturesChart.setSectorDescriptions(self.case.descripcions)
		self.candidaturesChart.setSectorValues(**toCandidatures)
		self.proportionalChart.setSectorDescriptions(self.case.descripcions)
		self.proportionalChart.setSectorValues(**proportional)
		self.sconsChart.setSectorDescriptions(self.case.descripcions)
		self.sconsChart.setSectorValues(**scons)
		print "Hondt Table"
		self.hondtTable.threshold = self.case.votsValids * threshold
		self.hondtTable.nSeats = self.case.representants
		self.hondtTable.feedDescriptions(self.case.descripcions)
		self.hondtTable.feedVotations(toCandidatures)
		print "Stats"
		census = sum(self.case.vots.values())
		def displayStats(widget, text, quantity) :
			percent = 100.*quantity/census
			widget.setText("<b>%s:</b> %i (%.2f%%)"%(
				text, quantity, percent))
		self.censusLabel.setText("<b>%s:</b> %s"%(self.tr("Census"),census))

		displayStats(self.abstentionLabel, self.tr("Abstention"), self.case.vots['abstencion'])
		displayStats(self.nullLabel, self.tr("Nulls"), self.case.vots['nulos'])
		displayStats(self.blankLabel, self.tr("Blanks"), self.case.vots['blancos'])
		displayStats(self.thresholdLabel, self.tr("Threshold (%0%)").arg(threshold*100),
			threshold*(census-self.case.vots['abstencion']-self.case.vots['nulos']))
		self.seatsLabel.setText(self.tr("<b>Seats:</b>"))
		self.seatsLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignVCenter)
		print "Updating seat spinner"
		self._updatingSeatsSpinner = True
		self.seatsSpiner.setValue(self.case.representants)
		self._updatingSeatsSpinner = False
		print "end"