Example #1
0
def main():
  print "=======================Problem 1========================="
  Problem1.main()
  print "=======================Problem 2========================="
  Problem2.main()
  print "=======================Problem 3========================="
  Problem3.main()
  print "=======================Problem 4========================="
  Problem4.main()
 def test6(self):
     input = "https://www.netflix.com/watch/70152014?trackId=200257859"
     expected = [
         "https", "www.netflix.com", "watch/70152014?trackId=200257859"
     ]
     actual = Problem1.URLSplit(
         "https://www.netflix.com/watch/70152014?trackId=200257859")
     self.assertEqual(expected, actual)
def test_smallest_factor():
    assert p1.smallest_factor(1) == 1, "failed on 1"
    assert p1.smallest_factor(2) == 2, "failed on smallest prime number case"
    assert p1.smallest_factor(3) == 3, "failed on small prime number cases"
    assert p1.smallest_factor(
        4) == 2, "failed on smallest composite number case"
    assert p1.smallest_factor(6) == 2, "failed on small composite number cases"
    assert p1.smallest_factor(
        9) == 3, "failed when n is the square of prime number cases"
    assert p1.smallest_factor(
        16) == 2, "failed when n is the square of composite number cases"
    assert p1.smallest_factor(17) == 17, "failed on large prime number cases"
    assert p1.smallest_factor(
        18) == 2, "failed on large composite number cases"
Example #4
0
def problem1(input1, input2):
    # Put problem1 code here

    alphabet = "0 1 2 3 4 5 6 7 8 9".split()
    d = Problem1.gen_dfa(input2, alphabet)
    print("True means the number is not strongly divisible:",
          d.run_with_input_list(input1))
    d.print()
    return
Example #5
0
    def sample_posterior(self):
        """ sample the posterior distribution of the mortality probability """

        # find values of mortality probability at which the posterior should be evaluated
        self._mortalitySamples = np.random.uniform(low=CalibSets.POST_L,
                                                   high=CalibSets.POST_U,
                                                   size=CalibSets.POST_N)

        # create a multi cohort
        multiCohort = SurvivalCls.MultiCohort(
            ids=self._cohortIDs,
            mortality_probs=self._mortalitySamples,
            pop_sizes=[CalibSets.SIM_POP_SIZE] * CalibSets.POST_N)

        # simulate the multi cohort
        multiCohort.simulate(CalibSets.TIME_STEPS)

        # calculate the likelihood of each simulated cohort
        for cohort_id in self._cohortIDs:

            # get the average survival time for this cohort
            mean = multiCohort.get_cohort_mean_survival(cohort_id)
            #survivaltimes = multiCohort.get_survival_times(cohort_id)
            fiveyearlist = multiCohort.get_five_year_survival(cohort_id)
            fiveyearrate = sum(fiveyearlist) / CalibSets.OBS_N

            # construct a gaussian likelihood
            # with mean calculated from the simulated data and standard deviation from the clinical study.
            # evaluate this pdf (probability density function) at the mean reported in the clinical study.
            weight = stat.binom.pmf(k=CalibSets.OBS_FIVE_YEAR_RATE,
                                    n=CalibSets.OBS_N,
                                    p=fiveyearrate)

            # store the weight
            self._weights.append(weight)

        # normalize the likelihood weights
        sum_weights = np.sum(self._weights)
        self._normalizedWeights = np.divide(self._weights, sum_weights)

        # re-sample mortality probability (with replacement) according to likelihood weights
        self._mortalityResamples = np.random.choice(
            a=self._mortalitySamples,
            size=CalibSets.NUM_SIM_COHORTS,
            replace=True,
            p=self._normalizedWeights)

        # produce the list to report the results
        for i in range(0, len(self._mortalitySamples)):
            self._csvRows.append([
                self._cohortIDs[i], self._normalizedWeights[i],
                self._mortalitySamples[i]
            ])

        # write the calibration result into a csv file
        InOutSupport.write_csv('CalibrationResults.csv', self._csvRows)
 def test5(self):
     input = "https://cs-people.bu.edu/dharmesh/teaching/cs591_sp20/assignments/assignment6/"
     expected = [
         "https", "cs-people.bu.edu",
         "dharmesh/teaching/cs591_sp20/assignments/assignment6/"
     ]
     actual = Problem1.URLSplit(
         "https://cs-people.bu.edu/dharmesh/teaching/cs591_sp20/assignments/assignment6/"
     )
     self.assertEqual(expected, actual)
def apply_monte_carlo_simulation( costOfLiving , numTimes ):
    utilMap = UtilityMap()
    transitionModel = TransitionModel()
    rewardSet = RewardSet( costOfLiving )
    utilMap = Problem1.apply_value_iteration( utilMap , transitionModel , rewardSet )
    policy = utilMap.get_optimal_policy( transitionModel )
   
    rewards = []
    for _ in range( numTimes ):
        rewards.append( simulate_run( 2 , 3 , policy , rewardSet ) ) 
    return rewards
