示例#1
0
    def mc_reject(a, b, x):

        top = np.amax(fn(x))  # get max of function to integrate

        nAccept = 0
        nTotal = 0

        # accepted values
        Xaccept = []
        Yaccept = []

        # reject values
        Xreject = []
        Yreject = []

        # sample number
        isample = []
        # calculated values of the integral
        calcInt = []

        random = Random()

        idraw = max(1, int(Nsteps) / 100000)
        #print(idraw)
        for i in range(0, Nsteps):
            X = random.rand()  # leave as is since x range is [0,1]
            Y = top * random.rand(
            )  # transform this to sample from the max value of the function
            #print(top)
            nTotal += 1
            if (Y < np.sin(np.pi * X) + 1.0):  #accept if inside
                nAccept += 1
                if (i % idraw == 0):
                    Xaccept.append(X)
                    Yaccept.append(Y)
            else:  # reject if outside
                if (i % idraw == 0):
                    Xreject.append(X)
                    Yreject.append(Y)
            if (i % idraw == 0):
                isample.append(nTotal)
                calcInt.append(top * nAccept / nTotal)

        return (isample, calcInt)
示例#2
0
 def __init__(self, seed=5555):
     self.m_random = Random(seed)
示例#3
0
        p = sys.argv.index('-Nmeas')
        Nt = int(sys.argv[p + 1])
        if Nt > 0:
            Nmeas = Nt
    if '-Nexp' in sys.argv:
        p = sys.argv.index('-Nexp')
        Ne = int(sys.argv[p + 1])
        if Ne > 0:
            Nexp = Ne
    if '-output' in sys.argv:
        p = sys.argv.index('-output')
        OutputFileName = sys.argv[p + 1]
        doOutputFile = True

    # class instance of our Random class using seed
    random = Random(seed)

    if doOutputFile:
        outfile = open(OutputFileName, 'w')
        outfile.write(str(rate) + " \n")
        for e in range(0, Nexp):
            for t in range(0, Nmeas):
                outfile.write(str(random.Exponential(rate)) + " ")
            outfile.write(" \n")
        outfile.close()
    else:
        print(rate)
        for e in range(0, Nexp):
            for t in range(0, Nmeas):
                print(random.Exponential(rate), end=' ')
            print(" ")
示例#4
0
            Nskip = Ns
    if '--model0' in sys.argv:
        model = 0
    elif '--model1' in sys.argv:
        model = 1
    else:
        print("You must specify a model.")
        sys.exit(1)

    if '-output' in sys.argv:
        p = sys.argv.index('-output')
        OutputFileName = sys.argv[p + 1]
        doOutputFile = True

    # class instance of our Random class using seed
    random = Random(seed)

    def getObservation():

        # model 0
        # alpha and beta for our gamma distribution
        alpha = 2.7
        beta = 1.57

        if model == 1:  # model 1
            alpha, beta = random.PriorRand(alpha, beta)

        # get rate for given parameters
        rate = np.random.gamma(alpha, beta)

        return np.random.poisson(rate)
示例#5
0
class MySort:
    """A crappy sorting class"""

    # initialization method for Random class
    def __init__(self, seed=5555):
        self.m_random = Random(seed)

    # sorts array using bubble sort
    def BubbleSort(self, array):
        n = len(array)

        for i in range(n):
            # Create a flag that will allow the function to
            # terminate early if there's nothing left to sort
            already_sorted = True

            # Start looking at each item of the list one by one,
            # comparing it with its adjacent value. With each
            # iteration, the portion of the array that you look at
            # shrinks because the remaining items have already been
            # sorted.
            for j in range(n - i - 1):
                if array[j] > array[j + 1]:
                    # If the item you're looking at is greater than its
                    # adjacent value, then swap them
                    array[j], array[j + 1] = array[j + 1], array[j]

                    # Since you had to swap two elements,
                    # set the `already_sorted` flag to `False` so the
                    # algorithm doesn't finish prematurely
                    already_sorted = False

            # If there were no swaps during the last iteration,
            # the array is already sorted, and you can terminate
            if already_sorted:
                break

        return array

    # sorts array using insertion sort
    def InsertionSort(self, array):
        # Loop from the second element of the array until
        # the last element
        for i in range(1, len(array)):
            # This is the element we want to position in its
            # correct place
            key_item = array[i]

            # Initialize the variable that will be used to
            # find the correct position of the element referenced
            # by `key_item`
            j = i - 1

            # Run through the list of items (the left
            # portion of the array) and find the correct position
            # of the element referenced by `key_item`. Do this only
            # if `key_item` is smaller than its adjacent values.
            while j >= 0 and array[j] > key_item:
                # Shift the value one position to the left
                # and reposition j to point to the next element
                # (from right to left)
                array[j + 1] = array[j]
                j -= 1

            # When you finish shifting the elements, you can position
            # `key_item` in its correct location
            array[j + 1] = key_item

        return array

    # sorts array using quicksort
    def QuickSort(self, array):
        # If the input array contains fewer than two elements,
        # then return it as the result of the function
        if len(array) < 2:
            return array

        low, same, high = [], [], []

        # Select your `pivot` element randomly
        pivot = array[int(self.m_random.rand() * len(array))]

        for item in array:
            # Elements that are smaller than the `pivot` go to
            # the `low` list. Elements that are larger than
            # `pivot` go to the `high` list. Elements that are
            # equal to `pivot` go to the `same` list.
            if item < pivot:
                low.append(item)
            elif item == pivot:
                same.append(item)
            elif item > pivot:
                high.append(item)

        # The final result combines the sorted `low` list
        # with the `same` list and the sorted `high` list
        return self.QuickSort(low) + same + self.QuickSort(high)

    # sorts array using default Python sort
    def DefaultSort(self, array):
        array.sort()

        return array
