def testSparseSorSolver_DivergenceExampleHighRelaxationRate(self):
        vector_b = vector.Vector(name="b", number_list=[-1, 7, -7])

        sparse_sor_solver = sparse_sor.SparseSorSolver(self.matrix_a, vector_b,
                                                       100, .0001, 30.0)

        self.assertEqual(sparse_sor_solver.stopping_reason,
                         sor_pb2.SorReturnValue.X_SEQUENCE_DIVERGENCE)
 def testZeroOnDiagonal(self):
     zero_diagonal_mat = sparse_matrix.SparseMatrix(
         dense_matrix=[[4, 1], [1, 0]])
     b_vector = vector.Vector(name="b", number_list=[2, 2])
     sparse_sor_solver = sparse_sor.SparseSorSolver(zero_diagonal_mat,
                                                    b_vector, 50, 10**-20,
                                                    1)
     self.assertEqual(sparse_sor_solver.stopping_reason,
                      sor_pb2.SorReturnValue.ZERO_ON_DIAGONAL)
    def testSparseSorSolverToProto(self):
        matrix_a = sparse_matrix.SparseMatrix(
            dense_matrix=[[3, -1, 1], [-1, 3, -1], [1, -1, 3]])

        vector_b = vector.Vector(name="b", number_list=[-1, 7, -7])

        sparse_sor_solver = sparse_sor.SparseSorSolver(matrix_a, vector_b, 10,
                                                       .0001, 1.0)
        solution_proto = sparse_sor_solver.to_proto()
        self.assertEqual(type(solution_proto), sor_pb2.SorReturnValue)
    def testIllConditionedHighRelaxation(self):
        matrix_ill_conditioned = sparse_matrix.SparseMatrix(
            dense_matrix=[[1.01, 1], [1, 1.01]])

        vector_ill_conditioned = vector.Vector(name="b", number_list=[2, 2])

        sparse_sor_solver = sparse_sor.SparseSorSolver(matrix_ill_conditioned,
                                                       vector_ill_conditioned,
                                                       50, 10**-20, 1.5)

        print(sparse_sor_solver)
Beispiel #5
0
def experiment_EffectOfDifferentTolerance(matrix, vector):
    """Calculate residual sum for a matrix with different relaxation rates.
  
  Args:
    matrix: A sparse_matrix.Matrix. This needs to be diagonally dominant.
    vector: A vector.Vector
    
  Returns: List of sum of residuals for different relaxation rates.
  """
    i = -1
    while (i > -22):
        sparse_sor_solver = sparse_sor.SparseSorSolver(matrix, vector, 50,
                                                       10**i, 1.0)
        print(sparse_sor_solver)
        i -= 4
    def testSparseSorSolver_SolvedExample(self):
        matrix_a = sparse_matrix.SparseMatrix(
            dense_matrix=[[3, -1, 1], [-1, 3, -1], [1, -1, 3]])

        vector_b = vector.Vector(name="b", number_list=[-1, 7, -7])

        sparse_sor_solver = sparse_sor.SparseSorSolver(matrix_a, vector_b, 10,
                                                       .0001, 1.0)

        expected = [1, 2, -2]

        self.assertTrue(
            all(
                almost_equal(*values)
                for values in zip(expected, sparse_sor_solver.x)))
Beispiel #7
0
def effect_relaxation_rate(matrix, vector, maxits=50):
    """Calculate stopping iterationa matrix with different relaxation rates.

  Args:
    matrix: A sparse_matrix.Matrix. This needs to be diagonally dominant.
    vector: A vector.Vector
    maxits: Max number of iterations

  Returns: List of sum of residuals for different relaxation rates.
  """
    i = 0.1
    results = []
    while (i < 2.01):
        sparse_sor_solver = sparse_sor.SparseSorSolver(matrix, vector, maxits,
                                                       2**-20, i)
        results.append(sparse_sor_solver.iteration)
        i += 0.01
    return (results)
    def testSparseSorSolver_MatrixProto(self):
        matrix_a_proto = sor_pb2.SparseMatrix(matrix_name="a",
                                              row_count=3,
                                              column_count=3)
        for i in range(0, 3):
            # This creates and returns a pointer to a sor_pb2.SparseValue message.
            value = matrix_a_proto.values.add()
            value.row_index = i
            value.column_index = i
            # This is just a made up float value.
            value.value = (i + 1) * 3.9

        matrix_a = sparse_matrix.SparseMatrix(matrix_a_proto)

        vector_b = vector.Vector(name="b", number_list=[2, 3, 4])

        sparse_sor_solver = sparse_sor.SparseSorSolver(matrix_a, vector_b, 10,
                                                       .0001, 1.0)

        self.assertEqual(sparse_sor_solver.stopping_reason,
                         sor_pb2.SorReturnValue.RESIDUAL_CONVERGENCE)
