class Option_Price:
    energy_list: np.ndarray
    S = 50
    K = 50
    r = 0.05
    v = 0.5
    T = 1
    CorP = "C"
    Steps = 100
    samples = 10000

    def __init__(self):
        #steps and dimension
        self.ndim = self.Steps  #proxy for number of time steps, linearly the system in one dimensional
        self.samples = self.samples
        self.potential = Option(self.S, self.K, self.r, self.v, self.T,
                                self.CorP, self.Steps)
        #setting up the simulator
        self.mc = MC(self.potential, np.zeros(self.ndim), 1)
        #generating coords(normal random numbers)
        self.takestep = SimpleGaussian(42, self.ndim)
        self.mc.set_take_step(self.takestep)
        self.Recorded_Energy = RecordEnergyTimeSeries(1, 1)
        #collecting all energies of each simulation
        self.mc.add_action(self.Recorded_Energy)
        self.mc.run(self.samples)
        self.energy_list = np.array(
            self.Recorded_Energy.get_energy_time_series())
Ejemplo n.º 2
0
class TestRecordCoordsTimeSeries(unittest.TestCase):
    def setUp(self):
        self.bdim = 3
        self.origin: np.ndarray = [5, 6, 7]
        self.temp = 1
        self.potential = TestPotential()
        self.mc = MC(self.potential, self.origin, self.temp)
        self.nrsteps = 100

    def test_frequencies(self):
        self.step = NoTakeStep()
        self.mc.set_take_step(self.step)
        self.Record_Hist = RecordEnergyHistogram(0, 100, 50, 0)
        self.mc.add_action(self.Record_Hist)
        self.mc.run(self.nrsteps)
        #self.coords_list = np.array(self.Record_Coords.get_timeseries())
        ans = np.asarray(self.origin * self.nrsteps).reshape(self.nrsteps, -1)
        print(self.Record_Hist.get_histogram(),
              len(self.Record_Hist.get_histogram()))
Ejemplo n.º 3
0
class TestRecordCoordsTimeSeries(unittest.TestCase):
    
    def setUp(self):
        self.bdim = 3
        self.origin: np.ndarray= [5, 6, 7]
        self.temp = 1
        self.potential = NoPotential()
        self.mc = MC(self.potential, self.origin, self.temp)
        self.nrsteps = 5

    def test_frequencies(self) :
        self.step = NoTakeStep()
        self.mc.set_take_step(self.step)
        self.Record_Coords = RecordsCoordsTimeSeries(self.bdim, 1, 1)
        self.mc.add_action(self.Record_Coords)
        self.mc.run(self.nrsteps)
        self.coords_list = np.array(self.Record_Coords.get_timeseries())
        ans = np.asarray(self.origin*self.nrsteps).reshape(self.nrsteps, -1)
        np.allclose(self.coords_list, ans)
Ejemplo n.º 4
0
class TestTakeStepProbability(unittest.TestCase):
    def setUp(self):
        self.ndim = 42
        self.k = 100
        self.bdim = 2
        self.origin = np.zeros(self.ndim)
        self.potential = Harmonic(self.origin, self.k, self.bdim)
        self.potential_pattern = Harmonic(self.origin, self.k, self.bdim)
        self.temp = 1
        self.nr_steps = 10000
        self.mc = MC(self.potential, self.origin, self.temp)
        self.mc_pattern = MC(self.potential_pattern, self.origin, self.temp)

    def test_frequencies(self):
        self.tsA = GaussianCoordsDisplacement(42, 1, self.ndim)
        self.tsA_pattern = GaussianCoordsDisplacement(42, 1, self.ndim)
        self.tsB = GaussianCoordsDisplacement(44, 2, self.ndim)
        self.tsB_pattern = GaussianCoordsDisplacement(44, 2, self.ndim)
        self.step = TakeStepProbability(42)
        self.step.add_step(self.tsA, 1)
        self.step.add_step(self.tsB, 3)
        self.step_pattern = TakeStepPattern()
        self.step_pattern.add_step(self.tsA_pattern, 1)
        self.step_pattern.add_step(self.tsB_pattern, 3)
        freqA = 1 / (1 + 3)
        freqB = 1 - freqA
        self.mc.set_take_step(self.step)
        self.mc.run(self.nr_steps)
        self.mc_pattern.set_take_step(self.step_pattern)
        self.mc_pattern.run(self.nr_steps)
        print(self.tsA.get_count(), self.tsB.get_count())
        self.assertAlmostEqual(freqA,
                               self.tsA.get_count() / self.nr_steps,
                               delta=1e-2)
        self.assertAlmostEqual(freqB,
                               self.tsB.get_count() / self.nr_steps,
                               delta=1e-2)
        self.assertAlmostEqual(freqA,
                               self.tsA_pattern.get_count() / self.nr_steps,
                               delta=1e-2)
        self.assertAlmostEqual(freqB,
                               self.tsB_pattern.get_count() / self.nr_steps,
                               delta=1e-2)
