class ActiveLearning(object): def __init__(self, experiment): self.experiment = experiment self.datasets = Datasets(experiment) self.budget = self.experiment.conf.budget self.iteration_number = 1 self.current_budget = self.budget self.previous_iteration = None self.current_iteration = None def runIterations(self): while True: try: self.runNextIteration() except (NoLabelAdded) as e: print e break def runNextIteration(self): self.current_iteration = Iteration( self.experiment, self.iteration_number, datasets=self.datasets, previous_iteration=self.previous_iteration, budget=self.current_budget) self.current_budget = self.current_iteration.runIteration() self.iteration_number += 1 self.current_iteration.previous_iteration = None self.previous_iteration = self.current_iteration def checkAnnotationQueriesAnswered(self): self.experiment.session.commit() return self.current_iteration.checkAnnotationQueriesAnswered()
class Main: def __init__(self, iterations): self._iterations = iterations self._iter = Iteration() def main(self): for i in range(self._iterations): self._iter.run() for i in self._iter.getSwarm(): print(i.fitness(), i.position)
def __init__(self, experiment, iteration_number, datasets = None, previous_iteration = None, budget = None): Iteration.__init__(self, experiment.conf, iteration_number, datasets = datasets, previous_iteration = previous_iteration, budget = budget, output_dir = experiment.getOutputDirectory()) self.experiment = experiment
def runNextIteration(self): self.current_iteration = Iteration( self.experiment, self.iteration_number, datasets=self.datasets, previous_iteration=self.previous_iteration, budget=self.current_budget) self.current_budget = self.current_iteration.runIteration() self.iteration_number += 1 self.current_iteration.previous_iteration = None self.previous_iteration = self.current_iteration
def runNextIteration(self, output_dir=None): self.current_iteration = Iteration( self.conf, self.iteration_number, datasets=self.datasets, previous_iteration=self.previous_iteration, budget=self.current_budget, output_dir=output_dir) self.current_budget = self.current_iteration.runIteration() self.iteration_number += 1 self.current_iteration.previous_iteration = None self.previous_iteration = self.current_iteration
class Iterations(object): def __init__(self, experiment): self.experiment = experiment self.datasets = Datasets(experiment) self.budget = self.experiment.conf.budget self.iteration_number = 1 self.current_budget = self.budget self.previous_iteration = None self.current_iteration = None def runIterations(self): while True: try: start = time.time() self.runNextIteration() print '%%%%%%%%%%%%%%%%% Iteration ', time.time() - start except (NoLabelAdded) as e: print e break def runNextIteration(self): self.current_iteration = Iteration( self.experiment, self.iteration_number, datasets=self.datasets, previous_iteration=self.previous_iteration, budget=self.current_budget) self.current_budget = self.current_iteration.runIteration() self.iteration_number += 1 self.current_iteration.previous_iteration = None self.previous_iteration = self.current_iteration
class ActiveLearning(object): def __init__(self, conf, datasets): self.conf = conf self.datasets = datasets self.budget = self.conf.budget self.iteration_number = 1 self.current_budget = self.budget self.previous_iteration = None self.current_iteration = None def runIterations(self, output_dir=None): while True: try: self.runNextIteration(output_dir) except (NoLabelAdded) as e: print e break def runNextIteration(self, output_dir=None): self.current_iteration = Iteration( self.conf, self.iteration_number, datasets=self.datasets, previous_iteration=self.previous_iteration, budget=self.current_budget, output_dir=output_dir) self.current_budget = self.current_iteration.runIteration() self.iteration_number += 1 self.current_iteration.previous_iteration = None self.previous_iteration = self.current_iteration
def printResultOfIteration(coeff_mat, b_vec, epoch=100): from Iteration import Iteration x_GS_vec = Iteration.GaussSeidelMethod(coeff_mat, b_vec) x_J_vec = Iteration.JacobiMethod(coeff_mat, b_vec) print() print(f"{'Result of Iteration':-^{50}}") print(f"x from Gauss-Seidel: {x_GS_vec}") print(f"{'x from Jacobi':>19}: {x_J_vec}") print() print("Check Result:") print(f"{'vector b':>16}: {b_vec}") print(f"matmul of A, xGS: {np.matmul(coeff_mat, x_GS_vec)}") print(f"matmul of A, xJ : {np.matmul(coeff_mat, x_J_vec)}") print() print(f"{'Print finished':-^{50}}") print()
def gen_new_it(pre, it): # Get correct file path ft = FileTree() path = f"{ft.get_its_num_dir(0, it)}" only_files = [f for f in listdir(path) if isfile(join(path, f))] it_file = "" for i in only_files: if pre in i: it_file = i break # Load file buffer with open(f"{path}/{it_file}", "rb") as f: It = pkl.load(f) # Get shapes results, nodes_discrete, No, Cu, num_div, sol_range, it_step = \ It.give_shapes() nodes_scaled, nodes_discrete, No, Cu = new_iteration( results, nodes_discrete, No, Cu, num_div, sol_range, it_step) New_It = Iteration("network_simulations_3D", It.sol_range, It.num_div, it_step + 1, nodes_scaled, nodes_discrete, Cu, No) New_It.save()
def __init__(self, iterations): self._iterations = iterations self._iter = Iteration()
# print(f"h target: {h_target}") # ----------------------------------------------------------------------------------------- # Iteration example # input 형식(matrix A, vector b) -> Ax = b 근사 A = np.array([[-4, 1, 1, 0], [1, -4, 0, 1], [2, 0, -4, 1], [0, 2, 1, -4]]) b_vec = np.array([0.75, 1.125, -1.5, -6]) # 사용법 x_GS_vec = Iteration.GaussSeidelMethod(A, b_vec) x_J_vec = Iteration.JacobiMethod(A, b_vec) # 결과 출력법 # Utils.printResultOfIteration(coeff_mat=A, b_vec=b_vec) # TODO n번째 yn구하기, vector input validation(list -> np.ndarray) # ----------------------------------------------------------------------------------------- # PDE(elliptic example) # input 형식: # (xrange, yrange, h, uL=None, uR=None, uB=None, uT=None, f=None, # un_axis=None, un=None, # for mixed boundary condition # boundary_type='Dirichlet')
def __PoissonEquationWithDirichlet(xrange, yrange, h, uL, uR, uB, uT, poisson_func): from Iteration import Iteration x_linspace = np.arange(xrange[0], xrange[1] + h, h) y_linspace = np.arange(yrange[0], yrange[1] + h, h) m = len(x_linspace) n = len(y_linspace) vec_len = (m - 2) * (n - 2) if type(uL) == int or float: # uL is a constant left_boundary_values = np.array([uL for _ in range(n - 2)]) else: # uL is a function left_boundary_values = np.array( [uL(x_linspace[0], y_linspace[j]) for j in range(1, n - 1)]) if type(uR) == int or type(uR) == float: # uR is a constant right_boundary_values = np.array([uR for _ in range(n - 2)]) else: # uR is a function right_boundary_values = np.array( [uR(x_linspace[-1], y_linspace[j]) for j in range(1, n - 1)]) if type(uB) == int or type(uB) == float: # uB is a constant bottom_boundary_values = np.array([uB for _ in range(m - 2)]) else: # uB is a function bottom_boundary_values = np.array( [uB(x_linspace[i], y_linspace[0]) for i in range(1, m - 1)]) if type(uT) == int or type(uT) == float: # uT is a constant top_boundary_values = np.array([uT for _ in range(m - 2)]) else: # uT is a function top_boundary_values = np.array( [uT(x_linspace[i], y_linspace[-1]) for i in range(1, m - 1)]) x_grid, y_grid = np.meshgrid(x_linspace[1:-1], y_linspace[1:-1]) # m-2 x n-2 x_coordinates = x_grid.ravel() y_coordinates = y_grid.ravel() # 경계보다 한칸 안에 있는 점들 indices left_inner_boundary_indices = np.squeeze( np.where(x_coordinates == x_linspace[1])) right_inner_boundary_indices = np.squeeze( np.where(x_coordinates == x_linspace[m - 2])) bottom_inner_boundary_indices = np.squeeze( np.where(y_coordinates == y_linspace[1])) top_inner_boundary_indices = np.squeeze( np.where(y_coordinates == y_linspace[n - 2])) # f(x,y) 넣어줌 b_vec = np.array([ pow(h, 2) * poisson_func(x_coordinates[i], y_coordinates[i]) for i in range(vec_len) ]) # boundary conditions 넣어줌 for j, left_index in enumerate(left_inner_boundary_indices): b_vec[left_index] -= left_boundary_values[j] for j, right_index in enumerate(right_inner_boundary_indices): b_vec[right_index] -= right_boundary_values[j] for i, bottom_index in enumerate(bottom_inner_boundary_indices): b_vec[bottom_index] -= bottom_boundary_values[i] for i, top_index in enumerate(top_inner_boundary_indices): b_vec[top_index] -= top_boundary_values[i] D = -4 * np.identity(m - 2) + np.eye(m - 2, k=-1) + np.eye(m - 2, k=1) I = np.identity(m - 2) A = np.block([[D if i == j else I for i in range(n - 2)] for j in range(n - 2)]) # A * u_vec = b_vec u_vec = Iteration.GaussSeidelMethod(coeff_mat=A, b_vec=b_vec) return u_vec
def __NeumannWithAxisY(xrange, yrange, h, un, poisson_func, uL=None, uR=None, uB=None, uT=None): # uT가 없다는 가정하에 작성 # un is a function of x from Iteration import Iteration x_linspace = np.arange(xrange[0], xrange[1] + h, h) y_linspace = np.arange(yrange[0], yrange[1] + h, h) m = len(x_linspace) n = len(y_linspace) vec_len = (m - 2) * (n - 1) if type(uL) == int or float: # uL is a constant left_boundary_values = np.array([uL for _ in range(n - 1)]) else: # uL is a function left_boundary_values = np.array( [uL(x_linspace[0], y_linspace[j]) for j in range(1, n)]) if type(uR) == int or type(uR) == float: # uR is a constant right_boundary_values = np.array([uR for _ in range(n - 1)]) else: # uR is a function right_boundary_values = np.array( [uR(x_linspace[-1], y_linspace[j]) for j in range(1, n)]) if type(uB) == int or type(uB) == float: # uB is a constant bottom_boundary_values = np.array([uB for _ in range(m - 2)]) else: # uB is a function bottom_boundary_values = np.array( [uB(x_linspace[i], y_linspace[0]) for i in range(1, m - 1)]) x_grid, y_grid = np.meshgrid(x_linspace[1:-1], y_linspace[1:]) # m-2 x n-1 x_coordinates = x_grid.ravel() y_coordinates = y_grid.ravel() # 경계보다 한칸 안에 있는 점들 indices left_inner_boundary_indices = np.squeeze( np.where(x_coordinates == x_linspace[1])) right_inner_boundary_indices = np.squeeze( np.where(x_coordinates == x_linspace[m - 2])) bottom_inner_boundary_indices = np.squeeze( np.where(y_coordinates == y_linspace[1])) # un 계산할 경계 indices top_boundary_indices = np.squeeze( np.where(y_coordinates == y_linspace[-1])) # f(x,y) 넣어줌 b_vec = np.array([ pow(h, 2) * poisson_func(x_coordinates[i], y_coordinates[i]) for i in range(vec_len) ]) # boundary conditions 넣어줌 for j, left_index in enumerate(left_inner_boundary_indices): b_vec[left_index] -= left_boundary_values[j] for j, right_index in enumerate(right_inner_boundary_indices): b_vec[right_index] -= right_boundary_values[j] for i, bottom_index in enumerate(bottom_inner_boundary_indices): b_vec[bottom_index] -= bottom_boundary_values[i] # 경계에서 근사치 빼줌 for top_index in top_boundary_indices: b_vec[top_index] -= 2 * h * un(x_coordinates[top_index]) D = -4 * np.identity(m - 2) + np.eye(m - 2, k=-1) + np.eye(m - 2, k=1) I = np.identity(m - 2) A = np.block([[ D if i == j else (2 * I if i == n - 3 and j == n - 2 else I) for i in range(n - 1) ] for j in range(n - 1)]) # A * u_vec = b_vec u_vec = Iteration.GaussSeidelMethod(coeff_mat=A, b_vec=b_vec) return u_vec
def ParabolicPDE(xrange, trange, initial_f, h, r=1, uL=None, uR=None, plot=False): # parabolic PDE: ut = uxx # crank-nicolson method from Iteration import Iteration if plot: pass if (type(uL) != (int or float)) or (type(uR) != (int or float)): raise Exception("uL or uR is function: not implemented yet") if r != 1: raise Exception("r != 1: not implemented yet") k = r * pow(h, 2) x_linspace = np.arange(xrange[0], xrange[1] + h, h) t_linspace = np.arange(trange[0], trange[1] + k, k) m = len(x_linspace) n = len(t_linspace) # TODO diff < e 등으로 처리해야할듯 ''' np.sin이 정확한 값을 뱉지를 않아서 예외처리 불가능. if uL != initial_f(x_linspace[0]) or uR != initial_f(x_linspace[-1]): print(uL, uR, initial_f(x_linspace[0]), initial_f(x_linspace[-1])) raise Exception("invalid boundary condition") ''' x_boundary = np.array([ uL if i == 0 else (uR if i == m - 1 else initial_f(x_linspace[i])) for i in range(m) ]) t_boundary = np.array([uL, uR]) result = list() result.append((t_linspace[0], x_boundary)) for time in t_linspace[1:]: b_vec = np.zeros(m - 2) next_f = np.zeros(m) # 다음 t에 나타날 f의 근사 next_f[0] = t_boundary[0] next_f[-1] = t_boundary[-1] # x boundary 빼줌 for i in range(1, m - 1): x_boundary_sum = x_boundary[i - 1] + x_boundary[i + 1] b_vec[i - 1] -= x_boundary_sum # t boundary 빼줌 for i in range(-1, 1): b_vec[i] -= t_boundary[i] D = -4 * np.identity(m - 2) + np.eye(m - 2, k=-1) + np.eye(m - 2, k=1) inner_next_f = Iteration.GaussSeidelMethod(coeff_mat=D, b_vec=b_vec) next_f[1:-1] = inner_next_f next_t_and_f = (time, next_f) result.append(next_t_and_f) x_boundary = next_f return result
def answerAnnotationQueries(self): if self.conf.auto: Iteration.answerAnnotationQueries(self)
from Newton import Newton, check_result from Iteration import Iteration, check_iteration from math import cos, sin, sqrt F1 = [lambda x, y: cos(x) + y - 1.5, lambda x, y: 2 * x - sin(y - 0.5) - 1] F_d1 = [[lambda x, y: -sin(x), lambda x, y: 1], [lambda x, y: 2, lambda x, y: -cos(y - 0.5)]] F2 = [lambda x, y: sin(x + y) - 1.5 * x + 1, lambda x, y: x**2 + y**2 - 1] F_d2 = [[lambda x, y: cos(x + y) - 1.5, lambda x, y: cos(x + y)], [lambda x, y: 2 * x, lambda x, y: 2 * y]] if __name__ == '__main__': result = Newton([3.4, 3.2], 0.001, F1, F_d1) result1 = Iteration([0.8, -0.4], 0.001, F2, F_d2)