def enclose(function, variable, name=None): """Given a function f(x0, x1...), write a function f(x0, x1...) - variable. For example, if the argument function corresponds to 'x**2 + sin(y) + c', the return function will correspond to '(x**2 + sin(y) + c) - variable'. This is useful if, for instance, we have a model with a constraint or objective function g(x0, x1...) and need to introduce a new variable which is constrained to be equal to the value of g. If the argument function is linear (that is, an instance of functions.Linear,) so is the return function. Otherwise, the first and second derivative caches are preserved, and the first derivative wrt variable is filled in. """ if isinstance(function, Linear): new_coefficients = {'variable': -1} new_coefficients.update(function.coefficients) return Linear(new_coefficients, name=name) new_expr = '(%s) - %s' % (function.math, variable) new_variables = function.variables.copy() new_variables.add(variable) new_function = Function(new_expr, variables=new_variables, first_derivatives=function._first_derivatives, second_derivatives=function._second_derivatives, name=name) new_function._first_derivatives[variable] = '-1.' return new_function
def menu_linear(): global functions contexts.append("LIN") c = prompt("Coefficient", False, expect=float) f = Linear(c) remove_from_contexts("LIN") return f
def single_fva(model, variable, guess=None): """ Find min/max values of variable in model. The existing objective function is lost. """ extrema = [] # Minimize variable, then -1.0*variable # (maximizing it.) for sign in (1., -1.): model.objective_function = Linear({variable: sign}, name='fva_%s' % variable) model.compile() if getattr(model, 'repeated_solve_max_attempts', 1) > 1: model.repeated_solve(guess, model.repeated_solve_max_iter, model.repeated_solve_max_attempts) else: model.solve(guess) # Record the flux, not the objective function value extrema.append(sign * model.obj_value) return extrema
def add_conservation_functions(self, *species_list): """ Add functions to the network representing net species production. The functions give the sum of fluxes to each species. Functions are of the form '_conservation_' + species_id. Species should be specified by id, to ensure that the resulting function name is a valid python/C variable id. If the species list is not specified, conservation functions will be created for all species in the associated network. """ if not species_list: species_list = self.species.keys() stoichiometry_terms = {species: {} for species in species_list} for rxn in self.reactions: for reactantId, coefficient in rxn.stoichiometry.items(): # I forget what types 'coefficient' might be, so # perhaps overzealously I cast it to a float. # Note that this will fail for exotic, non-numerical # stoichiometry coefficients. (We could handle these # in principle at the cost of detecting them and # using nonlinear conservation constraints.) if reactantId in stoichiometry_terms: stoichiometry_terms[reactantId][rxn.id] = float( coefficient) for species, terms in stoichiometry_terms.items(): fid = '_conservation_' + species if terms: func = Linear(terms, name=fid) self.constraints.set(fid, func) return stoichiometry_terms
# F, mask = cv2.findFundamentalMat(inliers_f1,inliers_f2,cv2.FM_LMEDS) # draw epipolar lines # img_f1, img_f2 = EpipolarLines(img_orig1, inliers_f1, img_orig2, inliers_f2, F) # These are the possible transforms between frame1 (f1) and frame2 (f2) T = getCameraPose(F, K, points_f1, points_f2) # X: 4 sets of 3D points (from triangulation) from 4 camera poses X = np.zeros((4, l, 3)) # Calculate point positions T_1 = np.identity(4)[:3, :] # 3x4 for i in range(4): T_2 = T[0, :, :] X[i, :, :] = Linear(K, T_1, T_2, points_f1, points_f2) # Final transform and points in front of camera R_final, t_final, X_final = checkCheirality(T, X) R_final, t_final = recoverPose(None, K, points_f1, points_f2) # Calculate pose of the camera relative to the first camera pose pose.update2D(R_final, t_final) # print(t_final) # pose.update(R_final, t_final) # break result = cv2.resize(img, (800, 600), interpolation=cv2.INTER_AREA) cv2.imshow('Img', result) if cv2.waitKey(1) & 0xFF == ord('q'):
def Setup_Grid(i, alpha, matrix_type): """ This routine sets up the grid(mesh). The grid is the uniform mesh with uniformly distributed data. Be aware that the number of data need to be entered manually input: i the index of grid size alpha matrix_type, if is the original version, enter 'Original'. There is no return of this routine """ #from dvector import dvector from quick_d import dvector from h_boundaries import hboundaries from tempfile import TemporaryFile global u, rhs, h, cexact, x1, y1 n = 2**i + 1 # Find the spacing h = 1 / float(n - 1) # Set the mesh grid with data structure of nnumpy array x1, y1 = np.meshgrid(np.arange(0, 1 + h, h), np.arange(0, 1 + h, h)) nodes = np.vstack([x1.ravel(), y1.ravel()]).T # Set the initerior of the mesh intx, inty = np.meshgrid(np.arange(h, 1, h), np.arange(h, 1, h)) intnodes = np.vstack([intx.ravel(), inty.ravel()]).T # Set the uniformly distributed data datax = np.linspace(0, 1.0, 100) datay = np.linspace(0, 1.0, 100) dataX, dataY = np.meshgrid(datax, datay) data = Linear(dataX, dataY) data = data.flatten() coordx = dataX.flatten() coordy = dataY.flatten() Coord = zip(coordx, coordy) # Set the exact solution of c, g1, g2, w on every node cexact = Linear c = cexact(x1, y1).flatten() g1exact = Xlinear g1 = g1exact(x1, y1).flatten() g2exact = Ylinear g2 = g2exact(x1, y1).flatten() wexact = Zero w = -alpha * wexact(x1, y1).flatten() #w = w/float(alpha) print 'START' start = time.time() # Import the dvector #drhs = TemporaryFile() dvector = dvector(Coord, data, nodes, n) / float(len(Coord)) dvector = np.reshape(dvector, (n, n))[1:-1, 1:-1] done = time.time() elapsed = done - start print(elapsed) print 'FINISH' # import the boundary condition to form rhs vector h1 = hboundaries(alpha, h, n, nodes, intnodes, c, g1, g2, w)[0] h2 = hboundaries(alpha, h, n, nodes, intnodes, c, g1, g2, w)[1] h3 = hboundaries(alpha, h, n, nodes, intnodes, c, g1, g2, w)[2] h4 = hboundaries(alpha, h, n, nodes, intnodes, c, g1, g2, w)[3] h1 = np.reshape(h1, (n - 2, n - 2)) h2 = np.reshape(h2, (n - 2, n - 2)) h3 = np.reshape(h3, (n - 2, n - 2)) h4 = np.reshape(h4, (n - 2, n - 2)) # Initial guess u = np.zeros((4, n, n)) u[0] = sin_soln(x1, y1) u[1] = sin_soln(x1, y1) u[2] = sin_soln(x1, y1) u[3] = sin_soln(x1, y1) if matrix_type == 'Original': rhs = np.zeros((4, n, n)) rhs[0][1:-1, 1:-1] = -h4 rhs[1][1:-1, 1:-1] = -h2 rhs[2][1:-1, 1:-1] = -h3 rhs[3][1:-1, 1:-1] = dvector - h1 else: rhs = np.zeros((4, n, n)) rhs[3][1:-1, 1:-1] = -np.sqrt(alpha) * h4 rhs[1][1:-1, 1:-1] = -h2 / float(np.sqrt(alpha)) rhs[2][1:-1, 1:-1] = -h3 / float(np.sqrt(alpha)) rhs[0][1:-1, 1:-1] = dvector - h1
def __init__(self, base_model, N, split_parameters=(), save_objectives=True): """Create a new optimization problem from images of a base problem. If save_objectives is true, the base model's objective function will be preserved for each image as a variable constrained to equal that image's objective function value, and a default objective function which is the sum of the individual objective functions will be applied. The replica model is not compiled by default. The parameters of the base problem will not be split across images, except for those listed in split_parameters. """ NonlinearModel.__init__(self) # Compile the base problem to ensure all its derivative # caches are populated and its variable list is up-to-date. base_model.compile() self.base_variables = base_model.variables _base_variable_set = set(self.base_variables) # Parameters are constant across all images. shared_parameters = { k: v for k, v in base_model.parameters.iteritems() if k not in split_parameters } self.parameters = shared_parameters # Set up a template for constraints requiring # variables to equal the objective value for each image if save_objectives: template = enclose(base_model.objective_function, 'objective_value') # Note enclose() will copy # the derivative caches automatically, # and they will be preserved by template.substitute() # below. objectives_by_image = [] for i in xrange(N): name_map = {n: self.metaname(n, i) for n in self.base_variables} name_map.update({p: self.metaname(p, i) for p in split_parameters}) # Initialize local parameters self.parameters.update({ name_map[p]: base_model.parameters[p] for p in split_parameters }) # Translate all constraints for key, g0 in base_model.constraints.items(): new_name = self.metaname(g0.name, i) new_key = self.metaname(key, i) gi = g0.substitute(name_map, new_name) self.constraints.set(new_key, gi) self.set_bound(new_key, base_model.get_bounds(key)) # Apply all variable bounds for v in self.base_variables: self.set_bound(self.metaname(v, i), base_model.get_bounds(v)) # Set up a new variable equal to this image's original # objective function. if save_objectives: this_objective = self.metaname('objective_value', i) objectives_by_image.append(this_objective) name_map['objective_value'] = this_objective new_id = self.metaname('objective_constraint', i) local_constraint = template.substitute(name_map, new_id) self.constraints.set(new_id, local_constraint) self.set_bound(new_id, 0.) # Set the combined objective function, if desired if save_objectives: coefficients = dict.fromkeys(objectives_by_image, 1.) self.objective_function = Linear( coefficients, name='combined_objective_function') self.N = N
def forward(self, x: Tensor, h_prev: Tensor): h_curr = self.hidden_unit(x, h_prev) h_curr1, h_curr2 = Split(h_curr, times=2)() y = Linear(h_curr1, self.W_hy, self.b_y)() return y, h_curr2