def euc_proj_descent(q, M, r, c, l, precision, T, rate=None, rate_type=None): if (q <= 1): print("Warning: Projected gradient methods only work when q>1") ind_map = np.asarray(np.matrix(r).transpose().dot(np.matrix(c))) P = deepcopy(ind_map) new_score = q_obj(q, P, M, l) scores = [] scores.append(new_score) best_score = new_score best_P = P count = 1 while count <= T: G = q_grad(q, P, M, l) if rate is None: P = proj.euc_projection( P - (math.sqrt(2 * math.sqrt(2) / T) / np.linalg.norm(G)) * G, r, c, precision) #Absolute horizon #P = proj.euc_projection(P - (math.sqrt(2./count)/np.linalg.norm(G))*G,r,c,precision) #Rolling horizon elif rate_type is "constant": P = proj.euc_projection(P - rate * G, r, c, precision) elif rate_type is "constant_length": P = proj.euc_projection(P - rate * np.linalg.norm(G) * G, r, c, precision) elif rate_type is "diminishing": P = proj.euc_projection(P - rate / math.sqrt(count) * G, r, c, precision) elif rate_type is "square_summable": P = proj.euc_projection(P - rate / count * G, r, c, precision) #Update score list new_score = q_obj(q, P, M, l) scores.append(new_score) #Keep track of the best solution so far if (new_score < best_score): best_score = new_score best_P = P count += 1 return best_P, scores
def check_seats_if_available(self, cursor, string): place = ast.literal_eval(string) proj = Projections.Projections(cursor) if self.check_seats_for_out_index(cursor, string) is True: if proj.seats[place[0]][place[1]] == 'x ': print("This seat is taken!") return False else: return True
def __init__(self, set_id = 0, in_collision = 0, breaks = 0, data = [], obj_data = DataModel.clsData()): if len(obj_data.data)==0: DataModel.clsData.__init__(self,set_id,in_collision,breaks,data) else: DataModel.clsData.__init__(self,obj_data.set_id,obj_data.in_collision,obj_data.breaks,obj_data.data) self.projections = Projections.clsProjectionOverAxis(self.data,self.word_ref_center,self.pi)
def Nesterov_grad(q, M, r, c, l, precision, T): if (q < 2): print("Warning: Nesterov's accelerated gradient only works when q>2") ind_map = np.matrix(r).transpose().dot(np.matrix(c)) P = deepcopy(ind_map) #Estimation of the gradient Lipschitz constant L = q / (l * (q - 1) * (q - 1)) new_score = q_obj(q, P, M, l) scores = [] scores.append(new_score) best_score = new_score best_Y = P #Negative cumulative weighted gradient sum grad_sum = np.zeros(P.shape) count = 1 while count <= T: G = q_grad(q, P, M, l) grad_sum -= count / 2 * G Y = proj.euc_projection(P - G / L, r, c, precision) Z = proj.Sinkhorn(np.multiply(ind_map, np.exp(grad_sum / L)), r, c, precision) P = (2 * Z + (count) * Y) / (count + 2) #Update score list new_score = q_obj(q, Y, M, l) scores.append(new_score) #Keep track of the best solution so far if (new_score < best_score): best_score = new_score best_Y = Y count += 1 return best_Y, scores
def checking_movie_for_spots(self, cursor, string): proj = Projections.Projections(cursor) proj.select_title(cursor, string) result = cursor.execute(''' SELECT id, movie_id, date_time, movie_type FROM Projections''') for row in result: if row['movie_id'] == int(string): print(str(row['id']) + ' - ' + row['date_time'] + ' (' + row['movie_type'] + ') ' + str(proj.spots) + " available spots")
def _generate_db_month_district(self, district=0): """ Filters the DB according to the district and generates a dictionary with the number of crimes by month and year, for each indicator. If district is set to zero, computes the total of all Chicago. As a note, it uses the following pd.datetime.strptime(str(int(month)).zfill(2)+str(year), '%m%Y') in order to create the index as a date type, making it easier to plot later. If there is no crime data, it sets the value Nan from numpy. Returns a a dictionary of the number of crimes :return data_ind """ Years = self.Year.unique() data_ind = pd.DataFrame(columns=('density', 'effectiveness', 'effect_by_sqm')) #CHicago considers the total information by month/year if district == 0: area = 0 for district in self.districts_contained: area += proj.PolygonProjection(du.get_polygon(district)).calculate_area_in_miles() for year in Years: data_district_year = self[self['Year'] == year] for month in range(1,13): data_district_month = data_district_year[data_district_year['Month'] == month] if len(data_district_month) == 0: data_ind.loc[ pd.datetime.strptime(str(int(month)).zfill(2)+str(year), '%m%Y')] =[np.nan, np.nan, np.nan] else: data_ind.loc[ pd.datetime.strptime(str(int(month)).zfill(2)+str(year), '%m%Y')] = [ len(data_district_month)/ area, len(data_district_month[data_district_month['Arrest'] == True])*1.0 / len(data_district_month), (len(data_district_month[data_district_month['Arrest'] == True])*1.0 / len(data_district_month['Arrest']))/area] #Other case, it computes the indicator of the inputted district else: for year in Years: data_district_year = self[(self['District'] == district) & (self['Year'] == year)] for month in range(1,13): data_district_month = data_district_year[data_district_year['Month'] == month] if len(data_district_month) == 0: data_ind.loc[ pd.datetime.strptime(str(int(month)).zfill(2)+str(year), '%m%Y')] =[np.nan, np.nan, np.nan] else: data_ind.loc[ pd.datetime.strptime(str(int(month)).zfill(2)+str(year), '%m%Y')] = [iu.get_density(polygon = du.get_polygon(district), ammount = len(data_district_month)), iu.effectiveness_police(data_district_month), iu.effectiveness_sq_mile(polygon = du.get_polygon(district), data =data_district_month)] return data_ind
def test_definition(self): #Correct input list of list or list of tuples (list of two elements) valid_input = [zip([1, 2, 3], [2, 3, 4]), zip((1, 2, 3), (2, 3, 4))] #Incorrect value 1, not list with 2 elements or another type invalid_input = [ [1, 2, 3], 2, 'a', ] #Incorrect value 2, list with more than 2 elements invalid_input2 = [zip([1, 2, 3], [2, 3, 4], [1, 1, 1])] for i in range(len(valid_input)): self.assertTrue(Projections.PolygonProjection(valid_input[i])) for i in range(len(invalid_input)): self.assertRaises(TypeError, Projections.PolygonProjection, invalid_input[i]) for i in range(len(invalid_input2)): self.assertRaises(ValueError, Projections.PolygonProjection, invalid_input2[i])
def __init__(self, f, gradf, s1, s2, r, x0, name): p = proj.NoProjection() super().__init__(f, gradf, p, p, s1, s2, r, x0, name)
import sqlite3 import Movies import Projections #import Reservations conn = sqlite3.connect("cinema.db") conn.row_factory = sqlite3.Row cursor = conn.cursor() proj = Projections.Projections(cursor) movie = Movies.Movies(cursor) #def give_up(): # print("You can give up if you want!") # give_up = input("Enter command for give up> ") # if give_up == "give up": # menu() #def menu(): # print(''' Welcome to your cinema! # Here are the things you can do: # 1. add_movie # 2. show_movies # 3. add_projection # 4. show_movie_projections <movie_id> # 5. show_movie_projections_by_date <movie_id> <date_time> # 6. make_reservation''') # command = input("Enter your choice: ") # return command #if __name__ == '__main__':
conts_time = fs[0::10]-fstar xconts = xs[0::10,:].transpose() def fMinusFStar(x): return f(x) - fstar vertices = np.array([[1, 0], [np.cos(2*np.pi/3), np.sin(2*np.pi/3)], [np.cos(4*np.pi/3), np.sin(4*np.pi/3)]]).T def toSimplex(x): return np.dot(vertices, x-xstar) # Parameters, simplex constrained projections lmax = 20 s = 1/lmax r = 3 p1 = proj.SimplexProjectionExpSort(dimension = d, epsilon = 0.3) p2 = proj.SimplexProjectionExpSort(dimension = d, epsilon = 0) s1 = s*p1.epsilon/(1+d*p1.epsilon) s2 = s # descent methods amd = ac.AcceleratedMethod(f, gradf, p1, p2, s1, s2, r, x0, 'accelerated descent') amddiv = ac.AcceleratedMethod(f, gradf, p1, p2, s1, s2, r, x0, 'accelelerated Euler descent', divergent=True) md = ac.MDMethod(f, gradf, p2, s2, x0, 'mirror descent') methods = [md, amd, amddiv, ] ms = range(len(methods)) # run the descent