def generatePayee(length, plainOutput=False):
    # Usage
    # print generatePayee(5)
    if plainOutput:
        return RandomGenerator.randomName(length)
    else:
        return 'Payee: ' + RandomGenerator.randomName(length)
Exemplo n.º 2
0
 def refresh(self, random_seed=None):
     if random_seed != None:
         self.random_seed = random_seed
     RandomGenerator.set_seed(self.random_seed)
     self.my_table = RandomGenerator.random_generator.rand(
         self.dim_1, self.dim_2,
         self.dim_3)  #Mersenne Twister Random Generator
def generateAmount(numOfDigits=3, plainOutput=False):
    # Usage
    # print generateAmount(3)
    if plainOutput:
        return str(RandomGenerator.randomIntegerNDigits(numOfDigits))
    return 'Amount: ' \
        + str(RandomGenerator.randomIntegerNDigits(numOfDigits)) \
        + ' Satoshi'
Exemplo n.º 4
0
 def __init__(self,influence_matrix,random_seed=0):
     # CONSTRUCTOR
     self.random_seed = random_seed
     RandomGenerator.set_seed(random_seed)
     self.influence_matrix = influence_matrix
     self.dim_1 = self.influence_matrix.my_N
     self.dim_2 = 2
     self.dim_3 = 1 << self.influence_matrix.my_K # i.e., power of 2 by K
     self.my_table = RandomGenerator.random_generator.rand(self.dim_1,self.dim_2,self.dim_3) #Mersenne Twister Random Generator
Exemplo n.º 5
0
def handle_dis_kon():
    clear()
    print("------------------------------------")
    print(" Verteilung des Kongruenzgenerators")
    print("------------------------------------")
    print()
    print("Wählen Sie 1, um die Ergebnisse der Seminararbeit zu erhalten.")
    print("Wählen sie 2, um eigene Ergebnisse zu erhalten")
    print()
    user_input = input("Antwort: ")

    if user_input == "1":
        clear()
        print("Sie haben Option 1 gewählt.")
        try:
            RandomGenerator.main(10061, 1, 2**16, 54, 1000000, 10)
        except Exception as e:
            print(e)

    if user_input == "2":
        """
        (a, c, m, x, n, length)
        """
        clear()
        print("Sie haben Option 2 gewählt.")
        try:
            a = int(input("a = "))
            c = int(input("c = "))
            m = int(input("m = "))
            x = int(input("x = "))
            n = int(input("n = "))
            length = int(input("Intervall bis (einschließlich) = "))

            RandomGenerator.main(a, c, m, x, n, length)

        except Exception as e:
            clear()
            print(e)
            print("Scheinbar haben Sie einen unzulässigen Wert eingetipp!")
            sleep(2)
            return handle_dis_kon()

    if user_input == "":
        clear()
        return main()

    user_input = input()

    if user_input == "":
        clear()
        return main()
Exemplo n.º 6
0
def GenerateSudoku():
    """
    Generates a full Sudoku with all numbers

    Returns:
    3D-Array 

    """
    succesfull = 0
    countTries = 0

    while succesfull < 1:
        Sudoku = ArrayTools.nullBased2DArray(9)
                
        for x in range (0,9):
            for y in range(0,9):
                cands = CandidateChecker.getCandidates(Sudoku, x, y)

                #Check if there are no more candidates
                if(len(cands) == 0):
                    succesfull = -1
                    countTries = countTries + 1
                    break
                else:
                    Sudoku[x][y] = RandomGenerator.GenerateRandom(cands)

                #Check if succesfull
                if((x == 8) & (y == 8)):
                    succesfull = 1
                    print("Generation succesfull with " + str(countTries) + " Tries!")
            if(succesfull == -1 | succesfull == 1):
                break
    return Sudoku
Exemplo n.º 7
0
def handle_kon_test():
    clear()
    print("------------------------------------------------")
    print(" Sequenz mit einen Kongruenzgenerator erstellen")
    print("------------------------------------------------")
    print()
    print(
        "Wählen sie die 1, um die Zufallssequenz der Verteilung aus der Seminararbeit zu erhalten."
    )
    print("Wählen sie die 2, um eigene Reihen zu erstellen.")

    user_input = input("Antwort: ")

    if user_input == "1":
        clear()
        print("Sie haben Option 1 gewählt.")
        print()
        RandomGenerator.main2(10061, 1, 2**16, 54, 1000000, 0, 9)

    if user_input == "2":
        clear()
        print("Sie haben Option 2 gewählt.")
        print()
        try:
            a = int(input("a = "))
            c = int(input("c = "))
            m = int(input("m = "))
            x = int(input("x = "))
            n = int(input("Länge der Sequenz = "))
            start = int(input("Startwert: "))
            end = int(input("Endwert: "))
            RandomGenerator.main2(a, c, m, x, n, start, end)

        except Exception as e:
            print(e)
            print("Ups! Sie haben wohl einen unzulässigen Wert eingegeben!")
            return handle_kon_test()

    if user_input == "":
        clear()
        return main()

    user_input = input()

    if user_input == "":
        clear()
        return main()
Exemplo n.º 8
0
    def clear(self):
        Board.board = [[0]*self.width for i in range(self.height)]
        Board.active = None
        Board.stored = None
        Board.gameOver = False
        Board.fall_rate = 2
        Board.lines_total = 0
        Board.level = 1
        Board.next_level = 5
        
        Board.combo_length = 0
        Board.points = 0

        RandomGenerator.reseed()
        self.next_pieces.clear()
        for i in range(7):
            self.next_pieces.append(RandomGenerator.get_next())
Exemplo n.º 9
0
    def __init__(self, width, height):
        Board.board = [[0]*width for i in range(height)]
        self.width = width
        self.height = height
        for i in range(7):
            self.next_pieces.append(RandomGenerator.get_next())

        self.opacity_screen10 = pygame.Surface(((width)*BLOCKSIZE, (height)*BLOCKSIZE), pygame.SRCALPHA)
        self.opacity_screen10.fill((0,0,0,40))
Exemplo n.º 10
0
 def export_record(self, file_name):
     #standardized values
     land = self.agent_clan.landscape
     for sr in self.simulation_record:
         sr.performance = land.get_standardized_value(sr.performance)
     #for plot
     simple_simulation_record = [(sr.ct, sr.performance)
                                 for sr in self.simulation_record]
     nrow = len(simple_simulation_record)
     ncol = 2
     a = np.zeros(nrow * ncol, dtype='f').reshape(nrow, ncol)
     for k, l in enumerate(simple_simulation_record):
         a[k, 0] = l[0]
         a[k, 1] = l[1]
     file_name_plot = "%s_spreadsheet_plot.txt" % file_name
     np.savetxt(file_name_plot, a, fmt=['%d', '%.4f'], delimiter=',')
     #for record
     file_name_record = "%s_record.gz" % file_name
     f_record = gzip.open(file_name_record, 'wb')
     writer = csv.writer(f_record, lineterminator='\n', delimiter='\t')
     writer.writerow(['location_id', 'tick', 'plan', 'fitness'])
     for sr in self.simulation_record:
         writer.writerow([sr.location_id, sr.ct, sr.plan, sr.performance])
     f_record.close()
     #for profile
     plan_profile = self.adapter_plan_profile
     clan_profile = self.agent_clan.__str__()
     behavior_profile = self.adapter_behavior_profile
     time_stamp = time.ctime()
     file_name_profile = "%s_profile.txt" % file_name
     f_profile = open(file_name_profile, 'wb')
     f_profile.write("=========================================\n")
     f_profile.write("NK Landscape Simuation\n")
     f_profile.write("=========================================\n")
     f_profile.write("\nRandom seed:%d\n" %
                     RandomGenerator.get_current_seed())
     f_profile.write("\n%s\n" % time_stamp)
     f_profile.write("\n%s\n" % plan_profile)
     f_profile.write("\n%s\n" % clan_profile)
     f_profile.write("\n%s\n" % behavior_profile)
     f_profile.close()