Beispiel #9
0
def generate_option_price_grid(timesteps, strike_price, h, k, sigma, r,
                               stock_price_array):
    """Generate the matrix of option prices for each price, timestep pair.

  Args:
    timesteps: The integer number of timesteps to run for.
    strike_price: The strike price of the option in question.
    h: h the number of intervals into which the price is broken.
    k: k the number of intervals into which each timestep is broken.
    sigma: The standard deviation
    r: The risk free rate.

  Returns:
    A list of lists matrix. The  rows are for different stock prices and the
        columns are the different timesteps.
  """
    option_price_grid = [[None for _ in range(h + 1)]
                         for _ in range(timesteps + 1)]
    # row is across prices columns are over time
    option_price_grid[0] = start_prices(strike_price, stock_price_array)
    # A matrix will have N-2 * N-2 elements. Of which only 3 * N-2 are populated
    A = sparse_matrix.SparseMatrix(
        dense_matrix=generate_black_scholes_matrix(h - 1, k, sigma, r))

    adjustment = generate_adjustment_term(strike_price, k, sigma, r)
    time_step = 1
    while time_step < (timesteps + 1):
        # Need to create a new list here to avoid Python list mutability.
        f_vector = option_price_grid[time_step - 1][:]
        # Need to adjust 1st element by adding adjustment term.
        f_vector[1] += adjustment
        f = vector.Vector(number_list=f_vector[1:-1])
        sparse_sor_solver = sparse_sor.SparseSorSolver(A, f, 100, .0001, 1.0)
        option_price_grid[time_step] = (
            [strike_price] + sparse_sor_solver.get_solution().values + [0])
        time_step += 1
    return option_price_grid
Beispiel #10
0
}).set_index('relaxation_rate')

pyplot.plot(table[:1.65])
pyplot.ylabel('Number of Iterations Run')
pyplot.xlabel('Relaxation Rate')
pyplot.legend(["diag_c", "diag_a", "diag_b", "positive_def"], loc=9, ncol=4)
pyplot.show()

# Print results to be added to assignment doc

print("------------------------------------------------------------------")
print("Show effect of setting relaxation rate set to out of bounds number")
print("------------------------------------------------------------------")

# Experiment to see effect of setting relaxation rate to out of bounds number
sparse_sor_solver_a = sparse_sor.SparseSorSolver(positive_definite_symmetric,
                                                 vector_b_1, 50, 10**-10, 20)

sparse_sor_solver_b = sparse_sor.SparseSorSolver(diag_dominant_a, vector_b_2,
                                                 50, 10**-10, 20)

sparse_sor_solver_c = sparse_sor.SparseSorSolver(diag_dominant_b, vector_b_3,
                                                 50, 10**-10, 20)

sparse_sor_solver_d = sparse_sor.SparseSorSolver(diag_dominant_c, vector_b_4,
                                                 50, 10**-10, 20)

print(sparse_sor_solver_a)
print(sparse_sor_solver_b)
print(sparse_sor_solver_c)
print(sparse_sor_solver_d)
""" Black-Scholes with Google stock options """
#! /usr/bin/python3
"""End to end demonstration script for sparse_sor."""
import data_io
import vector
import sparse_sor
import sparse_matrix
from proto_genfiles.protos import sor_pb2
import sys

if __name__ == "__main__":
    # Remove one for the program itself.
    args = len(sys.argv) - 1
    print("Number of additional command line args passed: %s" % args)
    # Default values
    input_filename = "nas_Sor.in"
    output_filename = "nas_Sor.out"
    if args > 2:
        raise Exception("Error: Too many command line args passed")
    elif args == 2:
        output_filename = sys.argv[2]
    if args >= 1:
        input_filename = sys.argv[1]
    print("Reading input data from file: %s" % input_filename)
    matrix_proto, vector_proto = data_io.read_input(input_filename)
    matrix_a = sparse_matrix.SparseMatrix(matrix_proto)
    vector_b = vector.Vector(vector_proto=vector_proto)
    solver = sparse_sor.SparseSorSolver(matrix_a, vector_b, 10, .0001, 1.0)
    solution_proto = solver.to_proto()
    print("Calculation complete. Writing solution to: %s" % output_filename)
    data_io.write_output(solution_proto, output_filename)
 def testSparseSorSolver_PositiveDefiniteRelaxationVeryHigh(self):
     sparse_sor_solver = sparse_sor.SparseSorSolver(
         self.positive_definite_symmetric, self.vector_b, 250, 10**-20, 1.9)
     print(sparse_sor_solver)
     self.assertEqual(sparse_sor_solver.stopping_reason,
                      sor_pb2.SorReturnValue.MAX_ITERATIONS_REACHED)
 def testSparseSorSolver_PositiveDefiniteRelaxationHigh(self):
     sparse_sor_solver = sparse_sor.SparseSorSolver(
         self.positive_definite_symmetric, self.vector_b, 250, 10**-20, 1.5)
     print(sparse_sor_solver)
     self.assertEqual(sparse_sor_solver.stopping_reason,
                      sor_pb2.SorReturnValue.RESIDUAL_CONVERGENCE)
 def testSparseSorSolver_ClassExample2RelaxationVeryHigh(self):
     sparse_sor_solver = sparse_sor.SparseSorSolver(self.matrix_a,
                                                    self.vector_b, 50,
                                                    10**-20, 1.9)
     self.assertEqual(sparse_sor_solver.stopping_reason,
                      sor_pb2.SorReturnValue.X_SEQUENCE_DIVERGENCE)
 def testSparseSorSolver_ClassExampleRelaxationHigh(self):
     sparse_sor_solver = sparse_sor.SparseSorSolver(self.matrix_a,
                                                    self.vector_b, 10,
                                                    10**-20, 1.5)
     self.assertEqual(sparse_sor_solver.stopping_reason,
                      sor_pb2.SorReturnValue.MAX_ITERATIONS_REACHED)