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 make_a_reservation(cursor, connection):
     seats = []
     username = input("Enter username > ")
     number_of_tickets = input("Enter the number of tickets > ")
     Movies.get_all(cursor, connection)
     movie_id = input("Choose a projection >")
     Projections.get_all_for(cursor, movie_id)
     projection_id = input("Enter the wanted projection")
     for x in range(1, int(number_of_tickets)+1):
         seats.append(Reservations.choose_seats(cursor, connection, projection_id))
     Reservations.print_reservation(cursor, username, movie_id, projection_id, seats)
     Reservations.confirm(cursor, connection, username, projection_id, seats)
Example #3
0
def main():
    connection = sqlite3.connect('cinema')
    connection.row_factory = sqlite3.Row
    cursor = connection.cursor()
    cursor.execute('''CREATE TABLE IF NOT EXISTS cinema(id INTEGER PRIMARY KEY,
    name TEXT)''')
    Projections.load_reservations()
    connection.commit()
    Reservations.create_database(connection, cursor)
    Projections.create_database(connection, cursor)
    Movies.create_database(connection, cursor)
    cinema = Cinema()
    cinema.main_menu(cursor, connection)
 def show_movie_projections(self, movie_id):
     spots_unavailable = Reservations.show_used_seats_on_each_projection(
         self.__conn)
     avail_sp = {}
     for x in spots_unavailable:
         avail_sp[x['projection_id']] = self.capacity - x['num']
     return {
         "projetions":
         Projections.show_movie_projections_by_movie_id(movie_id),
         "available_spots": avail_sp}
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 choose_seats(cursor, connection, projection_id):
     Projections.print_projection_seats(projection_id)
     row_and_col = input("Enter the row and the collum separated with \" , \" >")
     row_and_col = (row_and_col.split(","))
     Reservations.reserv_seat(cursor, connection, projection_id, row_and_col[0], row_and_col[1])
     return (row_and_col)
Example #7
0
 def choose_movie(cls, conn, movie_id):
     res = Projections.show_projections(conn, movie_id=movie_id)
     return res
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!')
 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)
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 #11
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 #12
0
 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)
Example #13
0
class ProjectionSimulator(object):
    """
    Simple class to simulate parallel-beam x-ray projections of a phantom. 
    Since the projections are usually obtained from a phantom, it's preferred
    (for convenience) to match the number of bins to the pixel size of the
    phantom. Otherwise, the phantom needs to be resized before being projected.
    If the reconstruction is performed using a binary system matrix, that
    matrix can be evaluated during the projection. 
    """
    def __init__(self, views, nrBins, phantom=None, start=0, stop=180):
        self.__phantom = phantom 
        self.__nrBins = nrBins
        self._views = views
        self._start = start 
        self._stop = stop
        self._angleInc = (stop-start)/float(views)
        self.__projections = None

    @property 
    def loadSize(self):
        return self._views

    @property 
    def phantom(self):
        return self.__phantom 

    @property 
    def projections(self):
        return self.__projections

    @property 
    def views(self):
        return self._views 

    def initProjections(self):
        """ Initialize the projections object. """
        self.__projections = Projections(self._views, self.__nrBins)

    def projectAll(self, start=0, stop=180):
        """ 
        Simulate a parallel-beam x-ray projection by summing up the phantom
        data matrix column wise, yielding a sinogram line. 
        To this end, the number of bins (that the phantom is projected onto)
        and the phantom pixel size should be equal. Otherwise, the phantom
        needs to be reshaped.
        """
        if self.readyForProjecting():
            for a in range(0, self._views):
                if a%25==0:
                    print "Projecting view " + str(a)
                self.computeOne(a)

    def computeOne(self, view):
        """
        Helper function. Performs a single projection.
        Required in ProjectionSimulatorHandler.process() to signal progress
        after a single projection. 

        :param      view | int 
        """
        rotPhantom = self.phantom.rotate(self._start - view*self._angleInc)
        self.__projections.project(view, rotPhantom)

    def ready(self):
        """
        Convenience method for checking prerequisites for projecting.

        :return     isReady | bool 
        """
        if self.phantom is None or self.projections is None: 
            return False
        if self.__nrBins != self.phantom.size:
            pass #TODO resize phantom
        return True
Example #14
0
 def initProjections(self):
     """ Initialize the projections object. """
     self.__projections = Projections(self._views, self.__nrBins)
Example #15
0
 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))
Example #16
0
 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)
Example #17
0
 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 #18
0
 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 #19
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 #20
0
 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))
Example #21
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"))