Example #8
0
    def simulate(self,
                 num_of_simulated_cohorts,
                 cohort_size,
                 time_steps,
                 cohort_ids=None):
        """ simulate the specified number of cohorts based on their associated likelihood weight
        :param num_of_simulated_cohorts: number of cohorts to simulate
        :param cohort_size: the population size of cohorts
        :param time_steps: simulation length
        :param cohort_ids: ids of cohort to simulate
        """
        # resample cohort IDs and mortality probabilities based on their likelihood weights
        # sample (with replacement) from indices [0, 1, 2, ..., number of weights] based on the likelihood weights
        sampled_row_indices = np.random.choice(a=range(0, len(self._weights)),
                                               size=num_of_simulated_cohorts,
                                               replace=True,
                                               p=self._weights)

        # use the sampled indices to populate the list of cohort IDs and mortality probabilities
        resampled_ids = []
        resampled_probs = []
        for i in sampled_row_indices:
            resampled_ids.append(self._cohortIDs[i])
            resampled_probs.append(self._mortalityProbs[i])

        # simulate the desired number of cohorts
        if cohort_ids is None:
            # if cohort ids are not provided, use the ids stored in the calibration results
            self._multiCohorts = SurvivalCls.MultiCohort(
                ids=resampled_ids,
                pop_sizes=[cohort_size] * num_of_simulated_cohorts,
                mortality_probs=resampled_probs)
        else:
            # if cohort ids are provided, use them instead of the ids stored in the calibration results
            self._multiCohorts = SurvivalCls.MultiCohort(
                ids=cohort_ids,
                pop_sizes=[cohort_size] * num_of_simulated_cohorts,
                mortality_probs=resampled_probs)

        # simulate all cohorts
        self._multiCohorts.simulate(time_steps)
Example #9
0
def apply_monte_carlo_simulation(costOfLiving, numTimes):
    utilMap = UtilityMap()
    transitionModel = TransitionModel()
    rewardSet = RewardSet(costOfLiving)
    utilMap = Problem1.apply_value_iteration(utilMap, transitionModel,
                                             rewardSet)
    policy = utilMap.get_optimal_policy(transitionModel)

    rewards = []
    for _ in range(numTimes):
        rewards.append(simulate_run(2, 3, policy, rewardSet))
    return rewards
Example #10
0
def problem1():
    import Problem1
    print "Solving Problem 1"
    answers = Problem1.solve()
    f = open("generated/P1-output.txt", "w")
    f.write("0.0000\n\n")
    prevPolicyStr = str(Problem1.get_optimal_policy(0))
    f.write(prevPolicyStr + "\n")
    for i in range(0, 8):
        f.write(str('{0:.4f}'.format(answers[i])) + "\n\n")
        nextPolicyStr = str(Problem1.get_optimal_policy(answers[i] - 0.0001))
        output = ""
        for i in range(len(nextPolicyStr)):
            if (nextPolicyStr[i] == prevPolicyStr[i]):
                output += nextPolicyStr[i]
            else:
                output += nextPolicyStr[i] + "*"

        f.write(output + "\n")
        prevPolicyStr = nextPolicyStr

    f.close()
    print "Finished Solving Problem 1"
def problem1():
    import Problem1
    print "Solving Problem 1"
    answers = Problem1.solve()
    f = open( "generated/P1-output.txt" , "w" )
    f.write( "0.0000\n\n" )
    prevPolicyStr = str(Problem1.get_optimal_policy( 0 ))
    f.write( prevPolicyStr + "\n" )
    for i in range(0,8):
        f.write( str('{0:.4f}'.format(answers[ i ])) + "\n\n" )
        nextPolicyStr = str(Problem1.get_optimal_policy( answers[ i ] - 0.0001 ))
        output = ""
        for i in range(len(nextPolicyStr)):
            if ( nextPolicyStr[ i ] == prevPolicyStr[ i ] ):
                output += nextPolicyStr[ i ]
            else:
                output += nextPolicyStr[ i ] + "*"
                
        f.write( output + "\n" )
        prevPolicyStr = nextPolicyStr
        
    f.close()
    print "Finished Solving Problem 1"
