Example #1
0
 def test_add_projection(self):
     db = "cinema.db"
     projections = Projections(db)
     #projections.add_projection(1, "3D", "2014-04-01", "19:10")
     #projections.add_projection(1, "2D", "2014-04-01", "19:00")
     #projections.add_projection(1, "4DX", "2014-04-02", "21:00")
     #projections.add_projection(3, "2D", "2014-04-05", "20:00")
     #projections.add_projection(2, "3D", "2014-04-02", "22:00")
     #projections.add_projection(2, "2D", "2014-04-02", "19:30")
     #TESTING SHOW PROJECTIONS
     projections.show_movie_projection(2)
def optimize(numRemainingPos, remainingPosList, remainingSal, excludedNames,
             numLineups, salariesDir, projDir):
    proj = Projections(salariesDir, projDir)
    data = proj.data
    clean_data = cleanProj(data)
    removePlayers(clean_data, excludedNames)
    clean_data.reset_index(drop=True, inplace=True)
    posIndicies = getPosIndices(clean_data, remainingPosList)

    # Get matrix of all combinations of Player Identities
    indexCombinations = np.array(np.meshgrid(*posIndicies)).T.reshape(
        -1, numRemainingPos)
    rangeSeries = np.array(range(indexCombinations.shape[0]))
    rangeMatrix = np.repeat(rangeSeries,
                            numRemainingPos).reshape(-1, numRemainingPos)
    rangeMatrixMult = rangeMatrix * len(clean_data)
    indexIncrements = (rangeMatrixMult + indexCombinations).reshape(-1)
    playerIdentities = np.zeros(indexCombinations.shape[0] * len(clean_data))
    np.add.at(playerIdentities, indexIncrements, 1)
    playerIdentities = playerIdentities.reshape(-1, len(clean_data))

    # Get matrix of projections
    pointProjections = clean_data["Fpts"].to_numpy(copy=True)
    pointProjMatrix = np.repeat(pointProjections.reshape(1, -1),
                                indexCombinations.shape[0],
                                axis=0)
    salaries = clean_data["Salary"].to_numpy(copy=True)
    salaryMatrix = np.repeat(salaries.reshape(1, -1),
                             indexCombinations.shape[0],
                             axis=0)

    # Create masks for salary and duplicate (no more than 1 of each player) restraints
    lineupSalMatrix = salaryMatrix * playerIdentities
    lineupSalTotals = np.sum(lineupSalMatrix, axis=1)
    salMask = np.where(lineupSalTotals <= remainingSal, 1, 0)
    maxOccurrenceArray = np.amax(playerIdentities, axis=1)
    dupeMask = np.where(maxOccurrenceArray > 1, 0, 1)

    # Apply masks to projection totals
    lineupProjMatrix = pointProjMatrix * playerIdentities
    lineupProjTotals = np.sum(lineupProjMatrix, axis=1) * salMask * dupeMask
    lineupOrder = np.argsort(lineupProjTotals)
    playerNames = clean_data["Name"]
    lineupNum = numLineups
    for lineupInd in lineupOrder[-lineupNum:]:
        print("Lineup " + str(lineupNum) + ":")
        lineupPlayerIndices = np.argsort(
            playerIdentities[lineupInd, :])[-numRemainingPos:]
        for playerIndex in lineupPlayerIndices:
            print(playerNames[playerIndex])
        print(str(lineupProjTotals[lineupInd]) + " Fpts")
        print("\n")
        lineupNum -= 1