Exemplo n.º 11
0
 def create(self):
     self.next_pieces.append(RandomGenerator.get_next())
     Board.active = Tetromino(3, 0, self.next_pieces.popleft())
     self.shadowUpdate()
Exemplo n.º 12
0
    M = M / M.sum(0)
    M = M / M.sum(0)
    err = np.inf
    for p in perm:
        wM = M[:, list(p)]
        werr = np.linalg.norm(wM - true_M, 2)
        if werr < err:
            err = werr
    return err


for i in range(L):
    nn = 0
    for N in wN:
        # Generate Data
        X, M, omega, x = rg.generate_sample_SingleTopic(N, n, k, 20)
        wM2, wM3 = sm.RecoverMoments(omega, M)
        NSteps.append(N)

        # Retrieve empirical tensors
        print('.............Getting matrices')
        M1, M2, M3 = sm.RetrieveTensorsST(X)

        print('.............SVTD is working')
        t0 = time.time()
        # Parameters Learning
        MSVTD, omegaSVTD = sm.learn_LVM_Core(M1, M2, M3, k)
        TimeSVTD[i, nn] = time.time() - t0
        CL = sm.AssignClustersSingleTopic(MSVTD, omegaSVTD, X)
        #Calculates clustering accuracy and learning error
        CLAccuracySVTD[i, nn] = adjusted_rand_score(x, CL)
import matplotlib.pyplot as plt
from matplotlib import colors
import RandomGenerator as Rndm

##! Start:
print("========  RandomGenerator: tests start  ========")

##! Test singleton class feature:
RandomGeneratorTest = 1
print()
print("RandomGeneratorTest:", RandomGeneratorTest,
      " check if class is a singleton.")
nuSIMPATH = os.getenv('nuSIMPATH')
rootfilename = os.path.join(nuSIMPATH, 'Scratch/plots_endProdStrght.root')
print(rootfilename)
RndmGen = Rndm.RandomGenerator(rootfilename, 'histP', 'histXPS')
RndmGen1 = Rndm.RandomGenerator(rootfilename, 'histP', 'histXPS')
print("---->RndmGen singleton test:", id(RndmGen), id(RndmGen1),
      id(RndmGen) - id(RndmGen1))
if RndmGen != RndmGen1:
    raise Exception("RandomGenerator is not a singleton class!")

##! Check get methods:
RandomGeneratorTest = 2
print()
print("RandomGeneratorTest:", RandomGeneratorTest, " check get methods.")
print("    RandomGenerator: version:", RndmGen.CdVrsn())

x = np.array([])
y = np.array([])
xp = np.array([])
Exemplo n.º 14
0
def generateNonce(plainOutput=False):
    if plainOutput:
        return str(RandomGenerator.randomIntegerNbit(128))
    return 'Nonce: ' + str(RandomGenerator.randomIntegerNbit(128))
Exemplo n.º 15
0
def SimulatedAnnealing( Method, Task, **kwargs ):


    global Function_Name, Ndim, Minimum, NS, NT, MaxEvl, \
        EPS, RT, Temperature, LowerBounds, UpperBounds, \
        VM, C, Debugging

    IO.OutPut( Task, Method )

    IO.SA_GlobalVariables()

    X_Optimum = [] ; F_Optimum = [] ; TestSolution = []

    ntests = 0
    if( Task == 'Benchmarks' ):
        ntests = IO.CheckNumberTests()
        SA_Function, SA_Minimum, SA_N, SA_NS, SA_NT, SA_MaxEvl, SA_EPS, SA_RT, SA_Temp, \
            SA_LowerBounds, SA_UpperBounds, SA_VM, SA_C, SA_Debugging, SA_Xopt, \
            SA_Fopt = IO.ReadInCoolingSchedule( No_Tests = ntests )

    elif( Task == 'Problem' ):
        if kwargs: # For Problems
            for key in kwargs:
                if ( key == 'FileName' ): 
                    Problem_FileName = kwargs[ key ]

            #IO.ReadInCoolingSchedule( File_Name = Problem_FileName )
            rub1 = [], rub2 = []
            SA_Function, SA_Minimum, SA_N, SA_NS, SA_NT, SA_MaxEvl, SA_EPS, SA_RT, SA_Temp, \
                SA_LowerBounds, SA_UpperBounds, SA_VM, SA_C, SA_Debugging, rub1, \
                rub2 =  IO.ReadInCoolingSchedule( File_Name = Problem_FileName )
            ntests = 0

        else: 
            sys.exit( 'Option not found' )

    else:
        sys.exit( 'Option not found' )


    """ Calling main SA loop: """


    for itest in range( ntests ):

        Function_Name = SA_Function[ itest ]
        Ndim = SA_N[ itest ]
        Minimum = SA_Minimum[ itest ]
        NS = SA_NS[ itest ]
        NT = SA_NT[ itest ]
        MaxEvl = SA_MaxEvl[ itest ]
        EPS = SA_EPS[ itest ]
        RT = SA_RT[ itest ]
        Temperature = SA_Temp[ itest ]
        LowerBounds = SA_LowerBounds[ itest ]
        UpperBounds = SA_UpperBounds[ itest ]
        VM = SA_VM[ itest ]
        C = SA_C[ itest ]
        Debugging = SA_Debugging[ itest ]

        if( Task == 'Benchmarks' ):
            XSolution = SA_Xopt[ itest ]
            FSolution = SA_Fopt[ itest ]

        

        """ Initial guess-solution obtained randomly """
        X_Guess = []
        X_Guess = RanGen.RandomNumberGenerator( Ndim, LowerBounds, UpperBounds )

        """ Calling the function for the first time before the SA main loop """
        Func = BTest.TestFunction( Function_Name, Ndim, X_Guess )


        X_OPT, F_OPT = ASA_Loops( Task, X_Guess, Func )
        
        X_Optimum.append( X_OPT )
        F_Optimum.append( F_OPT )

        """" Printing solutions in the screen and in the output file """

        TestSolution.append( BTest.AssessTests( Function_Name, XSolution, X_OPT, EPS ) )
        IO.f_SAOutput.write( '\n' )
        IO.f_SAOutput.write( '{a:}:{b:}'.format( a = Function_Name, b = TestSolution[ itest ] ) + '\n' )
        IO.f_SAOutput.write( '\n' )

        print Function_Name, ':', TestSolution[ itest ]
Exemplo n.º 16
0
import RandomGenerator
import numpy as np

x = RandomGenerator.poisson(1000, 0.5)
x = np.array(x)

print "Max=%i Min=%i" % (x.max(), x.min())

np.save("_gen/random_values.npy", x)
Exemplo n.º 17
0
def getLastRecordsBySource(args=None):
	return "select * from IoTMessages where source = '" + \
		RandomGenerator.choice(SOURCES) + \
		"' order by timestamp desc limit "+`args.statementSize`
Exemplo n.º 18
0
def generateSerialNum(plainOutput=False):
    if plainOutput:
        return str(RandomGenerator.randomIntegerNbit(128))
    return 'Serial number: ' + str(RandomGenerator.randomIntegerNbit(128))