def solve():
    utilMap = UtilityMap()
    transitionModel = TransitionModel()
    rewardSet = RewardSet( -0.04 )
    utilMap = Problem1.apply_value_iteration( utilMap , transitionModel , rewardSet )
    
    rewards10 = apply_monte_carlo_simulation( -0.04 , 10 )
    print "10 run mean:", sum( rewards10 ) / 10.0
    print "10 run stddev:" , numpy.std( numpy.array( rewards10 ) )
    rewards100 = apply_monte_carlo_simulation( -0.04 , 100 )
    print "100 run mean:" , sum( rewards100 ) / 100.0
    print "100 run stddev:" , numpy.std( numpy.array( rewards100 ) )
    rewards1000 = apply_monte_carlo_simulation( -0.04 , 1000 )
    print "1000 run mean:" , sum( rewards1000 ) / 1000.0
    print "1000 run stddev:" , numpy.std( numpy.array( rewards1000 ) )
    return (utilMap , rewards10 , rewards100 , rewards1000)
Example #13
0
def solve():
    utilMap = UtilityMap()
    transitionModel = TransitionModel()
    rewardSet = RewardSet(-0.04)
    utilMap = Problem1.apply_value_iteration(utilMap, transitionModel,
                                             rewardSet)

    rewards10 = apply_monte_carlo_simulation(-0.04, 10)
    print "10 run mean:", sum(rewards10) / 10.0
    print "10 run stddev:", numpy.std(numpy.array(rewards10))
    rewards100 = apply_monte_carlo_simulation(-0.04, 100)
    print "100 run mean:", sum(rewards100) / 100.0
    print "100 run stddev:", numpy.std(numpy.array(rewards100))
    rewards1000 = apply_monte_carlo_simulation(-0.04, 1000)
    print "1000 run mean:", sum(rewards1000) / 1000.0
    print "1000 run stddev:", numpy.std(numpy.array(rewards1000))
    return (utilMap, rewards10, rewards100, rewards1000)
                  zeros(upper_bound+1 - lower_bound)]

    for N in N_values:  # Loop as required by problem
        max_error = [0, 0, 0]  # Used store the maximum error of each interpolation
        max_x = [0, 0, 0]  # Used to store the abscicas at which the maximum error occurs

        # Generating the ordinates and absciccas

        interval = [-5, 5]
        spacing = 10 / N
        points = [interval[0] + spacing / 2 + spacing * m for m in range(N)]  # creates the absiccas
        values = [f(x) for x in points]  # creates the ordinates

        # Newton approximation:

        newton_poly = pb1.newton_interpolation(values, points)  # This gives us our newton_polynomial

        # Newton with Chebyshev zeros:

        cheb_zeros = pb2.chebyshev(-5, 5, N)  # Retrieves the Chebyshev zeros
        cheb_values = [f(x) for x in cheb_zeros]  # Retrieves the ordinates for the Chebyshev zeros
        cheb_newton_poly = pb1.newton_interpolation(cheb_values, cheb_zeros)  # Generates polynomial

        spline_coeff = pb3.SplineCoefficients(points, values)  # Returns our spline interpolation coefficients

        x = linspace(interval[0], interval[1], 1001)

        for i in range(1001):  # We loop through the 1001 points
            x_coord = x[i]
            # We evaluate all of the approximations at the iteration absica and store it in an array
 def test3(self):
     input = "https://www.facebook.com/messages/t/2972109159468035"
     expected = ["https", "www.facebook.com", "messages/t/2972109159468035"]
     actual = Problem1.URLSplit(
         "https://www.facebook.com/messages/t/2972109159468035")
     self.assertEqual(expected, actual)
 def test4(self):
     input = "https://github.com/sumara523/cs591_c2_assignment_6"
     expected = ["https", "github.com", "sumara523/cs591_c2_assignment_6"]
     actual = Problem1.URLSplit(
         "https://github.com/sumara523/cs591_c2_assignment_6")
     self.assertEqual(expected, actual)
Example #17
0
import Parameters as P
import Problem1 as Cls
import SupportSteadyState as Support

# create a cohort of patients for when the drug is not available
cohortFairCoin = Cls.Cohort(id=1,
                            pop_size=P.SIM_POP_SIZE,
                            mortality_prob=P.MORTALITY_PROB)
# simulate the cohort
FairCoinOutcome = cohortFairCoin.simulate(P.TIME_STEPS)

# create a cohort of patients for when the drug is available
cohortUnfairCoin = Cls.Cohort(id=2,
                              pop_size=P.SIM_POP_SIZE,
                              mortality_prob=P.MORTALITY_PROB *
                              P.DRUG_EFFECT_RATIO)
# simulate the cohort
UnfairCoinOutcome = cohortUnfairCoin.simulate(P.TIME_STEPS)

# print outcomes of each cohort
Support.print_outcomes(FairCoinOutcome, 'When coin is fair:')
Support.print_outcomes(UnfairCoinOutcome, 'When coin is unfair:')

# draw survival curves and histograms
Support.draw_survival_curves_and_histograms(FairCoinOutcome, UnfairCoinOutcome)

# print comparative outcomes
Support.print_comparative_outcomes(FairCoinOutcome, UnfairCoinOutcome)
import Problem1 as pb