Ejemplo n.º 5
0
class ComputePi(object):
    def __init__(self, ndim=2, nsamples=1e4):
        #
        self.ndim = ndim
        self.nsamples = nsamples
        #
        self.radius = 44
        self.potential = nullpotential  #NullPotential()
        self.mc = MC(self.potential, np.ones(ndim), 1)
        self.step = UniformRectangularSampling(42, self.radius)
        self.mc.set_take_step(self.step)
        self.mc.set_report_steps(0)
        self.conftest_check_spherical_container = CheckSphericalContainerConfig(
            self.radius)
        #no problem till here
        self.mc.add_conf_test(self.conftest_check_spherical_container)
        self.mc.set_print_progress(False)
        self.mc.run(nsamples)
        self.p = self.mc.get_accepted_fraction()
        self.pi = get_pi(self.p, self.ndim)
Ejemplo n.º 6
0
class IsingMetropolisMonteCarlo(MC):
    """ Single flip montecarlo runner for the ising model

    """
    def __init__(self,
                 potential,
                 initial_coords,
                 temperature,
                 niter,
                 hEmin=0,
                 hEmax=100,
                 hbinsize=0.01,
                 radius=2.5,
                 acceptance=0.5,
                 adjustf=0.9,
                 adjustf_niter=1e4,
                 adjustf_navg=100,
                 bdim=3,
                 single=False,
                 seeds=None):
        #calling the base class
        hEmin = 0
        print("initial", hEmin)
        super(IsingMetropolisMonteCarlo,
              self).__init__(potential, initial_coords, temperature)
        random.seed(10)
        #initial_coords = random.randint(2,
        #                                size=(N, N),
        #                                dtype=bool)  # we're starting
        # with a random initial configuration

        # define the monte carlo runner with
        # the potential function , initial coordinates and temperature
        #ising_model = IsingModel(N, N)
        self.mc = MC(potential, initial_coords, temperature)
        # add the step type
        #self.take_step = IsingFlip(10, N, N)
        seeds = range(np.iinfo(np.int32).max)
        # accept test
        self.accepttest = MetropolisTest(seeds)
        self.mc.take_steps = SimpleGaussian(43, 4)
        self.conftest = CheckSphericalContainer(radius, bdim)
        print("Here", self.mc.take_steps)
        # action
        self.binsize = hbinsize
        # record_energy
        print("min1", hEmin, "max1", hEmax)
        self.histogram = RecordEnergyHistogram(hEmin, hEmax, self.binsize,
                                               adjustf_niter)

        #self.action = RecordEnergyTimeSeries(record_every, stepskip)
        self.config = 0

        self.mc.set_take_step(self.mc.take_steps)
        self.mc.add_accept_test(self.accepttest)
        self.mc.add_action(self.histogram)
        self.mc.add_conf_test(self.conftest)
        self.mc.set_report_steps(adjustf_niter)
        self.nsteps = niter

    def run(self):
        """ Runs the Monte Carlo simulation
        """
        #print(self.nsteps)
        #print(self.mc.trial_coords)
        self.mc.run(self.nsteps)

    def get_et_series(self):
        """ gets the array of energies at every iteration
        """
        return np.array(self.action.get_energy_time_series())

    def set_control(self, c):
        """
        sets the temperature or whichever control parameter that takes
        the role of the temperature, such as the stifness of an harmonic
        """
        self.temperature = c

    def get_stepsize(self):
        return self.step.get_stepsize()

    def dump_histogram(self, fname):
        """write histogram to fname"""
        Emin, Emax = self.histogram.get_bounds_val()
        histl = self.histogram.get_histogram()
        hist = np.array(histl)
        Energies, step = np.linspace(Emin,
                                     Emax,
                                     num=len(hist),
                                     endpoint=False,
                                     retstep=True)
        assert (abs(step - self.binsize) < self.binsize / 100)
        np.savetxt(fname, np.column_stack((Energies, hist)), delimiter='\t')
        mean, variance = self.histogram.get_mean_variance()
        return mean, variance

    def get_histogram(self):
        """returns a energy list and a histogram list"""
        Emin, Emax = self.histogram.get_bounds_val()
        histl = self.histogram.get_histogram()
        hist = np.array(histl)
        Energies, step = np.linspace(Emin,
                                     Emax,
                                     num=len(hist),
                                     endpoint=False,
                                     retstep=True)
        mean, variance = self.histogram.get_mean_variance()
        assert (abs(step - self.binsize) < self.binsize / 100)
        return Energies, hist, mean, variance

    def show_histogram(self):
        """shows the histogram"""
        hist = self.histogram.get_histogram()
        val = [i * self.binsize for i in xrange(len(hist))]
        plt.hist(val, weights=hist, bins=len(hist))
        plt.show()