Exemplo n.º 19
0
def ASA_Loops(TestName, X_Try, Func, **kwargs):

    if kwargs:
        for key in kwargs:
            if (key == 'LBounds'):
                Lower_Bounds = kwargs[key]
            elif (key == 'UBounds'):
                Upper_Bounds = kwargs[key]
            elif (key == 'Minimum'):
                Minimum = kwargs[key]
            elif (key == 'NDim'):
                Ndim = kwargs[key]
            elif (key == 'VM'):
                VM = kwargs[key]
            elif (key == 'C'):
                C = kwargs[key]

    else:
        Lower_Bounds = SA_LowerBounds
        Upper_Bounds = SA_UpperBounds
        Ndim = SA_N
        VM = SA_VM
        C = SA_C
        Minimum = SA_Minimum
    """ For debugging """
    #pdb.set_trace()

    IO.f_SAOutput.write('\n')
    IO.f_SAOutput.write('Initialising SA Algorithm for: {a:}'.format(
        a=TestName) + '\n')
    """ Initialisation of a few parameters. """
    Try = False
    NAcc = 0
    Nobds = 0
    NFCNEV = 0
    NEps = 4
    MaxNum = 1.e20

    NACP = [0 for i in range(Ndim)]
    XP = [0. for i in range(Ndim)]
    FStar = [MaxNum for i in range(NEps)]
    FStar[0] = Func

    FOpt = Func
    XOpt = X_Try

    Temp = SA_Temp
    Fraction = True

    if SA_Testing:
        Fraction = False

    kloop = 0
    """ Beginning of the main outter loop: """
    while kloop <= SA_MaxEvl:

        NUp = 0
        NRej = 0
        NDown = 0
        LNobds = 0
        """ Beginning of the m loop: """
        mloop = 0
        while mloop < SA_NT:
            """ Beginning of j loop: """
            jloop = 0
            while jloop < SA_NS:
                """ Beginning of the h loop: """
                hloop = 0
                while hloop < Ndim:

                    if Fraction:
                        dim = Ndim - 1
                    else:
                        dim = Ndim

                    for i in range(dim):
                        rand = RanGen.RandomNumberGenerator(
                            Ndim, Lower_Bounds, Upper_Bounds)

                        if (i == hloop):
                            XP[i] = X_Try[i] + VM[i] * (2. * rand[i] - 1.)
                        else:
                            XP[i] = X_Try[i]

                    if Fraction:
                        XP[dim] = 1. - ListSum(XP[0:dim])

                    Envelope_Constraints(XP,
                                         NDim=Ndim,
                                         LBounds=Lower_Bounds,
                                         UBounds=Upper_Bounds,
                                         TryC=Try,
                                         IsNormalised=Fraction)

                    if Try:
                        LNobds += 1
                        Nobds += 1

                    FuncP = BTest.TestFunction(TestName, Ndim, XP)
                    """ The function must be minimum """
                    if Minimum:
                        FuncP = -FuncP

                    NFCNEV += 1
                    """ If there were more than MAXEVL evaluations of the objective function, 
                        the SA algorithm may finish """
                    if (NFCNEV >= SA_MaxEvl):
                        IO.f_SAOutput.write(
                            '\n \n    ################################################################################## \n'
                        )
                        IO.f_SAOutput.write(
                            '{s:20} Maximum number of evaluations of the function was reached. Either increase MAXEVL or EPS or reduce RT or NT (NFCNEV: {a:})'
                            .format(s=' ', a=NFCNEV) + '\n')
                        IO.f_SAOutput.write(
                            '{s:20} XOpt: {a:} with FOpt: {b:}'.format(s=' ',
                                                                       a=XOpt,
                                                                       b=FOpt))
                        sys.exit()
                    """ The new coordinate is accepted and the objective
                        function increases """
                    if (FuncP >= Func):
                        X_Try = XP
                        Func = FuncP

                        if (SA_Debugging):
                            IO.f_SAOutput.write(
                                '{s:20} New vector-solution is accepted ( X: {a:}) with solution {b:.4f}'
                                .format(s=' ', a=X_Try, b=FuncP) + '\n')

                        NAcc += 1
                        NACP[hloop] = NACP[hloop] + 1
                        NUp += 1
                        """ If the new FP is larger than any other point,
                            this will be chosen as the new optimum """

                        if (FuncP > FOpt):
                            for i in range(Ndim):
                                XOpt[i] = XP[i]
                            FOpt = FuncP

                    else:
                        """ However if FuncP is smaller than the others, thus the Metropolis
                            criteria (Gaussian probability density function) - or any other
                            density function that may be added latter - may be used to either
                            accept or reject this coordinate.  """
                        rand = RanGen.RandomNumberGenerator(
                            Ndim, Lower_Bounds, Upper_Bounds)
                        Density = math.exp((FuncP - Func) / max(Temp, SA_EPS))
                        Density_Gauss = 0.5 * (rand[0] * rand[Ndim - 1])

                        if (Density_Gauss < Density):
                            X_Try = XP
                            Func = FuncP

                            if (SA_Debugging):
                                IO.f_SAOutput.write('\n \n ')
                                IO.f_SAOutput.write(
                                    '{s:20} Metropolis Criteria; New vector-solution is generated ( X: {a:}) with solution {b:.4f}'
                                    .format(s=' ', a=X_Try, b=FuncP) + '\n')

                            NAcc += 1
                            NACP[hloop] = NACP[hloop] + 1
                            NDown += 1

                        else:
                            NRej += 1
                    """ End of h loop """
                    hloop += 1
                """ End of j loop """
                jloop += 1
            """ As half of the evaluations may be accepted, thus the VM array may be adjusted """
            for i in range(SA_N):
                Ratio = float(NACP[i]) / float(SA_NS)
                if (Ratio > 0.6):
                    VM[i] = VM[i] * (1. + C[i] * (Ratio - 0.6) / 0.4)

                elif (Ratio < 0.4):
                    VM[i] = VM[i] * (1. + C[i] * (0.41 - Ratio) / 0.4)

                if (VM[i] > (Upper_Bounds[i] - Lower_Bounds[i])):
                    VM[i] = Upper_Bounds[i] - Lower_Bounds[i]

            #IO.f_SAOutput.write( '{s:20} {a:3d} Points rejected. VM is adjusted to {b:}'.format( s = ' ', a = NRej, b = VM ) + '\n' )

            NACP = [0 for i in NACP]
            """ End of m loop """
            mloop += 1
        """ Checking the stopping criteria """
        Quit = True
        FStar[0] = Func

        if ((FOpt - FStar[0]) <= SA_EPS):
            Quit = True

        for i in range(NEps):
            if (abs(Func - FStar[i]) > SA_EPS):
                Quit = False

        if Quit:
            X_Try = XOpt

            if Minimum:
                FOpt = -FOpt

            IO.f_SAOutput.write(
                '\n \n     ******** TERMINATION ALGORITHM *********** \n \n ')

            IO.f_SAOutput.write(
                '{s:20} Minimum was found (FOpt = {a:}) with coordinates XOpt: {b:}'
                .format(s=' ', a=FOpt, b=XOpt) + '\n')
            IO.f_SAOutput.write(
                '{s:20} Number of evaluations of the function:{a:5d}. Number of rejected points:{b:5d}'
                .format(s=' ', a=NFCNEV, b=NRej) + '\n')

            return XOpt, FOpt
        """ If the stoppage criteria can not be reached, return to the LOOP """
        Temp = SA_RT * Temp
        for i in xrange(NEps - 1, 0, -1):
            FStar[i] = FStar[i - 1]

        Func = FOpt
        X_Try = XOpt
        """ End of k loop """
        kloop += 1
Exemplo n.º 20
0
import RandomGenerator as rand
import SpectralMethod as sm
import numpy as np

#######################################################################
## Set here the model parameters:
#######################################################################
N = 1000  #The number of documents
n = 6  #The size of the vocabulary
k = 3  #The number of topics
c = 3000  #The number of words per document
TestSingleTopic = True  #Set to true to test the single topic model, to false to test LDA

if TestSingleTopic:
    # We generate the random text X, and parameters of the model
    X, M, omega, _ = rand.generate_sample_SingleTopic(N, n, k, c)
    # We retrieve the tensors we need to learn the model
    M1, M2, M3 = sm.RetrieveTensorsST(X)
    # We learn the model parameters
    M_tilde, omega_tilde = sm.learn_LVM_Core(M1, M2, M3, k)
    print('Error: %f ' % (np.linalg.norm(
        M_tilde.dot(np.diag(omega_tilde)).dot(M_tilde.T) -
        M.dot(np.diag(omega)).dot(M.T))))
