示例#1
0
    def __init__(
            self,
            building_path="data/building_oib_16linie.xlsx",
            kWp=1,  # PV kWp
            battery_kWh=1):  # Battery kWh

        ###### Compononets #####
        # (Other classes and parts, that form the model)
        self.building = Building(path=building_path)
        self.HVAC = HVAC()

        self.PV = PV(csv="data/pv_1kWp.csv", kWp=1)
        self.PV.set_kWp(kWp)

        self.battery = Battery(kWh=battery_kWh)

        ###### Parameters #####
        self.cp_air = 0.34  # spez. Wärme kapazität Luft (Wh/m3K)

        self.price_grid = 0.19  # €/kWh
        self.price_feedin = 0.05  # €/kWh

        ###### Timeseries #####
        # load Usage characteristics
        self.Usage = pd.read_csv("data/usage_profiles.csv", encoding="cp1252")

        # load climate data
        self.TA = np.genfromtxt("data/climate.csv", delimiter=";")[1:, 1]
        # load solar gains
        self.QS = np.genfromtxt("data/Solar_gains.csv")  # W/m²
示例#2
0
 def generatePVForBureauWithCoalitionMode(cls,
                                          real_result,
                                          coalition_mode,
                                          party_to_favorite='',
                                          coalition_group=[]):
     pv_list = []
     if coalition_mode == 0:
         for index, item in enumerate(real_result):
             pv = PV(PARTIES_LIST[index])
             pv.party_results = real_result
             pv_list.append(pv)
         return pv_list
     elif coalition_mode == 1:
         generate_pv = Fonction.generateRandomNumbersWithPref(
             len(PARTIES_LIST), sum(real_result), party_to_favorite)
         for index, item in enumerate(real_result):
             pv = PV(PARTIES_LIST[index])
             if index in coalition_group:
                 # pv.party_results = [(PARTIES_LIST[i], votes) for i, votes in
                 #                     enumerate(generatePV)]
                 pv.party_results = [votes for votes in generate_pv]
             else:
                 pv.party_results = real_result
             pv_list.append(pv)
         return pv_list
     else:
         for index, item in enumerate(real_result):
             pv = PV(PARTIES_LIST[index])
             pv.party_results = Fonction.generateRandomNumbersWithPref(
                 len(real_result), sum(real_result), index)
             pv_list.append(pv)
         return pv_list
示例#3
0
 def __init__(self, name, enrolled_persons):
     self.name = name
     self.enrolled_persons = enrolled_persons
     self.results = PV()
     '''ce sont les vrais resultats du bureau de vote. c'est la reference. c'est sous la forme (nomParti,voix)'''
     self.all_pv = []
     self.elecam_pv = PV()
