miércoles, 27 de marzo de 2019

Clase Generador Congruencial Lineal en Python

Clase Generador Congruencial Lineal en Python

Hola acá les muestro un Generador congruencial Lineal escrito en python, este generador puede calcular automáticamente NORM, SUM y MULT dependiendo del numero de iteraciones con el menor desperdicio de semillas así como también es posible inicializar dicho generador con solo llamar una función o hacerlo individualmente con cada variable de este.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from generator import Generator

def main():

    gen = Generator()
    gen.P = 0.3 #probabilidad de exito
    gen.initGenerator(1000)
    pass

if __name__ == '__main__':
    main()



  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
#!/usr/bin/python3
# -*- coding: <utf-8> -*-
# 

from random import random, seed,randint
from decimal import *
from os import name
from subprocess import call

class Generator(object):
    """docstring for Generator"""
    """CONSTRUCTOR DEL GENERADOR CON VALORES POR DEFECTO DE VARIABLES"""
    def __init__(self, P = 0, MULT = 0, NORM = 16384, SUM = 0, NUM_SIMULATION = 10000, BASE_NORM = 2):
        super(Generator).__init__()
        self.P = P
        self.Q = 0
        self.MULT = MULT
        self.SUM = SUM
        self.NORM = NORM
        self.NUM_SIMULATION = NUM_SIMULATION
        self.BASE_NORM= BASE_NORM

#GETTERS Y SETTERS DE VARIABLES"""
    @property
    def P(self) -> float:
        return self.__P
    
    @P.setter
    def P(self,value: float):
        self.__P = value
        pass

    @property
    def Q(self) -> float:
        return self.__Q
    
    @Q.setter
    def Q(self,value: float):
        self.__Q = value
        pass

    @property
    def MULT(self) -> int:
        return self.__MULT
    
    @MULT.setter
    def MULT(self,value: int):
        self.__MULT = value
        pass

    @property
    def SUM(self) -> int:
        return self.__SUM
    
    @SUM.setter
    def SUM(self,value: int):
        self.__SUM = value
        pass

    @property
    def NORM(self) -> int:
        return self.__NORM
    
    @NORM.setter
    def NORM(self,value: int):
        self.__NORM = value
        pass

    @property
    def BASE_NORM(self) -> int:
        return self.__BASE_NORM
    
    @BASE_NORM.setter
    def BASE_NORM(self,value: int):
        self.__BASE_NORM = value
        pass

    @property
    def NUM_SIMULATION(self) -> int:
        return self.__NUM_SIMULATION
    
    @NUM_SIMULATION.setter
    def NUM_SIMULATION(self,value: int):
        self.__NUM_SIMULATION = value
        pass
    #FUNCION CON LA QUE OBTENEMOS EL ULTIMO DIGITO DE UN NUMERO X"""
    def __getLastDigit(self,num: int) -> int:
        num = int(num)
        return num%10
        pass
#FUNCION QUE CALCULA EL VALOR DE LA CONSTANTE SUM"""
    def calculateSUM(self, num: int) -> int:
        num = int(num)
        if self.BASE_NORM == 10:
            digit = self.__getLastDigit(num)
            if digit == 1 or digit == 3 or digit == 7 or digit == 9 :
                return num
                pass
            return self.calculateSUM(num+1)
            pass
        return num if num%2 == 1 else num+1
        pass

#FUNCION QUE CALCULA EL VALOR DE LA CONSTANTE MULT"""
    def calculateMULT(self, num) -> int:
        num = int(num)
        if self.BASE_NORM == 10:
            if (num-1)%20 == 0:
                return num
                pass
            return self.calculateMULT(num+1)
            pass
        elif (num-1)%4 == 0:
            return num
            pass
        return self.calculateMULT(num+1)
        pass