else:
    # We generate the random text X, and parameters of the model
    X, M, Alpha = rand.generate_sample_LDA(N, n, k, c)
    Alpha0 = np.sum(Alpha)
    # We retrieve the tensors we need to learn the model
    M1a, M2a, M3a = sm.RetrieveTensorsLDA(X, Alpha0)
    # We learn the model parameters
    M_tilde, Alpha_tilde = sm.learn_LVM_Core_LDA(M1a, M2a, M3a, Alpha0, k)
Exemplo n.º 21
0
        StudyDir, StudyName,
        'normalisation' + str(ctrlInst.runNumber()) + '.root')
    trfCmplxFile = os.path.join(
        nuSIMPATH, '11-Parameters/nuSTORM-TrfLineCmplx-Params-v1.0.csv')
    print("ftrfCmplxFile ", trfCmplxFile)
    print(
        "numSIMPATH, filename, rootinputfilename, rootfilename, trfCmplxFile \n",
        nuSIMPATH, "\n", filename, "\n", rootInputFilename, "\n", rootFilename,
        "\n", trfCmplxFile)
    outFilename = rootFilename
    logging.info(
        "Parameters: %s,  \ntransfer line parameters: %s,  \noutput file: %s",
        filename, trfCmplxFile, rootFilename)

    # Get machine and run parameters
    RndmGen = Rndm.RandomGenerator(rootInputFilename, 'histP', 'histXPS')
    nuStrt = nuPrdStrt.nuSTORMPrdStrght(filename)
    psLength = nuStrt.ProdStrghtLen()
    nuTrLnCmplx = nuTrfLineCmplx.nuSTORMTrfLineCmplx(trfCmplxFile)
    tlCmplxLength = nuTrLnCmplx.TrfLineCmplxLen()
    detectorPosZ = nuStrt.HallWallDist()
    # set up the detector front face
    fluxPlane = plane.plane(psLength, detectorPosZ)
    # set up the event history - instantiate
    eH = eventHistory.eventHistory()
    eH.outFile(outFilename)
    # create the root structure to write to
    eH.rootStructure()
    # initialise the python arrays to something sensible
    eH.makeHistory()