def comp_sketch(matrix, objective, load_N=False, save_N=False, N_dir='../N_file/', **kwargs):
    """
    Given matrix A, the function comp_sketch computes a sketch for A and performs further operations on PA.
    It returns the total running time and the desired quantity.

    parameter:
        matrix: a RowMatrix object storing the matrix [A b]
        objective: either 'x' or 'N'
            'x': the function returns the solution to the problem min_x || PA[:,:-1]x - PA[:,-1] ||_2
            'N': the function returns a square matrix N such that PA[:,:-1]*inv(N) is a matrix with orthonormal columns
        load_N: load the precomputed N matrices if possible (it reduces the actual running time for sampling sketches)
        save_N: save the computed N matrices for future use
        sketch_type: either 'projection' or 'sampling'
        projection_type: cw, gaussian, rademacher or srdht
        c: projection size
        s: sampling size (for sampling sketch only)
        k: number of independent trials to run
    """

    sketch_type = kwargs.get('sketch_type')

    if not os.path.exists(N_dir):
        os.makedirs(N_dir)

    if objective == 'x':
        
        if sketch_type == 'projection':
            projection = Projections(**kwargs)
            t = time.time()
            x = projection.execute(matrix, 'x', save_N)
            t = time.time() - t

            if save_N:
                logger.info('Saving N matrices from projections!')
                N = [a[0] for a in x]
                x = [a[1] for a in x]
                # saving N
                filename = N_dir + 'N_' + matrix.name + '_projection_' + kwargs.get('projection_type') + '_c' + str(int(kwargs.get('c'))) + '_k' + str(int(kwargs.get('k')))+ '.dat'
                data = {'N': N, 'time': t}
                pickle_write(filename,data)
 
        elif sketch_type == 'sampling':
            s = kwargs.get('s')
            new_N_proj = 0
            N_proj_filename = N_dir + 'N_' + matrix.name + '_projection_' + kwargs.get('projection_type') + '_c' + str(int(kwargs.get('c'))) + '_k' + str(int(kwargs.get('k'))) +'.dat'

            if load_N and os.path.isfile(N_proj_filename):
                logger.info('Found N matrices from projections, loading them!')
                N_proj_filename = N_dir + 'N_' + matrix.name + '_projection_' + kwargs.get('projection_type') + '_c' + str(int(kwargs.get('c'))) + '_k' + str(int(kwargs.get('k'))) +'.dat'
                result = pickle_load(N_proj_filename)
                N_proj = result['N']
                t_proj = result['time']
            else: # otherwise, compute it
                t = time.time()
                projection = Projections(**kwargs)
                N_proj = projection.execute(matrix, 'N')
                t_proj = time.time() - t
                new_N_proj = 1

            sampling = Sampling(N=N_proj)
            t = time.time()
            x = sampling.execute(matrix, 'x', s, save_N )
            t = time.time() - t + t_proj

            if save_N and new_N_proj:
                logger.info('Saving N matrices from projections!')
                #filename = N_dir + 'N_' + matrix.name + '_projection_' + kwargs.get('projection_type') + '_c' + str(int(kwargs.get('c'))) + '_k' + str(int(kwargs.get('k'))) + '.dat'
                data = {'N': N_proj, 'time': t_proj}
                pickle_write(N_proj_filename,data)

            if save_N:
                logger.info('Saving N matrices from sampling!')
                N = [a[0] for a in x]
                x = [a[1] for a in x]
                filename = N_dir + 'N_' + matrix.name + '_sampling_s' + str(int(kwargs.get('s'))) + '_' + kwargs.get('projection_type') + '_c' + str(int(kwargs.get('c'))) + '_k' + str(int(kwargs.get('k'))) + '.dat'
                data = {'N': N, 'time': t}
                pickle_write(filename,data)

        else:
            raise ValueError('Please enter a valid sketch type!')
        return x, t

    elif objective == 'N':
        if sketch_type == 'projection':
            N_proj_filename = N_dir + 'N_' + matrix.name + '_projection_' + kwargs.get('projection_type') + '_c' + str(int(kwargs.get('c'))) + '_k' + str(int(kwargs.get('k'))) + '.dat'

            if load_N and os.path.isfile(N_proj_filename):
                logger.info('Found N matrices from projections, loading them!')
                result = pickle_load(N_proj_filename)
                N = result['N']
                t = result['time']
            else:
                t = time.time()
                projection = Projections(**kwargs)
                N = projection.execute(matrix, 'N')
                t = time.time() - t

                if save_N:
                    logger.info('Saving N matrices from projections!')
                    data = {'N': N, 'time': t}
                    pickle_write(N_proj_filename,data)

        elif sketch_type == 'sampling':
            s = kwargs.get('s')
            new_N_proj = 0
            new_N_samp = 0

            N_samp_filename = N_dir + 'N_' + matrix.name + '_sampling_s' + str(int(kwargs.get('s'))) + '_' + kwargs.get('projection_type') + '_c' + str(int(kwargs.get('c'))) + '_k' + str(int(kwargs.get('k'))) + '.dat'
            N_proj_filename = N_dir + 'N_' + matrix.name + '_projection_' + kwargs.get('projection_type') + '_c' + str(int(kwargs.get('c'))) + '_k' + str(int(kwargs.get('k'))) + '.dat'

            if load_N and os.path.isfile(N_samp_filename):
                logger.info('Found N matrices from sampling, loading them!')
                result = pickle_load(N_samp_filename)
                N = result['N']
                t = result['time']

            elif load_N and os.path.isfile(N_proj_filename):
                logger.info('Found N matrices from projections, loading them!')
                result = pickle_load(N_proj_filename)
                N_proj = result['N']
                t_proj = result['time']

                sampling = Sampling(N=N_proj)
                t = time.time()
                N = sampling.execute(matrix, 'N', s)
                t = time.time() - t + t_proj
                new_N_samp = 1

            else:
                t = time.time()
                projection = Projections(**kwargs)
                N_proj = projection.execute(matrix, 'N')
                t_proj = time.time() - t
                new_N_proj = 1

                t = time.time()
                sampling = Sampling(N=N_proj)
                N = sampling.execute(matrix, 'N', s)
                t = time.time() - t + t_proj
                new_N_samp = 1

            if save_N and new_N_proj:
                logger.info('Saving N matrices from projections!')
                data = {'N': N_proj, 'time': t_proj}
                pickle_write(N_proj_filename,data)

            if save_N and new_N_samp:
                logger.info('Saving N matrices from sampling!')
                data = {'N': N, 'time': t}
                pickle_write(N_samp_filename,data)

        else:
            raise ValueError('Please enter a valid sketch type!')
        return N, t
    else:
        raise ValueError('Please enter a valid objective!')