示例#6
0
    nTotal = 0

    # accepted values
    Xaccept = []
    Yaccept = []

    # reject values
    Xreject = []
    Yreject = []

    # sample number
    isample = []
    # calculated values of Pi (per sample)
    calcPi = []

    random = Random()

    idraw = max(1, int(Nsample) / 100000)
    for i in range(0, Nsample):
        X = random.rand()
        Y = random.rand()

        nTotal += 1
        if (X * X + Y * Y <= 1):  #accept if inside
            nAccept += 1
            if (i % idraw == 0):
                Xaccept.append(X)
                Yaccept.append(Y)
        else:  # reject if outside
            if (i % idraw == 0):
                Xreject.append(X)
示例#7
0
    if '-Ntoss' in sys.argv:
        p = sys.argv.index('-Ntoss')
        Nt = int(sys.argv[p + 1])
        if Nt > 0:
            Ntoss = Nt
    if '-Nexp' in sys.argv:
        p = sys.argv.index('-Nexp')
        Ne = int(sys.argv[p + 1])
        if Ne > 0:
            Nexp = Ne
    if '-output' in sys.argv:
        p = sys.argv.index('-output')
        OutputFileName = sys.argv[p + 1]
        doOutputFile = True

    # class instance of our Random class using seed
    random = Random(seed)

    if doOutputFile:
        outfile = open(OutputFileName, 'w')
        for e in range(0, Nexp):
            for t in range(0, Ntoss):
                outfile.write(str(random.Categorical(prob1, prob2)) + " ")
            outfile.write(" \n")
        outfile.close()
    else:
        for e in range(0, Nexp):
            for t in range(0, Ntoss):
                print(random.Categorical(prob1, prob2), end=' ')
            print(" ")
示例#8
0
import numpy as np
import sys
import matplotlib.pyplot as plt

sys.path.append(".")
from python.Random import Random

#global variables
bin_width = 0.
Xmin = -3.
Xmax = 2.
random = Random()


# Normal distribution with mean zero and sigma = 1
# Note: multiply by bin width to match histogram
def Gaus(x):
    return (1. / np.sqrt(2. * np.arccos(-1))) * np.exp(-x * x / 2.)


def PlotGaus(x, bin_width):
    return bin_width * Gaus(x)


# Uniform (flat) distribution scaled to Gaussian max
# Note: multiply by bin width to match histogram
def Flat(x):
    return 1. / np.sqrt(2 * np.arccos(-1.))


def PlotFlat(x, bin_width):
示例#9
0
        p = sys.argv.index('-Ndice')
        Nd = int(sys.argv[p + 1])
        if Nd > 0:
            Ndice = Nd
    if '-Nexp' in sys.argv:
        p = sys.argv.index('-Nexp')
        Ne = int(sys.argv[p + 1])
        if Ne > 0:
            Nexp = Ne
    if '-output' in sys.argv:
        p = sys.argv.index('-output')
        OutputFileName = sys.argv[p + 1]
        doOutputFile = True

    # class instance of our Random class using seed
    random = Random(seed)

    if doOutputFile:
        outfile = open(OutputFileName, 'w')
        for e in range(0, Nexp):
            for t in range(0, Ndice):
                outfile.write(
                    str(random.Categorical(prob1, prob2, prob3, prob4, prob5))
                    + " ")
            outfile.write(" \n")
        outfile.close()
    else:
        for e in range(0, Nexp):
            for t in range(0, Ndice):
                print(random.Categorical(prob1, prob2, prob3, prob4, prob5),
                      end=' ')
示例#10
0
    if '-Ntoss' in sys.argv:
        p = sys.argv.index('-Ntoss')
        Nt = int(sys.argv[p + 1])
        if Nt > 0:
            Ntoss = Nt
    if '-Nexp' in sys.argv:
        p = sys.argv.index('-Nexp')
        Ne = int(sys.argv[p + 1])
        if Ne > 0:
            Nexp = Ne
    if '-output' in sys.argv:
        p = sys.argv.index('-output')
        OutputFileName = sys.argv[p + 1]
        doOutputFile = True

    # class instance of our Random class using seed
    random = Random(seed)

    if doOutputFile:
        outfile = open(OutputFileName, 'w')
        for e in range(0, Nexp):
            for t in range(0, Ntoss):
                outfile.write(str(random.Bernoulli(prob)) + " ")
            outfile.write(" \n")
        outfile.close()
    else:
        for e in range(0, Nexp):
            for t in range(0, Ntoss):
                print(random.Bernoulli(prob), end=' ')
            print(" ")