Exemplo n.º 22
0
def ASA_Loops(Method, Task, Func, **kwargs):
    """ For debugging """
    #pdb.set_trace()

    TestName = SaT.Function_Name
    SVLE_Problem = False
    if kwargs:
        for key in kwargs:
            if (key == 'X_Feed'):
                X_Feed = kwargs[key]
            elif key == 'Thermodynamics':
                PhaseEquilibria = kwargs[key]
                SVLE_Problem = True
            else:
                sys.exit('In ASA_Loops. Option was not defined')

    IO.f_SAOutput.write('\n')
    IO.f_SAOutput.write('Initialising SA Algorithm for: {a:}'.format(
        a=TestName) + '\n')
    """ Initialisation of a few parameters. """
    Try = False
    NAcc = 0
    Nobds = 0
    NFCNEV = 0
    NEps = 4
    MaxNum = 1.e20

    NACP = [0 for i in range(SaT.Ndim)]
    XP = [0. for i in range(SaT.Ndim)]
    FStar = [MaxNum for i in range(NEps)]
    FStar[0] = Func

    FOpt = Func
    XOpt = SaT.SA_X
    X_Try = SaT.SA_X
    XOpt_f = [0. for i in range(SaT.Ndim)]
    """ The 'Fraction' variable assesses if the function to be optimised is
           a thermodynamic function (TRUE) and therefore the elements of the
           solution-coordinate needs to be bounded (0,1) and the summation
           of the N-1 elements must be smaller than 1.
        If FALSE then the above is neglected.                               """
    if Task == 'Benchmarks':
        Fraction = False
    elif Task == 'Problem' and SVLE_Problem:  #Problems
        Fraction = True
    """ =======================================================================
                       Beginning of the main outter loop: 
        ======================================================================= """

    kloop = 0
    while kloop <= SaT.MaxEvl:

        NUp = 0
        NRej = 0
        NDown = 0
        LNobds = 0
        """ Beginning of the m loop: number of iterations """
        mloop = 0
        while mloop < SaT.NT:
            """ Beginning of j loop: number of cycles"""
            jloop = 0
            while jloop < SaT.NS:
                """ Beginning of the h loop: """
                hloop = 0

                while hloop < SaT.Ndim:

                    if Fraction:
                        dim = SaT.Ndim - 1
                    else:
                        dim = SaT.Ndim

                    for i in range(SaT.Ndim):
                        rand = RanGen.RandomNumberGenerator(SaT.Ndim)

                        if (i == hloop):
                            XP[i] = X_Try[i] + SaT.VM[i] * (2. * rand[i] - 1.)
                        else:
                            XP[i] = X_Try[i]

                    #IO.f_SAOutput.write( 'XP(b4):{a:}'.format( a= XP ) + '\n' )

                    #pdb.set_trace()
                    """ ===========================================================
                            Feasibility Test: check is solution is bounded.
                        =========================================================== """
                    #if Fraction:
                    #    XP[ dim ] = X_Try[ dim ]
                    #XP[ SaT.Ndim ] = X_Try[ SaT.Ndim ]

                    if Task == 'Benchmarks':
                        BoxF.Envelope_Constraints( Method, Task, XP, NDim = SaT.Ndim, LBounds = SaT.LowerBounds, \
                                                   UBounds = SaT.UpperBounds, TryC = Try, IsNormalised = Fraction )

                    else:  # Problems
                        BoxF.Envelope_Constraints( Method, Task, XP, NDim = SaT.Ndim, LBounds = SaT.LowerBounds, \
                                                   UBounds = SaT.UpperBounds, TryC = Try, IsNormalised = Fraction, \
                                                   X_Feed = X_Feed )

                    #IO.f_SAOutput.write( 'XP(after):{a:}'.format( a= XP ) + '\n' )
                    #IO.f_SAOutput.write( '\n' )
                    #if kloop > 10:
                    print XP
                    sys.exit('fck')

                    if Try:
                        LNobds += 1
                        Nobds += 1
                    """ ============================================================ """

                    if Task == 'Benchmarks':
                        FuncP = BTest.TestFunction(SaT.Function_Name, SaT.Ndim,
                                                   XP)
                    else:  # Problems
                        FuncP, dummy = ObF.ObjFunction(
                            XP, Thermodynamics=PhaseEquilibria)
                    """ The function must be minimum """
                    if SaT.Minimum:
                        FuncP = -FuncP

                    NFCNEV += 1  # Number of evaluation of the function
                    """
                       ==================================================================
                         If there were more than MAXEVL evaluations of the objective
                            function, the SA algorithm will finish.
                       =================================================================="""

                    if (NFCNEV >= SaT.MaxEvl):
                        FOpt = -FOpt
                        Print.Print_SAA_Diagnostic(MaxEval='yes',
                                                   FOpt=FOpt,
                                                   XOpt=XOpt_f,
                                                   NFCNEV=NFCNEV)
                        sys.exit(
                            'SAA did not converge. Too many evaluations of the function!'
                        )
                    """"
                       ==================================================================
                         The new solution-coordinate is accepted and the objective 
                            function increases.
                       =================================================================="""

                    if (FuncP > Func):
                        for i in range(SaT.Ndim):
                            X_Try[i] = XP[i]
                        Func = FuncP

                        if SaT.Debugging == True:
                            IO.f_SAOutput.write(
                                '{s:20} New vector-solution is accepted ( X: {a:}) with solution {b:.4f}'
                                .format(s=' ', a=X_Try, b=FuncP) + '\n')

                        NAcc += 1
                        NACP[hloop] = NACP[hloop] + 1
                        NUp += 1
                        """ If the new FP is larger than any other point, this will be 
                               chosen as the new optimum                               """

                        if (FuncP > FOpt):
                            for i in range(SaT.Ndim):
                                XOpt[i] = XP[i]
                            FOpt = FuncP
                            for i in range(SaT.Ndim):
                                XOpt_f[i] = XP[i]

                        if Task == 'Benchmarks':
                            print 'NFCNEV(', NFCNEV, '), XOpt: ', XOpt_f, ' with FOpt: ', FOpt, '(Analytical:', -BTest.TestFunction(
                                SaT.Function_Name, SaT.Ndim,
                                SaT.BenchmarkSolution[0:SaT.Ndim]), ')'
                        else:
                            if (NFCNEV % 25) >= 24:
                                print 'NFCNEV(', NFCNEV, '), XOpt: ', XOpt_f, ' with FOpt: ', FOpt

                            if SaT.Debugging == True:
                                IO.f_SAOutput.write(
                                    '{s:20} New XOpt: {a:} with FOpt: {b:}'.
                                    format(s=' ', a=XOpt_f, b=FOpt) + '\n')

                    else:  # if ( FuncP > Func ):
                        """ However if FuncP is smaller than the others, thus the Metropolis criteria 
                               (Gaussian probability density function) - or any other density function
                               that may be added latter - may be used to either accept or reject this
                               coordinate.                                                            """

                        rand = RanGen.RandomNumberGenerator(SaT.Ndim)
                        #Density = math.exp( ( FuncP - Func ) / SaT.Temp )#max( SaT.Temp, SaT.EPS ) )
                        if SaT.Temp < max(1.e-6, SaT.EPS):
                            Density = math.exp(
                                (FuncP - Func) / max(1.e-3 * SaT.EPS, rand[0]))
                        else:
                            Density = math.exp((FuncP - Func) / SaT.Temp)
                        temp = 1.
                        for i in range(SaT.Ndim):
                            temp = temp * rand[i]
                        Density_Gauss = math.sqrt(abs(temp))

                        if (Density_Gauss < Density):
                            for i in range(SaT.Ndim):
                                X_Try[i] = XP[i]
                            Func = FuncP

                            if SaT.Debugging == True:
                                IO.f_SAOutput.write('\n \n ')
                                IO.f_SAOutput.write(
                                    '{s:20} Metropolis Criteria; New vector-solution is generated ( X: {a:}) with solution {b:.4f}'
                                    .format(s=' ', a=X_Try, b=FuncP) + '\n')

                            NAcc += 1
                            NACP[hloop] = NACP[hloop] + 1
                            NDown += 1

                        else:
                            NRej += 1
                    """ End of h loop """
                    #pdb.set_trace()
                    hloop += 1
                """ End of j loop """
                jloop += 1
            """
               ==================================================================
                 As half of the evaluations may be accepted, thus the VM array
                     may need to be adjusted.
               ================================================================== """

            for i in range(SaT.Ndim):
                Ratio = float(NACP[i]) / float(SaT.NS)
                if (Ratio > 0.6):
                    SaT.VM[i] = SaT.VM[i] * (1. + SaT.C[i] *
                                             (Ratio - 0.6) / 0.4)

                elif (Ratio < 0.4):
                    SaT.VM[i] = SaT.VM[i] / (1. + SaT.C[i] *
                                             (0.4 - Ratio) / 0.4)

                if (SaT.VM[i] > (SaT.UpperBounds[i] - SaT.LowerBounds[i])):
                    SaT.VM[i] = SaT.UpperBounds[i] - SaT.LowerBounds[i]

            if SaT.Debugging == True:
                IO.f_SAOutput.write(
                    '{s:20} {a:3d} Points rejected. VM is adjusted to {b:}'.
                    format(s=' ', a=NRej, b=SaT.VM) + '\n')

            NACP = [0 for i in range(SaT.Ndim)]
            """ End of m loop """
            mloop += 1
        """
           =======================================================================
                Diagnostics of the algorithm before the next temperature reduction
           ======================================================================= """

        Print.Print_SAA_Diagnostic(Diagnostics='yes',
                                   FOpt=FOpt,
                                   NUp=NUp,
                                   NDown=NDown,
                                   NRej=NRej,
                                   NAcc=NAcc,
                                   LNobds=LNobds,
                                   NFCNEV=NFCNEV,
                                   XOpt=XOpt,
                                   FStar=FStar)

        # This will make the tests run faster as we know the solution, thus they do
        #     not need to continue search if the solution if close enough
        if Task == 'Benchmarks':
            Quit = BTest.AssessTests(XOpt_f, SaT.BenchmarkSolution)
            if Quit:
                if SaT.Minimum:
                    FOpt = -FOpt
                Print.Print_SAA_Diagnostic(Termination='yes',
                                           FOpt=FOpt,
                                           NRej=NRej,
                                           XOpt=XOpt_f,
                                           NFCNEV=NFCNEV)
                return XOpt_f, FOpt
        #stop
        """
           ==========================================================
                     Checking the stoppage criteria           
           ==========================================================  """

        Quit = True
        FStar[0] = Func

        #print '--------------------------------------'
        #print ' FOpt, FStar, Func', FOpt, FStar, Func
        #print '--------------------------------------'

        if FOpt - FStar[0] <= SaT.EPS:
            Quit = False

        for i in range(NEps):
            if abs(Func - FStar[i]) > SaT.EPS:
                Quit = False

        if Quit:
            if Task == 'Benchmarks':
                Quit = BTest.AssessTests(XOpt_f, SaT.BenchmarkSolution)

            elif Task == 'Problem' and IO.to_bool(
                    SaT.BenchmarkSolution[0]):  # For validation
                Solution = np.arange(float(SaT.Ndim))
                for i in range(SaT.Ndim):
                    Solution[i] = IO.num(SaT.BenchmarkSolution[i + 1])

                FuncValid, dummy = ObF.ObjFunction(
                    Solution, Thermodynamics=PhaseEquilibria)
                FuncOpt, dummy = ObF.ObjFunction(
                    XOpt, Thermodynamics=PhaseEquilibria)
                print 'Gibbs Function (Validation, Optimum):', FuncValid, FuncOpt

                Pass = True
                if abs(FuncValid - FuncOpt) >= SaT.EPS:
                    Pass = Pass and False

                for i in range(SaT.Ndim):
                    if abs(XOpt[i] - Solution[i]) >= SaT.EPS:
                        Pass = Pass and False

                if Pass:
                    print 'Error Associated with: '
                    print ' (a) Function: ', abs(
                        FuncValid - FuncOpt) / FuncValid * 100., '%'
                    print ' (b) Solution Variables:'
                    for i in range(SaT.Ndim):
                        print 'X[', i, ']', abs(
                            XOpt[i] - Solution[i]) / Solution[i] * 100., '%'
                    Quit == True

        #print '===>', SaT.BenchmarkSolution
        #print assert(SaT.BenchmarkSolution)
        #sys.exit('fck11')

        #if assert(SaT.BenchmarkSolution):
        #    sys.exit('fck11')
        #else:
        #    sys.exit('fck--')
        #elif Quit and ( Task == 'Problem' ) and
        """
           ==========================================================
               Termination of the Simulated Annealing algorithm       
           ==========================================================  """

        if Quit:
            #X_Try = XOpt
            if SaT.Minimum:
                FOpt = -FOpt

            Print.Print_SAA_Diagnostic(Termination='yes',
                                       FOpt=FOpt,
                                       NRej=NRej,
                                       XOpt=XOpt_f,
                                       NFCNEV=NFCNEV)
            if Task == 'Problem':
                SpFunc.CalcOtherPhase(XP,
                                      SaT.UpperBounds,
                                      SaT.LowerBounds,
                                      Diagnostics=True)

            return XOpt_f, FOpt

        #print ' XOpt_f, FOpt ', XOpt_f, FOpt
        """
           ==========================================================
              If the stoppage criteria can not be reached, then
                 continue the K-LOOP
           ==========================================================  """

        SaT.Temp = SaT.RT * SaT.Temp
        for i in xrange(NEps - 1, 0, -1):
            FStar[i] = FStar[i - 1]
            #print 'FStar[ i ]',FStar[ i ]

        Func = FOpt
        for i in range(SaT.Ndim):
            X_Try[i] = XOpt[i]
            #print 'X_Try[ i ]',X_Try[ i ]
        """ End of k loop """
        kloop += 1