from movies import Movies
from projections import Projections
from reservation import Reservation

db = "cinema.db"
movies = Movies(db)
projections = Projections(db)
reservation = Reservation(db)
reservation.clear_reservation_on_stratup()


def start_mess():
    start_message = "Hello, here is the cinema. You can \
use one of the the following commands:\
\n show_movies - print all movies ordered by rating\
\n show_movie_projections <movie_id> - \
print all projections of a given movie\
\n make_reservation\
\n cancel_reservation <name> - disintegrate given person's reservation\
\n exit\
\n help"

    return start_message


def print_func(set_obj):
    for row in set_obj:
        print(row)


def print_hall(matrix):
Example #5
0
__author__ = 'ap'

import mysql.connector

from shared.dfs_constants import DFSConstants
from projections import Projections
from models.defense_vs_position_manager import DefenseVsPositionManager


cnx = mysql.connector.connect(user='******', password='******', host='localhost', database='basketball_reference')
dvp_manager = DefenseVsPositionManager(cnx=cnx)
projections = Projections(cnx=cnx)

teams = []

cursor = cnx.cursor()
try:
	cursor.execute("select distinct team from game_totals_basic where season = 2013")
	for result in cursor:
		teams.append(result[0])

	for position in ["PG", "SG", "SF", "PF", "C"]:
		ranks = []
		for team in teams:
			dvp = dvp_manager.calculate_defense_vs_position(DFSConstants.FANTASY_POINTS, position, team, 2013, DFSConstants.FAN_DUEL)
			ranks.append((dvp, team))
			# rank = projections.calculate_defense_vs_position_ranking(DFSConstants.FANTASY_POINTS, position, team, 2013, DFSConstants.FAN_DUEL)

		# Sort the results in ascending order (lowest value at element 0).
		ranks.sort()
Example #6
0
 def initProjections(self):
     """ Initialize the projections object. """
     self.__projections = Projections(self._views, self.__nrBins)
 def test_projection_Gaussian_N(self):
     proj = Projections(projection_type='gaussian', sc=sc, c=1e2, k=3)
     N = proj.execute(self.matrix_Ab, 'N')
     self.assertEqual(len(N), 3)
     self.assertEqual(N[0].shape, (self.matrix_Ab.n, self.matrix_Ab.n))
 def test_projection_SRDHT_x(self):
     proj = Projections(projection_type='srdht', sc=sc, c=1e2)
     sol = proj.execute(self.matrix_Ab, 'x')
     self.assertEqual(len(sol[0]), self.matrix_Ab.n)
 def test_projection_Rademacher_x(self):
     proj = Projections(projection_type='rademacher', sc=sc, c=1e2)
     sol = proj.execute(self.matrix_Ab, 'x')
     self.assertEqual(len(sol[0]), self.matrix_Ab.n)
Example #10
0
 def test_projection_Gaussian_x(self):
     proj = Projections(projection_type='gaussian', sc=sc, c=1e2, k=3)
     sol = proj.execute(self.matrix_Ab, 'x')
     self.assertEqual(len(sol), 3)
     self.assertEqual(len(sol[0]), self.matrix_Ab.n)
Example #11
0
 def test_get_date_time(self):
     db = "cinema.db"
     projections = Projections(db)
     result = projections._get_movie_date_time(1)
     self.assertEqual(result, ("2014-04-01", "19:10"))