unfair = pb.Cohort(2,1000,20,0.4)
print('Average reward for unfair coin is', unfair.get_average())
Example #19
0
import unittest
from Problem1 import * 

problem1 = Problem1()

class TestProblem1(unittest.TestCase):
    
    def test_returnType(self):
        self.assertTrue(type(problem1.urlSplit("a://b/c")) is list, "test_returnType should return a list")

    def test_inputWithAllComponents(self):
        self.assertEqual(problem1.urlSplit("https://www.google.com/some-path"), ["https", "www.google.com", "some-path"], "test_returnType should return all its components: http, www.google.com, some-path")
    
    def test_inputWithPathMissing(self):
        self.assertEqual(problem1.urlSplit("ftp://bu.edu/"), ["ftp", "bu.edu", ""], "test_returnType should return all its components: ftp, bu.edu, "" ")
    

if __name__ == "__main__":
    unittest.main()
 def test1(self):
     input = "https://www.google.com/some-path"
     expected = ["https", "www.google.com", "some-path"]
     actual = Problem1.URLSplit("https://www.google.com/some-path")
     self.assertEqual(expected, actual)
def containsError(sensorNetwork):
    '''Function check a dataset, log sensor errors and return a filtered dataset.
    
    Function accepts a dataset as a parameter.
    The dataset is examined for sensor errors.
    Identified errors are modified to -1, a non-valid float value.
    The Cluster and Sensor ID are logged to repair.
    The filtered dataset is returned.'''

    # Loop through entire dataset, sensor by sensor
    for i in range(0, 32):
        for j in range(0, 16):

            # If the sensor reports an error
            if sensorNetwork[i][j] == 'err':
                # Filter the error to -1 (non-valid float)
                sensorNetwork[i][j] = -1
                # Log the failed sensor information to the log file for repair.
                logger.info("SENSOR ERROR: Cluster: " + str(i + 1) +
                            ", Sensor: " + str(j + 1))

    # Return the filtered dataset
    return sensorNetwork


# Main - no specific main, not required in assessment. This block is demonstrating the functions
sensorData = dataGenerate.dataStreamGenerate()
corruptSensorData = corruptDataSet(sensorData)
dataStore.storeDataset(corruptSensorData)

filteredSensorData = containsError(corruptSensorData)
Example #22
0
import Problem1 as Cls
import scr.FigureSupport as figureLibrary

# expected rewards from 1000 games
setOfGames = Cls.SetOfGames(id=1, prob_head=0.45, n_games=1000)
outcomes = setOfGames.simulation()

##### Problem 1 #####
print("Estimated expected reward:", outcomes.get_ave_reward())
print("The 95% CI of expected reward:", outcomes.get_CI_reward(0.05))

print("Probability of loss in a single game:", outcomes.get_prob_loss())
print("The 95% CI of loss probability:", outcomes.get_CI_probLoss(0.05))

##### Problem 2 #####
print(
    "If we run our simulation many times, "
    "on average 95% of the confidence intervals generated will capture the true mean."
)

# plot
figureLibrary.graph_histogram(data=outcomes.get_rewards(),
                              title="Histogram of rewards",
                              x_label='Rewards',
                              y_label='Count')
 def test2(self):
     input = "ftp://bu.edu/"
     expected = ["ftp", "bu.edu", ""]
     actual = Problem1.URLSplit("ftp://bu.edu/")
     self.assertEqual(expected, actual)
if __name__ == "__main__":

    N = 9  # number of points
    interval = [-5, 5]
    cheb_zeros = chebyshev(interval[0], interval[1],
                           N)  # retrieve the chebyshev zeros
    values = [f(x) for x in cheb_zeros]  # calculate the function for the zeros

    print("The interpolation points are as follows:")
    print(cheb_zeros)

    print("Respectively, the function value at these points are:")
    print(values)

    P = pb1.newton_interpolation(values, cheb_zeros)
    X = cheb_zeros

    print("This gives the following interpolation polynomial:")
    pb1.print_polynomial(P, X)

    max_diff = 0
    max_x = 0
    poly_values = zeros(1001)
    x = linspace(interval[0], interval[1], 1001)

    for i in range(1001):
        x_coord = x[i]
        y_coord = pb1.get_value_of_polynomial(P, X, x_coord)
        fx = f(x_coord)
        if abs(fx - y_coord) > max_diff:
Example #25
0
# -*- coding: utf-8 -*-
__author__ = 'Vietworm'
import Problem1
import Problem2

"""Problem 1:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""

if Problem1.sumMultiples() == 233168:
    print "Problem 1 solved!"

"""Problem 2:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
"""

if Problem2.sumFibonacci(4000000) == 4613732:
    print "Problem 2 solved!"