Exemplo n.º 23
0
def ASA_Loops(Task, Func):
    """ For debugging """
    #pdb.set_trace()
    TestName = SaT.Function_Name

    IO.f_SAOutput.write('\n')
    IO.f_SAOutput.write('Initialising SA Algorithm for: {a:}'.format(
        a=TestName) + '\n')
    """ Initialisation of a few parameters. """
    Try = False
    NAcc = 0
    Nobds = 0
    NFCNEV = 0
    NEps = 4
    MaxNum = 1.e20

    NACP = [0 for i in range(SaT.Ndim)]
    XP = [0. for i in range(SaT.Ndim)]
    FStar = [MaxNum for i in range(NEps)]
    FStar[0] = Func

    FOpt = Func
    XOpt = SaT.SA_X
    X_Try = SaT.SA_X
    XOpt_f = [0. for i in range(SaT.Ndim)]
    """ The 'Fraction' variable assess if the function to be optimised is
           a thermodynamic function (TRUE) and therefore the elements of the
           solution-coordinate needs to be bounded (0,1) and the summation
           of the N-1 elements must be smaller than 1.
        If FALSE then the above is neglected.                               """
    if Task == 'Benchmarks':
        Fraction = False
    else:
        Fraction = True

    kloop = 0
    """ Beginning of the main outter loop: """
    while kloop <= SaT.MaxEvl:

        NUp = 0
        NRej = 0
        NDown = 0
        LNobds = 0
        """ Beginning of the m loop: """
        mloop = 0
        while mloop < SaT.NT:
            """ Beginning of j loop: """
            jloop = 0
            while jloop < SaT.NS:
                """ Beginning of the h loop: """
                hloop = 0

                while hloop < SaT.Ndim:

                    if Fraction:
                        dim = SaT.Ndim - 1
                    else:
                        dim = SaT.Ndim

                    for i in range(dim):
                        rand = RanGen.RandomNumberGenerator(dim)

                        if (i == hloop):
                            XP[i] = X_Try[i] + SaT.VM[i] * (2. * rand[i] - 1.)
                        else:
                            XP[i] = X_Try[i]
                    """ ===========================================================
                            Feasibility Test (only for Thermod problems) -- check
                              for compositional constraints.
                        =========================================================== """
                    if Fraction:
                        XP[dim - 1] = 1. - SpFunc.ListSum(XP[0:dim])

                    SpFunc.Envelope_Constraints(XP,
                                                NDim=SaT.Ndim,
                                                LBounds=SaT.LowerBounds,
                                                UBounds=SaT.UpperBounds,
                                                TryC=Try,
                                                IsNormalised=Fraction)

                    if Try:
                        LNobds += 1
                        Nobds += 1
                    """ ============================================================ """

                    if Task == 'Benchmarks':
                        FuncP = BTest.TestFunction(SaT.Function_Name, SaT.Ndim,
                                                   XP)
                    else:  # Problems
                        FuncP = ObF.ObjFunction(SaT.Function_Name, SaT.Ndim,
                                                XP)
                    """ The function must be minimum """
                    if SaT.Minimum:
                        FuncP = -FuncP

                    NFCNEV += 1  # Number of evaluation of the function
                    """
                       ==================================================================
                         If there were more than MAXEVL evaluations of the objective
                            function, the SA algorithm will finish.
                       =================================================================="""

                    if (NFCNEV >= SaT.MaxEvl):
                        FOpt = -FOpt
                        Print.Print_SAA_Diagnostic(MaxEval='yes',
                                                   FOpt=FOpt,
                                                   XOpt=XOpt_f,
                                                   NFCNEV=NFCNEV)
                        sys.exit(
                            'SAA did not converge. Too many evaluations of the function!'
                        )
                    """"
                       ==================================================================
                         The new solution-coordinate is accepted and the objective 
                            function increases.
                       =================================================================="""

                    if (FuncP >= Func):
                        for i in range(SaT.Ndim):
                            X_Try[i] = XP[i]
                        Func = FuncP

                        if SaT.Debugging == True:
                            IO.f_SAOutput.write(
                                '{s:20} New vector-solution is accepted ( X: {a:}) with solution {b:.4f}'
                                .format(s=' ', a=X_Try, b=FuncP) + '\n')

                        NAcc += 1
                        NACP[hloop] = NACP[hloop] + 1
                        NUp += 1
                        """ If the new FP is larger than any other point, this will be 
                               chosen as the new optimum                               """

                        if (FuncP > FOpt):
                            for i in range(SaT.Ndim):
                                XOpt[i] = XP[i]
                            FOpt = FuncP
                            for i in range(SaT.Ndim):
                                XOpt_f[i] = XP[i]

                            print 'NFCNEV(', NFCNEV, '), XOpt: ', XOpt_f, ' with FOpt: ', FOpt, '(Analytical:', -BTest.TestFunction(
                                SaT.Function_Name, SaT.Ndim,
                                SaT.BenchmarkSolution[0:SaT.Ndim]), ')'

                            if SaT.Debugging == True:
                                IO.f_SAOutput.write(
                                    '{s:20} New XOpt: {a:} with FOpt: {b:}'.
                                    format(s=' ', a=XOpt_f, b=FOpt) + '\n')

                    else:
                        """ However if FuncP is smaller than the others, thus the Metropolis criteria 
                               (Gaussian probability density function) - or any other density function
                               that may be added latter - may be used to either accept or reject this
                               coordinate.                                                            """

                        rand = RanGen.RandomNumberGenerator(SaT.Ndim)
                        #Density = math.exp( ( FuncP - Func ) / SaT.Temp )#max( SaT.Temp, SaT.EPS ) )
                        if SaT.Temp < max(1.e-6, SaT.EPS):
                            Density = math.exp(
                                (FuncP - Func) / max(1.e-3 * SaT.EPS, rand[0]))
                        else:
                            Density = math.exp((FuncP - Func) / SaT.Temp)
                        temp = 1.
                        for i in range(SaT.Ndim):
                            temp = temp * rand[i]
                        Density_Gauss = math.sqrt(abs(temp))

                        if (Density_Gauss < Density):
                            for i in range(SaT.Ndim):
                                X_Try[i] = XP[i]
                            Func = FuncP

                            if SaT.Debugging == True:
                                IO.f_SAOutput.write('\n \n ')
                                IO.f_SAOutput.write(
                                    '{s:20} Metropolis Criteria; New vector-solution is generated ( X: {a:}) with solution {b:.4f}'
                                    .format(s=' ', a=X_Try, b=FuncP) + '\n')

                            NAcc += 1
                            NACP[hloop] = NACP[hloop] + 1
                            NDown += 1

                        else:
                            NRej += 1
                    """ End of h loop """
                    hloop += 1
                """ End of j loop """
                jloop += 1
            """
               ==================================================================
                 As half of the evaluations may be accepted, thus the VM array
                     may need to be adjusted.
               ================================================================== """

            for i in range(SaT.Ndim):
                Ratio = float(NACP[i]) / float(SaT.NS)
                if (Ratio > 0.6):
                    SaT.VM[i] = SaT.VM[i] * (1. + SaT.C[i] *
                                             (Ratio - 0.6) / 0.4)

                elif (Ratio < 0.4):
                    SaT.VM[i] = SaT.VM[i] / (1. + SaT.C[i] *
                                             (0.4 - Ratio) / 0.4)

                if (SaT.VM[i] > (SaT.UpperBounds[i] - SaT.LowerBounds[i])):
                    SaT.VM[i] = SaT.UpperBounds[i] - SaT.LowerBounds[i]

            if SaT.Debugging == True:
                IO.f_SAOutput.write(
                    '{s:20} {a:3d} Points rejected. VM is adjusted to {b:}'.
                    format(s=' ', a=NRej, b=SaT.VM) + '\n')

            NACP = [0 for i in range(SaT.Ndim)]
            """ End of m loop """
            mloop += 1
        """
           =======================================================================
                Diagnostics of the algorithm before the next temperature reduction
           ======================================================================= """

        Print.Print_SAA_Diagnostic(Diagnostics='yes',
                                   FOpt=FOpt,
                                   NUp=NUp,
                                   NDown=NDown,
                                   NRej=NRej,
                                   NAcc=NAcc,
                                   LNobds=LNobds,
                                   NFCNEV=NFCNEV,
                                   XOpt=XOpt,
                                   FStar=FStar)

        # This will make the tests run faster as we know the solution, thus they do
        #     not need to continue search if the solution if close enough
        if Task == 'Benchmarks':
            Quit = BTest.AssessTests(XOpt_f, SaT.BenchmarkSolution)
            if Quit:
                if SaT.Minimum:
                    FOpt = -FOpt
                Print.Print_SAA_Diagnostic(Termination='yes',
                                           FOpt=FOpt,
                                           NRej=NRej,
                                           XOpt=XOpt_f,
                                           NFCNEV=NFCNEV)
                return XOpt_f, FOpt
        """
           ==========================================================
                     Checking the stoppage criteria
           ==========================================================  """

        Quit = False
        FStar[0] = Func

        if FOpt - FStar[0] <= SaT.EPS:
            Quit = True

        for i in range(NEps):
            if abs(Func - FStar[i]) > SaT.EPS:
                Quit = False

        if Quit and (Task == 'Benchmarks'):
            Quit = BTest.AssessTests(XOpt_f, SaT.BenchmarkSolution)
        """
           ==========================================================
               Termination of the Simulated Annealing algorithm       
           ==========================================================  """

        if Quit:
            #X_Try = XOpt
            if SaT.Minimum:
                FOpt = -FOpt

            Print.Print_SAA_Diagnostic(Termination='yes',
                                       FOpt=FOpt,
                                       NRej=NRej,
                                       XOpt=XOpt_f,
                                       NFCNEV=NFCNEV)

            return XOpt_f, FOpt
        """
           ==========================================================
              If the stoppage criteria can not be reached, then
                 continue the K-LOOP
           ==========================================================  """

        SaT.Temp = SaT.RT * SaT.Temp
        for i in xrange(NEps - 1, 0, -1):
            FStar[i] = FStar[i - 1]

        Func = FOpt
        for i in range(SaT.Ndim):
            X_Try[i] = XOpt[i]
        """ End of k loop """
        kloop += 1