#FUNCION QUE CALCULA EL VALOR DE LA CONSTANTE NOMR
#A PARTIR DE EL NUMERO DE ITERACIONES A REALIZAR SE CALCULA EL MEJOR NORMALIZADOR CON EL MENOR NUMERO DE SEMILLAS DESPERDICIADAS
#POR LO CUAL SE CALCULARA UN NUMERO CON BASE 10 Y OTRO CON BASE 2 Y SE ELEGIRA EL MEJOR DE ELLOS 

    def calculateNORM(self,num) -> int:
        baseA = self.__multiple(num,10) - num
        baseB = self.__multiple(num,2) - num
        temp = min(baseA,baseB)
        if temp == baseA:
            self.BASE_NORM=10
            pass
        else:
            self.BASE_NORM=2
        return temp + num
        pass

#FUNCION QUE INICIALIZA LAS CONSTANSTES DEL GENERADOR A PARTIR DEL NUMERO DE ITERACIONES A REALIZAR"""
    def initGenerator(self,num = 0):
        # self.clear()
        if num == 0:
            num = self.NUM_SIMULATION
            print('Usando {} iteraciones para inicializar el generador mixto'.format(self.NUM_SIMULATION))
            pass
        self.NORM = self.calculateNORM(num)
        self.SUM = self.calculateSUM((randint(1,int(self.NORM))))
        self.MULT = self.calculateMULT((randint(1,int(self.NORM))))
        self.NUM_SIMULATION = num
        print(self)
        pass

#FUNCION QUE CALCULA EL MULTIPLO DE UN NUMERO """
    def __multiple(self,num,base):
        temp=0
        i=1
        while(temp<num):
            temp= pow(base,i)
            i+=1
        return temp
        pass

#FUNCION DEL GENERADOR MIXTO"""
    def mixed_rand(self,SEM: int) -> int:
        return ((int(self.MULT)*int(SEM))+int(self.SUM))%int(self.NORM)
        pass

#FUNCION PARA MOSTRAR LOS VALORES DE LAS VARIABLES DEL GENRADOR"""
    def __str__(self):
        return "DATOS INICIALES [\n\tSUM = {}, \n\tMULT = {}, \n\tNORM = {}, \n\tNUMERO DE ENSAYOS = {}, \n\tBASE DEL NORMALIZADOR = {}, \n\tPROBABILIDAD DE EXITO = {}, \n\tPROBABILIDAD DE FRACASO = {} \n]".format(self.SUM,self.MULT,self.NORM,self.NUM_SIMULATION,self.BASE_NORM,self.P,self.Q)

#FUNCION UTILIZADA PARA FORMATEAR UNA LISTA DE NUMEROS EN COLUMNAS DE X ELEMENTOS POR DEFECTO USA 10 COLUMNAS"""
    def chunks(self,l, n = 10):
        # For item i in a range that is a length of l,
        for i in range(0, len(l), n):
            # Create an index range for l of n items:
            yield l[i:i+n]

#FUNCION UTILIZADA PARA FORMATEAR UNA LISTA DE NUMEROS EN FORMATO DE TABLA TABULADA"""
    # Pretty Print table in tabular format
    def prettyprint(self,table, justify = "R", columnWidth = 0):
        # Not enforced but
        # if provided columnWidth must be greater than max column width in table!
        if columnWidth == 0:
            # find max column width
            for row in table:
                for col in row:
                    width = len(str(col))
                    if width > columnWidth:
                        columnWidth = width

        outputStr = ""
        for row in table:
            rowList = []
            for col in row:
                if justify == "R": # justify right
                    rowList.append(str(col).rjust(columnWidth))
                elif justify == "L": # justify left
                    rowList.append(str(col).ljust(columnWidth))
                elif justify == "C": # justify center
                    rowList.append(str(col).center(columnWidth))
            outputStr += ' '.join(rowList) + "\n"
        return outputStr
#FUNCION UTILIZADA PARA ENCAPSULAR EL USO DE CHUNKS Y PRETTYPRINT """
    def print_in_columns(self, lst ,n = 20):
        print(self.prettyprint(list(self.chunks(lst,n)),"L"))
        pass
#FUNCION PARA LIMPIAR PANTALLA"""
    def clear(self):
        # check and make call for specific operating system
        _ = call('clear' if name =='posix' else 'cls')
        pass