示例#4
0
class Model:
    simulated = []  # this is not strictly neccessary

    # it uses a class variable to save
    # all simulated instances of a model
    # they get recorded at the end of the
    # Model.simulate() method

    def __init__(
            self,
            building_path="data/building_oib_16linie.xlsx",
            kWp=1,  # PV kWp
            battery_kWh=1):  # Battery kWh

        ###### Compononets #####
        # (Other classes and parts, that form the model)
        self.building = Building(path=building_path)
        self.HVAC = HVAC()

        self.PV = PV(csv="data/pv_1kWp.csv", kWp=1)
        self.PV.set_kWp(kWp)

        self.battery = Battery(kWh=battery_kWh)

        ###### Parameters #####
        self.cp_air = 0.34  # spez. Wärme kapazität Luft (Wh/m3K)

        self.price_grid = 0.19  # €/kWh
        self.price_feedin = 0.05  # €/kWh

        ###### Timeseries #####
        # load Usage characteristics
        self.Usage = pd.read_csv("data/usage_profiles.csv", encoding="cp1252")

        # load climate data
        self.TA = np.genfromtxt("data/climate.csv", delimiter=";")[1:, 1]
        # load solar gains
        self.QS = np.genfromtxt("data/Solar_gains.csv")  # W/m²

    def init_sim(self):
        # (re)load profiles from self.Usage
        #this is neccessary  if the PV model has changed inbetween simulations
        self.QI_winter = self.Usage["Qi Winter W/m²"].to_numpy()
        self.QI_summer = self.Usage["Qi Sommer W/m²"].to_numpy()

        self.ACH_V = self.Usage["Luftwechsel_Anlage_1_h"].to_numpy()
        self.ACH_I = self.Usage["Luftwechsel_Infiltration_1_h"].to_numpy()
        self.Qdhw = self.Usage["Warmwasserbedarf_W_m2"].to_numpy()
        self.ED_user = self.Usage["Nutzerstrom_W_m2"].to_numpy()

        # (re)load PV profiles
        #this is neccessary  if the PV model has changed inbetween simulations
        self.PV_prod = self.PV.TSD * 1000 / self.building.bgf  # everything is in Wh/m²
        self.PV_use = np.zeros(8760)
        self.PV_feedin = np.zeros(8760)
        self.PV_to_battery = np.zeros(8760)

        # initialize result arrays
        self.timestamp = pd.Series(
            np.arange('2020-01-01 00:00',
                      '2021-01-01 00:00',
                      dtype='datetime64[h]'))

        self.QV = np.zeros(8760)  # ventilation losses
        self.QT = np.zeros(8760)  # transmission losses
        self.QI = np.zeros(8760)  #  Internal losses
        self.Q_loss = np.zeros(8760)  # total losses without heating/cooling

        self.TI = np.zeros(8760)  # indoor temperature

        self.QH = np.zeros(8760)  # Heating demand Wh/m²
        self.QC = np.zeros(8760)  # Cooling demand Wh/m²

        # Energy demands
        self.ED_QH = np.zeros(8760)  # Electricity demand for heating Wh/m²
        self.ED_QC = np.zeros(8760)  # Electricity demand for cooling Wh/m²
        #self.ED_Qdhw = 0
        self.ED = np.zeros(8760)  # Electricity demand Wh/m²
        self.ED_grid = np.zeros(8760)

        self.Btt_to_ED = np.zeros(8760)

        ## initialize starting conditions
        self.TI[0] = self.HVAC.minimum_room_temperature

    def calc_QV(self, t):
        """Ventilation heat losses [W/m²BGF] at timestep t"""
        dT = self.TA[t - 1] - self.TI[t - 1]
        room_height = self.building.net_storey_height
        cp_air = self.cp_air
        # thermally effective air change
        eff_airchange = self.ACH_I[t] + self.ACH_V[
            t]  # * M.VentilationSystem.share_cs * rel_ACH_after_heat_recovery

        self.QV[t] = eff_airchange * room_height * cp_air * dT

    def calc_QT(self, t):
        """Transmission heat losses [W/m²BGF] at timestep t"""
        dT = self.TA[t - 1] - self.TI[t - 1]
        self.QT[t] = self.building.LT * dT

    def calc_QI(self, t):
        heat = self.timestamp[t].month in self.HVAC.heating_months
        cool = self.timestamp[t].month in self.HVAC.cooling_months
        if (heat and cool) or (
                not heat and
                not cool):  # wenn beides oder keinss von beiden, mittelwert
            self.QI[t] = (self.QI_winter[t] + self.QI_summer[t]) / 2
        elif heat:
            self.QI[t] = self.QI_winter[t]
        elif cool:
            self.QI[t] = self.QI_summer[t]
        else:
            raise NotImplementedError("Case not defined!")

    def handle_losses(self, t):
        # determine losses
        self.Q_loss[t] = (self.QT[t] + self.QV[t]) + self.QS[t] + self.QI[t]
        # determine indoor temperature after losses
        self.TI[t] = self.TI_after_Q(self.TI[t - 1], self.Q_loss[t],
                                     self.building.heat_capacity)

    def TI_after_Q(self, TI_before, Q, cp):
        """cp = spec. building heat_capacity"""
        return TI_before + Q / cp

    def is_heating_on(self, t, TI_new):
        if self.HVAC.heating_system == True:
            if self.timestamp[t].month in self.HVAC.heating_months:
                if TI_new < self.HVAC.minimum_room_temperature:
                    return True
        return False

    def is_cooling_on(self, t, TI_new):
        """
        Determines, whether all conditions are met to use cooling
        """
        c1 = self.HVAC.cooling_system == True
        c2 = self.timestamp[t].month in self.HVAC.cooling_months
        c3 = TI_new > self.HVAC.maximum_room_temperature
        return all(
            [c1, c2, c3]
        )  # returns True if all conditions are true, False otherwise. similarly, any(). You can stack this way more cleanly

    def minimum_Q(self, TI, set_min, set_max, cp):
        """calculates the minimum Q (positive or negative) to reach the setpoint targets"""
        if TI < set_min:
            return (set_min - TI) * cp
        if TI > set_max:
            return (set_max - TI) * cp
        else:
            return 0.

    def handle_heating(self, t):
        """Handles the use of a heating system, applies changes to self.QH, self.ED_QH, self.TI if neccessary"""
        TI = self.TI[t]
        if self.is_heating_on(t, TI):
            required_QH = self.minimum_Q(
                TI=TI,
                set_min=self.HVAC.minimum_room_temperature,
                set_max=self.HVAC.maximum_room_temperature,
                cp=self.building.heat_capacity)
            required_ED = required_QH / self.HVAC.HP_COP / self.HVAC.heating_eff
            available_power = self.HVAC.HP_heating_power
            self.ED_QH[t] = min(required_ED, available_power)
            self.QH[
                t] = self.ED_QH[t] * self.HVAC.HP_COP * self.HVAC.heating_eff
            self.TI[t] = self.TI_after_Q(TI, self.QH[t],
                                         self.building.heat_capacity)

    def handle_cooling(self, t):
        """Handles the use of a heating system, applies changes to self.QH, self.ED_QH, self.TI if neccessary"""
        TI = self.TI[t]
        if self.is_cooling_on(t, TI):
            required_QC = self.minimum_Q(
                TI=TI,
                set_min=self.HVAC.minimum_room_temperature,
                set_max=self.HVAC.maximum_room_temperature,
                cp=self.building.heat_capacity)
            required_ED = -required_QC / self.HVAC.HP_COP / self.HVAC.heating_eff
            available_power = self.HVAC.HP_heating_power
            self.ED_QC[t] = min(required_ED, available_power)
            self.QC[
                t] = -self.ED_QC[t] * self.HVAC.HP_COP * self.HVAC.heating_eff
            self.TI[t] = self.TI_after_Q(TI, self.QC[t],
                                         self.building.heat_capacity)

    def calc_ED(self, t):
        self.ED[t] = self.ED_QH[t] + self.ED_QC[t] + self.ED_user[t]

    def handle_PV(self, t):
        """allocates the PV to direct and  battery charge use"""
        #calculate the direct Use of PV
        self.PV_use[t] = min(self.PV_prod[t], self.ED[t])
        remain = self.PV_prod[t] - self.PV_use[t]

        #calculate the remaining PV to Battery
        self.PV_to_battery[t] = self.battery.charge(
            remain * self.building.bgf / 1000) * 1000 / self.building.bgf
        remain = remain - self.PV_to_battery[t]
        #calculate the remaining PV to Battery
        self.PV_feedin[t] = max(remain - self.ED[t], 0)

    def handle_grid(self, t):
        """calculate the remaining grid demand: Total Energy demand [ED] - PVuse - Battery_discharge"""
        self.ED_grid[t] = self.ED[t] - self.PV_use[t] - self.Btt_to_ED[t]

    def handle_battery(self, t):
        # Lower SoC by hourly losses
        self.battery.SoC = (1 - self.battery.discharge_per_hour) \
                           * self.battery.SoC

        # calculate remaining electricity demand not covered after PV use for time t
        remaining_ED = (self.ED[t] - self.PV_use[t]
                        ) * self.building.bgf / 1000  #kW not W/m²
        # conditions
        # if remaining energy demand > 0 AND battery.SoC > 0
        c1 = (remaining_ED > 0)
        c2 = (self.battery.SoC > 0)
        if all([c1, c2]):
            self.Btt_to_ED[t] = self.battery.discharge(remaining_ED)

    def calc_cost(self, years=20, verbose=True):
        """calculates the total cost of the system"""
        # calc investment
        self.investment_cost = self.building.differential_cost * self.building.bgf + self.PV.cost + self.battery.cost
        self.operational_cost = self.building.bgf * (
                                - self.PV_feedin.sum()/1000 * self.price_feedin \
                                + self.ED_grid.sum()/1000 * self.price_grid)

        self.total_cost = self.investment_cost + self.operational_cost * years

        if verbose:
            print(f"Investment cost:  {round(self.investment_cost):>20.2f} €")
            print(
                f"Operational cost: {round(self.operational_cost):>20.2f} €/annum"
            )
            print(
                f"Total cost after {years} years: {round(self.total_cost):>11,.2f} €"
            )

        return self.total_cost

    def simulate(self):

        self.init_sim()  # don't forget to intialize the first timestep = 0
        # with sensible starting values
        # like TI[0] = self.minimum_room_temperature

        for t in range(1, 8760):
            #### Verluste
            self.calc_QV(t)
            self.calc_QT(t)
            self.calc_QI(t)
            self.handle_losses(t)

            #### Heizung
            self.handle_heating(t)

            #### Kühlung
            self.handle_cooling(t)

            #calc total energy demand
            self.calc_ED(t)

            #allocate pv
            self.handle_PV(t)

            # discharge battery
            self.handle_battery(t)

            # handle grid
            self.handle_grid(t)

        self.calc_cost(verbose=False)

        Model.simulated.append(
            self)  # this adds the model result to the base class (optional)
        return True  # the simulate() method does not NEEd to return something
        # but it can be used to check if the simulation ran successfully

    def plot(self, show=True, start=1, end=8760, month=None):
        fig, ax = plt.subplots(2, 2)  #,figsize=(8,12)) #tight_layout=True)
        ax = ax.flatten()
        self.plot_heat_balance(fig, ax[0], start=start, end=end)
        self.plot_temperatures(fig, ax[1], start=start, end=end)
        self.plot_electricity_demand(fig, ax[2], start=start, end=end)
        self.plot_electricity_use(fig, ax=ax[3], start=start, end=end)

        if show:
            dummy = plt.figure()  # create a dummy figure
            new_manager = dummy.canvas.manager  # and use its manager to display "fig"
            new_manager.canvas.figure = fig
            fig.set_canvas(new_manager.canvas)
            fig.show()

    def plot_heat_balance(self,
                          fig=None,
                          ax=None,
                          start=1,
                          end=8760,
                          **kwargs):
        if (fig, ax) == (None, None):
            fig, ax = plt.subplots(1, 1)
        self.plot_arrays(
            ax=ax,
            start=start,
            end=end,
            arrays=[self.QT, self.QV, self.QS, self.QI, self.QH, self.QC],
            **kwargs)
        ax.legend([
            "Transmissionsverluste", "Lüftungsverluste", "Solare Gewinne",
            "Innere Lasten", "Heizwärmebdedarf", "Kühlbedarf"
        ])
        ax.set_title("Wärmebilanz")
        ax.set_ylabel("W/m²")
        plt.show()

    def plot_temperatures(self,
                          fig=None,
                          ax=None,
                          start=1,
                          end=8760,
                          **kwargs):
        if (fig, ax) == (None, None):
            fig, ax = plt.subplots(1, 1)
        self.plot_arrays(ax=ax,
                         start=start,
                         end=end,
                         arrays=[self.TI, self.TA],
                         **kwargs)
        ax.legend(["Innenraum", "Außenluft"])
        ax.set_title("Temperatur")
        ax.set_ylabel("Temperatur [°C]")
        plt.show()

    def plot_electricity_demand(self,
                                fig=None,
                                ax=None,
                                start=1,
                                end=8760,
                                **kwargs):
        # FigureCanvas(fig) # not needed in mpl >= 3.1
        if (fig, ax) == (None, None):
            fig, ax = plt.subplots(1, 1)
        self.plot_arrays(
            ax=ax,
            start=start,
            end=end,
            arrays=[self.PV_prod, self.ED_QH, self.ED_QC, self.ED_user],
            **kwargs)
        ax.set_title("Strom")
        ax.set_ylabel("W/m²")
        ax.legend(["PV", "WP Heizen", "WP Kühlen", "Nutzerstrom"])
        plt.show()

    def plot_electricity_use(self,
                             fig=None,
                             ax=None,
                             start=1,
                             end=8760,
                             **kwargs):
        """plots the electricity supply and use"""
        if (fig, ax) == (None, None):
            fig, ax = plt.subplots(1, 1)
        self.plot_arrays(ax=ax,
                         start=start,
                         end=end,
                         arrays=[
                             self.PV_use, self.Btt_to_ED, self.ED_grid,
                             self.PV_to_battery, self.PV_feedin
                         ],
                         **kwargs)
        ax.set_title("PV Nutzung")
        ax.set_ylabel("W/m²")
        ax.legend([
            'PV Eigenverbrauch', 'Batterie-Entladung', 'Netzstrom',
            'Batterie-Beladung', 'Einspeisung'
        ])
        plt.show()

    def plot_arrays(self, ax, start, end, arrays: list, **kwargs):
        for array in arrays:
            ax.plot(array[start:end], **kwargs)

    def __repr__(self):
        width = len(self.building.file)
        return f"""
示例#5
0
def index():
    try:
        tab = ['RDPC', 'MRC', 'SDF', 'FPD', 'ADD', 'UDC', 'UNIVERS', 'PURS', 'MCNC', 'ANDP', 'CPP', 'SCNC', 'MP']
        variable.PARTIES_LIST = tab[:int(request.args.get('number_party'))]
        print("Je récupère les partis ")
        print(variable.PARTIES_LIST)
        variable.BUREAU_VOTES_NUMBER = int(request.args.get('bureau_number'))
        variable.ENROLLED_PEOPLE_NUMBER = int(request.args.get('enrolled_number'))
        variable.COALITION_MODE = int(request.args.get('coalition_mode'))
    except Exception:
        return str(status.HTTP_400_BAD_REQUEST), "The data is not in the real format"
    try:
        import shutil
        if os.path.exists(os.path.join(os.path.dirname(__file__), 'PV_IMAGE')):
            shutil.rmtree(os.path.join(os.path.dirname(__file__), 'PV_IMAGE'))
            os.makedirs(os.path.join(os.path.dirname(__file__), 'PV_IMAGE'))
        if os.path.exists(os.path.join(os.path.dirname(__file__), 'PV_PDF')):
            shutil.rmtree(os.path.join(os.path.dirname(__file__), 'PV_PDF'))
            os.makedirs(os.path.join(os.path.dirname(__file__), 'PV_PDF'))

        

        import random

        from PV import PV
        from variable import BUREAU_VOTES_NUMBER, ENROLLED_PEOPLE_NUMBER, PARTIES_LIST, COALITION_MODE, getCoalitionName

        from BureauVote import BureauVote
        from Fonction import Fonction

        bureauVotes_List = []
        print(PARTIES_LIST)
        repartitions = Fonction.generateRandomNumbers(BUREAU_VOTES_NUMBER, ENROLLED_PEOPLE_NUMBER)

        # je dispatche les nombres d'inscrits entre les bureaux de vote
        for i in range(BUREAU_VOTES_NUMBER):
            bureauVotes_List.append(BureauVote('Bureau_de_Vote_' + str(i + 1), repartitions[i]))

        # j'enregistre les resultats reels de chaque parti dans chaque bureau de vote, (RDPC,nbreVotes)
        for bureau in bureauVotes_List:
            pv = PV("Reference")
            pv.party_results = Fonction.generateRandomNumbers(len(PARTIES_LIST), bureau.enrolled_persons)
            bureau.results = pv
            # bureau.results = [(PARTIES_LIST[i], votes) for i, votes in
            #                   enumerate(Fonction.generateRandomNumbers(len(PARTIES_LIST), bureau.enrolled_persons))]

        # c'est la partie ou on commence a generer les pv en fonction de la fraude

        # print(Fonction.generatePVForBureauWithCoalitionMode(bureauVotes_List[0].results, COALITION_MODE, 2, [0, 6, 2]))
        # Ici on genere tous les PV avec une eventuelle coalition
        number_of_coalised_party = random.randint(1, len(PARTIES_LIST) - 1)
        coalised_group = Fonction.generateTabRandomElementsDiff(number_of_coalised_party, len(PARTIES_LIST))
        party_favorite = random.choice(coalised_group)
        for bureau in bureauVotes_List:
            bureau.all_pv = Fonction.generatePVForBureauWithCoalitionMode(bureau.results.party_results, COALITION_MODE, party_favorite, coalised_group)
        for bureau in bureauVotes_List:
            t = random.choices([0, 1], [0.35, 0.65])[0]
            if t:
                pv = PV("Elecam")
                pv.party_results = Fonction.generateRandomNumbersWithPref(len(PARTIES_LIST), bureau.enrolled_persons, 0)
                bureau.elecam_pv = pv
            else:
                pv = PV("Elecam")
                pv.party_results = bureau.results.party_results
                bureau.elecam_pv = pv
        for bureau in bureauVotes_List:
            print(bureau)
            for item in bureau.all_pv:
                print(item)

        # Creation de tous les dossiers

        #import os

        for party in PARTIES_LIST:
            if not os.path.exists(os.path.join(os.path.dirname(__file__), 'PV_PDF', party)):
                os.makedirs(os.path.join(os.path.dirname(__file__), 'PV_PDF', party))

        if not os.path.exists(os.path.join(os.path.dirname(__file__), 'PV_PDF', 'REAL_RESULT')):
            os.makedirs(os.path.join(os.path.dirname(__file__), 'PV_PDF', 'REAL_RESULT'))

        if not os.path.exists(os.path.join(os.path.dirname(__file__), 'PV_PDF', 'ELECAM')):
            os.makedirs(os.path.join(os.path.dirname(__file__), 'PV_PDF', 'ELECAM'))

        # Generating PDF files
        from fpdf import FPDF

        width_cell, height_cell = 150, 40

        for bureau in bureauVotes_List:
            for PV in bureau.all_pv:
                pdf = FPDF(orientation='P', unit='pt', format='A4')
                pdf.add_page()
                pdf.set_font("Arial", size=16)
                pdf.multi_cell(0, 20, "PV_" + bureau.name, 0)
                pdf.set_top_margin(20)
                pdf.set_font("Arial", size=14)
                pdf.multi_cell(0, 20, "Nombre_de_Votants : " + str(bureau.enrolled_persons), 0)
                pdf.set_top_margin(20)
                pdf.multi_cell(0, 20, "Type_de_Coalition : " + str(getCoalitionName(COALITION_MODE)), 0)
                pdf.set_top_margin(20)
                pdf.set_fill_color(193, 229, 252)
                pdf.cell(width_cell, height_cell, 'Nom_du_Parti', 1, 0, 'C', 1)
                pdf.cell(width_cell, height_cell, 'Nombre_de_Voix', 1, 1, 'C', 1)
                for index, votes in enumerate(PV.party_results):
                    pdf.set_font("Arial", size=14)
                    pdf.cell(width_cell, height_cell, str(PARTIES_LIST[index]), 1, 0, 'L', 0)
                    pdf.set_font("Arial", size=14)
                    pdf.cell(width_cell, height_cell, str(votes), 1, 1, 'L', 0)
                pdf.set_font("Arial", size=14)
                pdf.multi_cell(0, 20, "", 0)
                pdf.set_top_margin(20)
                pdf.set_fill_color(193, 229, 252)
                pdf.cell(width_cell, height_cell, 'Nom_du_Representant', 1, 0, 'C', 1)
                pdf.cell(2 * width_cell, height_cell, 'Signatures', 1, 1, 'C', 1)
                for index, votes in enumerate(PV.party_results):
                    pdf.set_font("Arial", size=14)
                    pdf.cell(width_cell, height_cell, str(PARTIES_LIST[index]), 1, 0, 'L', 0)
                    pdf.set_font("Arial", size=12)
                    pdf.cell(2 * width_cell, height_cell,
                            "Scrutateur_" + str(PARTIES_LIST[index]) + "_" + str(bureau.name), 1, 1, 'L', 0)

                pdf.output('PV_PDF/' + str(PV.party_name) + '/PV_' + str(bureau.name) + '.pdf')

            # pour mettre les PV d'elecam
            pdf = FPDF(orientation='P', unit='pt', format='A4')
            pdf.add_page()
            pdf.set_font("Arial", size=16)
            pdf.multi_cell(0, 20, "PV_ELECAM_" + bureau.name, 0)
            pdf.set_top_margin(20)
            pdf.set_font("Arial", size=14)
            pdf.multi_cell(0, 20, "Nombre_de_Votants : " + str(bureau.enrolled_persons), 0)
            pdf.set_top_margin(20)
            pdf.multi_cell(0, 20, "Type_de_Coalition : " + str(getCoalitionName(COALITION_MODE)), 0)
            pdf.set_top_margin(20)
            pdf.set_fill_color(193, 229, 252)
            pdf.cell(width_cell, height_cell, 'Nom_du_Parti', 1, 0, 'C', 1)
            pdf.cell(width_cell, height_cell, 'Nombre_de_Voix', 1, 1, 'C', 1)
            for index, votes in enumerate(bureau.elecam_pv.party_results):
                pdf.set_font("Arial", size=14)
                pdf.cell(width_cell, height_cell, str(PARTIES_LIST[index]), 1, 0, 'L', 0)
                pdf.set_font("Arial", size=14)
                pdf.cell(width_cell, height_cell, str(votes), 1, 1, 'L', 0)
            pdf.set_font("Arial", size=14)
            pdf.multi_cell(0, 20, "", 0)
            pdf.set_top_margin(20)
            pdf.set_fill_color(193, 229, 252)
            pdf.cell(width_cell, height_cell, 'Nom_du_Representant', 1, 0, 'C', 1)
            pdf.cell(2 * width_cell, height_cell, 'Signatures', 1, 1, 'C', 1)
            for index, votes in enumerate(bureau.elecam_pv.party_results):
                pdf.set_font("Arial", size=14)
                pdf.cell(width_cell, height_cell, str(PARTIES_LIST[index]), 1, 0, 'L', 0)
                pdf.set_font("Arial", size=12)
                pdf.cell(2 * width_cell, height_cell,
                        "Scrutateur_" + str(PARTIES_LIST[index]) + "_" + str(bureau.name), 1, 1, 'L', 0)

            pdf.output('PV_PDF/ELECAM/PV_Elecam_' + str(bureau.name) + '.pdf')

            # pour mettre les PV de reference
            pdf = FPDF(orientation='P', unit='pt', format='A4')
            pdf.add_page()
            pdf.set_font("Arial", size=16)
            pdf.multi_cell(0, 20, "PV_GAGNANT_" + bureau.name, 0)
            pdf.set_top_margin(20)
            pdf.set_font("Arial", size=14)
            pdf.multi_cell(0, 20, "Nombre_de_Votants : " + str(bureau.enrolled_persons), 0)
            pdf.set_top_margin(20)
            pdf.multi_cell(0, 20, "Type_de_Coalition : " + str(getCoalitionName(COALITION_MODE)), 0)
            pdf.set_top_margin(20)
            pdf.set_fill_color(193, 229, 252)
            pdf.cell(width_cell, height_cell, 'Nom_du_Parti', 1, 0, 'C', 1)
            pdf.cell(width_cell, height_cell, 'Nombre_de_Voix', 1, 1, 'C', 1)
            for index, votes in enumerate(bureau.results.party_results):
                pdf.set_font("Arial", size=14)
                pdf.cell(width_cell, height_cell, str(PARTIES_LIST[index]), 1, 0, 'L', 0)
                pdf.set_font("Arial", size=14)
                pdf.cell(width_cell, height_cell, str(votes), 1, 1, 'L', 0)
            pdf.set_font("Arial", size=14)
            pdf.multi_cell(0, 20, "", 0)
            pdf.set_top_margin(20)
            pdf.set_fill_color(193, 229, 252)
            pdf.cell(width_cell, height_cell, 'Nom_du_Representant', 1, 0, 'C', 1)
            pdf.cell(2 * width_cell, height_cell, 'Signatures', 1, 1, 'C', 1)
            for index, votes in enumerate(bureau.results.party_results):
                pdf.set_font("Arial", size=14)
                pdf.cell(width_cell, height_cell, str(PARTIES_LIST[index]), 1, 0, 'L', 0)
                pdf.set_font("Arial", size=12)
                pdf.cell(2 * width_cell, height_cell,
                        "Scrutateur_" + str(PARTIES_LIST[index]) + "_" + str(bureau.name), 1, 1, 'L', 0)

            pdf.output('PV_PDF/REAL_RESULT/PV_Gagnant_' + str(bureau.name) + '.pdf')




        #import os
        from pdf2jpg import pdf2jpg

        from variable import PARTIES_LIST

        #import shutil
        if os.path.exists(os.path.join(os.path.dirname(__file__), 'PV_IMAGE')):
            shutil.rmtree(os.path.join(os.path.dirname(__file__), 'PV_IMAGE'))


        for party in PARTIES_LIST:
            if not os.path.exists(os.path.join(os.path.dirname(__file__), 'PV_IMAGE', party)):
                os.makedirs(os.path.join(os.path.dirname(__file__), 'PV_IMAGE', party))

        if not os.path.exists(os.path.join(os.path.dirname(__file__), 'PV_IMAGE', 'REAL_RESULT')):
            os.makedirs(os.path.join(os.path.dirname(__file__), 'PV_IMAGE', 'REAL_RESULT'))

        if not os.path.exists(os.path.join(os.path.dirname(__file__), 'PV_IMAGE', 'ELECAM')):
            os.makedirs(os.path.join(os.path.dirname(__file__), 'PV_IMAGE', 'ELECAM'))

        for folder in os.listdir(os.path.join(os.path.dirname(__file__), 'PV_PDF')):
            for file in os.listdir(os.path.join(os.path.dirname(__file__), 'PV_PDF', folder)):
                # pages = convert_from_path(os.path.join(os.path.dirname(__file__), 'PV_PDF', folder, file), 500)
                # pages[0].save(os.path.join(os.path.dirname(__file__), 'PV_IMAGE', folder, file), 'JPEG')
                result = pdf2jpg.convert_pdf2jpg(os.path.join(os.path.dirname(__file__), 'PV_PDF', folder, file),
                                                os.path.join(os.path.dirname(__file__), 'PV_IMAGE', folder), pages="0")
                print(result)

        print('Delete that folders')

        #import shutil

        for folder in os.listdir(os.path.join(os.path.dirname(__file__), 'PV_IMAGE')):
            for small_folders in os.listdir(os.path.join(os.path.dirname(__file__), 'PV_IMAGE', folder)):
                file = os.listdir(os.path.join(os.path.dirname(__file__), 'PV_IMAGE', folder, small_folders))[0]
                tab = file.split('.')
                new_file_name = tab[0][2:] + '.' + tab[-1]
                shutil.move(os.path.join(os.path.dirname(__file__), 'PV_IMAGE', folder, small_folders, file),
                            os.path.join(os.path.dirname(__file__), 'PV_IMAGE', folder, new_file_name))
                os.rmdir(os.path.join(os.path.dirname(__file__), 'PV_IMAGE', folder, small_folders))

        


        import json
        #import os

        import requests
        from PIL import Image
        from pytesseract import image_to_string

        from variable import PARTIES_LIST


        def removeNumbers(string_numbers):
            for i, el in enumerate(string_numbers):
                if not string_numbers[-int(i) - 1].isdigit():
                    return string_numbers[-int(i - 1) - 1:]
                    break
            return string_numbers


        with open('results.json', 'w+') as f:
            f.write('[')
            for bureau_index, folder in enumerate(os.listdir(os.path.join(os.path.dirname(__file__), 'PV_IMAGE'))):
                for pv_index, image in enumerate(os.listdir(os.path.join(os.path.dirname(__file__), 'PV_IMAGE', folder))):
                    img = [str(elt) for elt in
                        image_to_string(
                            Image.open(os.path.join(os.path.dirname(__file__), 'PV_IMAGE', folder, image))).split(
                            '\n') if not elt.replace(" ", "") == ""]
                    bureau_de_Vote = img[0].replace("O", '0').replace('I', '1').replace(" ", "").split("_")[-1]
                    enrolled_number = img[1].split(':')[-1].replace("I", "1").replace(" ", "")
                    #print(bureau_de_Vote)
                    #print(enrolled_number)
                    #print(img)
                    #print(folder + image)
                    party = [int(removeNumbers(elt.replace(" ", "").replace("|", "1").replace("O", "0"))) for elt in
                            img[4:len(PARTIES_LIST) + 4]]
                    #print(party)
                    global_id = 11 * bureau_index + pv_index
                    #print(folder)
                    if folder == "ELECAM":
                        real_id, party_name = "elecam", -1
                    elif folder == "REAL_RESULT":
                        real_id, party_name = "bon", -2
                    else:
                        real_id, party_name = global_id, PARTIES_LIST.index(folder)

                    scrutateur_format = dict(scrutineerId=global_id, scrutineerName=real_id, partyNumber=party_name)
                    pv_format = dict(pvId=global_id, pollingStation=removeNumbers(bureau_de_Vote), numberOfSuscribers=enrolled_number,
                                    numberOfVoters=enrolled_number, voices=party, partyNumber=party_name,
                                    scrutineer="resource:org.cloud.elections.Scrutineer#{}".format(global_id), scrutineerName=real_id)
                    data_format = dict(id=global_id, bureau=bureau_de_Vote, nbreInscrits=enrolled_number,
                                    nbreVotants=enrolled_number,
                                    voix=party, idScrutateur=global_id,
                                    nomScrutateur=real_id, parti=party_name)
                    json.dump(data_format, f)
                    f.write(',')
                    r = requests.post('http://localhost:3000/api/Scrutineer', json=scrutateur_format)
                    r = requests.post('http://localhost:3000/api/Pv', json=pv_format)

            f.write(']')


        
        #print(variable.PARTIES_LIST)
        #print(variable.BUREAU_VOTES_NUMBER)
        #print(variable.ENROLLED_PEOPLE_NUMBER)
        #print(variable.COALITION_MODE)
        return str(status.HTTP_200_OK)
    except Exception as e:
        return str(status.HTTP_400_BAD_REQUEST), str(e)
示例#6
0
from BureauVote import BureauVote
from Fonction import Fonction

bureauVotes_List, results = [], []
repartitions = Fonction.generateRandomNumbers(BUREAU_VOTES_NUMBER,
                                              ENROLLED_PEOPLE_NUMBER)

# je dispatche les nombres d'inscrits entre les bureaux de vote
for i in range(BUREAU_VOTES_NUMBER):
    bureauVotes_List.append(
        BureauVote('Bureau_de_Vote_' + str(i + 1), repartitions[i]))

# j'enregistre les resultats reels de chaque parti dans chaque bureau de vote, (RDPC,nbreVotes)
for bureau in bureauVotes_List:
    pv = PV("Reference")
    pv.party_results = Fonction.generateRandomNumbers(len(PARTIES_LIST),
                                                      bureau.enrolled_persons)
    bureau.results = pv
    # bureau.results = [(PARTIES_LIST[i], votes) for i, votes in
    #                   enumerate(Fonction.generateRandomNumbers(len(PARTIES_LIST), bureau.enrolled_persons))]

# c'est la partie ou on commence a generer les pv en fonction de la fraude

# print(Fonction.generatePVForBureauWithCoalitionMode(bureauVotes_List[0].results, COALITION_MODE, 2, [0, 6, 2]))
# Ici on genere tous les PV avec une eventuelle coalition
number_of_coalised_party = random.randint(1, len(PARTIES_LIST) - 1)
coalised_group = Fonction.generateTabRandomElementsDiff(
    number_of_coalised_party, len(PARTIES_LIST))
party_favorite = random.choice(coalised_group)
print('il ya coalition ' + str(COALITION_MODE))