Exemplo n.º 24
0
def getRandomRecordsByRecordID(args=None):
	start = RandomGenerator.randint32()%(generationCount * args.concurrency)
	end = start + args.statementSize
	return "select * from IoTMessages where record_id > " + `start` + \
		" and record_id < " + `end` + \
		" order by timestamp desc limit " + `args.statementSize`
Exemplo n.º 25
0
def Envelope_Constraints(X, **kwargs):
    """ This function ensures that variable 'X' is bounded """

    rand = []
    TryAgain = True
    IsNormalised = True

    if kwargs:
        for key in kwargs:
            if (key == 'LBounds'):
                LowerBounds = kwargs[key]
            elif (key == 'UBounds'):
                UpperBounds = kwargs[key]
            elif (key == 'NDim'):
                n = kwargs[key]
            elif (key == 'TryC'):
                Try = kwargs[key]
            elif (key == 'IsNormalised'):
                IsNormalised = kwargs[key]
            elif (key == 'Z_Feed'):
                Z_Feed = kwargs[key]

    else:
        LowerBounds = SaT.LowerBounds
        UpperBounds = SaT.UpperBounds
        n = SaT.Ndim

    evaluations = 1

    if (IsNormalised):  # Mole/Mass/Volume Fraction
        dim = n - 1
    else:
        dim = n

    while TryAgain:

        #pdb.set_trace()

        #for i in range( dim ):
        for i in range(n):
            if ((X[i] < LowerBounds[i]) or (X[i] > UpperBounds[i])):
                rand = RanGen.RandomNumberGenerator(n)
                X[ i ] = LowerBounds[ i ] + ( UpperBounds[ i ] - LowerBounds[ i ] ) * \
                    rand[ i ]
                X[i] = min(max(LowerBounds[i], X[i]), UpperBounds[i])
                Try = True

        if (IsNormalised):  # Thermod problem

            Sum = ListSum(X[0:dim])

            if (Sum < 1.):
                SumOneOtherPhase = CalcOtherPhase(X, Z_Feed, UpperBounds,
                                                  LowerBounds)
                if SumOneOtherPhase:
                    TryAgain = False
                    if kwargs:
                        for key in kwargs:
                            if (key == 'TryC'):
                                return X, Try
                            else:
                                return X
                    else:
                        return X
                else:  # It did not satisfy the Box Formulation
                    rand = RanGen.RandomNumberGenerator(n)
                    for i in range(n):
                        X[ i ] = LowerBounds[ i ] + ( UpperBounds[ i ] - LowerBounds[ i ] ) * \
                            rand[ i ]
                        X[i] = min(max(LowerBounds[i], X[i]), UpperBounds[i])

            else:
                #for i in range( dim ): # This may need to be re-assesed later ...
                for i in range(n):  # This may need to be re-assesed later ...
                    rand = RanGen.RandomNumberGenerator(n)
                    if (evaluations % 3 == 0):
                        X[i] = rand[i]
                    elif (evaluations % 7 == 0):
                        X[i] = min(rand[i], rand[i + 1]) / max(
                            MinNum, float(i), 1. / rand[i + 1])
                    elif (evaluations % 11 == 0):
                        X[i] = abs(1. - rand[i] / rand[i + 1])
                    else:
                        X[i] = rand[i - 1]

                evaluations = evaluations + 1

                Sum = ListSum(X[0:dim])
                if (Sum < 1.):
                    SumOneOtherPhase = CalcOtherPhase(X, Z_Feed, UpperBounds,
                                                      LowerBounds)
                    Try = True
                    if SumOneOtherPhase:
                        TryAgain = False
                        if kwargs:
                            for key in kwargs:
                                if (key == 'TryC'):
                                    return X, Try
                                else:
                                    return X
                        else:
                            return X
            """ ################################################################################
                  Here it needs to be add a function to ensure feasibility of the composition
                    solution-coordinates,
                                  XiL = ( Z - (1-L) *XiV ) / L
                    This means we need to add a function linking the
                    SAA and the thermodynamic functions.
                ################################################################################"""

        else:  # Not a Thermod problem
            if kwargs:
                for key in kwargs:
                    if (key == 'TryC'):
                        return X, Try
                    else:
                        return X
            else:
                return X
Exemplo n.º 26
0
import RandomGenerator
import numpy as np

x = RandomGenerator.poisson(1000,0.5)
x = np.array(x)

print "Max=%i Min=%i" % (x.max(),x.min())

np.save("_gen/random_values.npy", x)
Exemplo n.º 27
0
def Envelope_Constraints(X, **kwargs):
    """ This function ensures that variable 'X' is bounded """

    rand = []
    TryAgain = True
    IsNormalised = True

    if kwargs:
        for key in kwargs:
            if (key == 'LBounds'):
                LowerBounds = kwargs[key]
            elif (key == 'UBounds'):
                UpperBounds = kwargs[key]
            elif (key == 'NDim'):
                n = kwargs[key]
            elif (key == 'TryC'):
                Try = kwargs[key]
            elif (key == 'IsNormalised'):
                IsNormalised = kwargs[key]

    else:
        LowerBounds = SA_LowerBounds
        UpperBounds = SA_UpperBounds
        n = SA_N

    evaluations = 1

    if (IsNormalised):  # Mole/Mass/Volume Fraction
        dim = n - 1
    else:
        dim = n

    while TryAgain:

        for i in range(dim):
            if ((X[i] < LowerBounds[i]) | (X[i] > UpperBounds[i])):
                rand = RanGen.RandomNumberGenerator(n, LowerBounds,
                                                    UpperBounds)
                X[ i ] = LowerBounds[ i ] + ( UpperBounds[ i ] - LowerBounds[ i ] ) * \
                    rand[ i ]
                X[i] = min(max(LowerBounds[i], X[i]), UpperBounds[i])
                Try = True

        if (IsNormalised):

            Sum = ListSum(X[0:dim])

            if (Sum < 1.):
                X[n - 1] = 1. - Sum
                TryAgain = False
                if kwargs:
                    for key in kwargs:
                        if (key == 'TryC'):
                            return X, Try
                        else:
                            return X
                else:
                    return X
            else:
                for i in range(dim):
                    rand = RanGen.RandomNumberGenerator(
                        n, LowerBounds, UpperBounds)
                    if (evaluations % 3 == 0):
                        X[i] = rand[i]
                    elif (evaluations % 7 == 0):
                        X[i] = min(rand[i], rand[i + 1]) / max(
                            MinNum, float(i), 1. / rand[i + 1])
                    elif (evaluations % 11 == 0):
                        X[i] = abs(1. - rand[i] / rand[i + 1])
                    else:
                        X[i] = rand[i - 1]

                evaluations = evaluations + 1
                Try = True

        else:
            if kwargs:
                for key in kwargs:
                    if (key == 'TryC'):
                        return X, Try
                    else:
                        return X
            else:
                return X
Exemplo n.º 28
0
def _generateRecord(args=None):
	timeStamp = long(time.time()*1000)
	source = RandomGenerator.choice(SOURCES)
	message = '{"timeStamp": %s, "message": "this is a test"}' % timeStamp 
	return (timeStamp, source, message)
Exemplo n.º 29
0
def SimulatedAnnealing(Method, Task, **kwargs):

    IO.OutPut(Task, Method)

    IO.SA_GlobalVariables()

    ntests = 0
    if (Task == 'Benchmarks'):
        ntests = IO.CheckNumberTests()
        SA_Function, SA_Minimum, SA_N, SA_NS, SA_NT, SA_MaxEvl, SA_EPS, SA_RT, SA_Temp, \
            SA_LowerBounds, SA_UpperBounds, SA_VM, SA_C, SA_Debugging, SA_Xopt, \
            SA_Fopt = IO.ReadInCoolingSchedule( No_Tests = ntests )

    elif (Task == 'Problem'):
        if kwargs:  # For Problems
            for key in kwargs:
                if (key == 'FileName'):
                    Problem_FileName = kwargs[key]

            #IO.ReadInCoolingSchedule( File_Name = Problem_FileName )
            rub1 = [], rub2 = []
            SA_Function, SA_Minimum, SA_N, SA_NS, SA_NT, SA_MaxEvl, SA_EPS, SA_RT, SA_Temp, \
                SA_LowerBounds, SA_UpperBounds, SA_VM, SA_C, SA_Debugging, rub1, \
                rub2 =  IO.ReadInCoolingSchedule( File_Name = Problem_FileName )
            ntests = 0

        else:
            sys.exit('Option not found')

    else:
        sys.exit('Option not found')
    """ Calling main SA loop: """

    for itest in range(ntests):

        Function = SA_Function[itest]
        Ndim = SA_N[itest]
        Minimum = SA_Minimum[itest]
        NS = SA_NS[itest]
        NT = SA_NT[itest]
        MaxEvl = SA_MaxEvl[itest]
        EPS = SA_EPS[itest]
        RT = SA_RT[itest]
        Temp = SA_Temp[itest]
        LowerBounds = SA_LowerBounds[itest]
        UpperBounds = SA_UpperBounds[itest]
        VM = SA_VM[itest]
        C = SA_C[itest]
        Debugging = SA_Debugging[itest]

        if (Task == 'Benchmarks'):
            XSolution = SA_Xopt[itest]
            FSolution = SA_Fopt[itest]
        """ Initial guess-solution obtained randomly """
        X_Guess = []
        X_Guess = RanGen.RandomNumberGenerator(Ndim, LowerBounds, UpperBounds)
        """ Calling the function for the first time before the SA main loop """
        Func = BTest.TestFunction(Function, Ndim, X_Guess)
        print 'X,F:', Function, X_Guess, Func




        X_OPT, F_OPT = ASA_Loops( Function, Ndim, Minimum, NS, NT, MaxEvl, EPS, RT, Temp, \
                                      LowerBounds, UpperBounds, VM, C, Debugging, \
                                      X_Guess, Func )
Exemplo n.º 30
0
def Envelope_Constraints( Method, Task, X, **kwargs ):
    """ This function ensures that variable 'X' is bounded """

    #if Task == "Problem":
    #    SyP.EnvirVar( Task, Method, Thermodynamics = 'Thermodynamics' )
    #    import ThermoTools as ThT

    rand = []
    TryAgain = True
    IsNormalised = True

    if kwargs:
        for key in kwargs:
            if ( key == 'LBounds' ):
                LowerBounds = kwargs[ key ]
            elif ( key == 'UBounds' ):
                UpperBounds = kwargs[ key ]
            elif ( key == 'NDim' ):
                n = kwargs[ key ]
            elif ( key == 'TryC' ):
                Try = kwargs[ key ]
            elif ( key == 'IsNormalised' ):
                IsNormalised = kwargs[ key ]
            elif ( key == 'Z_Feed' ):
                Z_Feed = kwargs[ key ]

    else:
         LowerBounds = SaT.LowerBounds
         UpperBounds = SaT.UpperBounds
         n = SaT.Ndim
    
    evaluations = 1
    
    if ( IsNormalised ): # Mole/Mass/Volume Fraction (thermodynamic problem)
        dim = n - 1
    else:
        dim = n

    SumOneOtherPhase = True
        
    while TryAgain:

        #pdb.set_trace()
        for i in range( n ):
            if ( ( X[ i ] < LowerBounds[ i ] ) or ( X[ i ] > UpperBounds[ i ] ) or ( not SumOneOtherPhase ) or ( not Try )):
                rand = RanGen.RandomNumberGenerator( n )
                X[ i ] = LowerBounds[ i ] + ( UpperBounds[ i ] - LowerBounds[ i ] ) * \
                    rand[ i ]
                X[ i ] = min( max( LowerBounds[ i ], X[ i ] ), UpperBounds[ i ] )
                Try = True 

        if ( not IsNormalised ): 
            if kwargs:
                for key in kwargs:
                    if ( key == 'TryC' ):
                        return X, Try
                    else:
                        return X
            else:
                return X

        else: # Thermod problem

            if  ListSum( X[ 0 : dim ] ) < 1.:
                SumOneOtherPhase = CheckOtherPhase( Task, Method, X, UpperBounds, LowerBounds )
                if SumOneOtherPhase:
                    if Try:
                        return X, Try
                    else:
                        return X
            else:
                Try = False