signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def draw360_to_texture(self, cubetexture, **kwargs): | assert self.camera.projection.aspect == <NUM_LIT:1.> and self.camera.projection.fov_y == <NUM_LIT> <EOL>if not isinstance(cubetexture, TextureCube):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>old_rotation = self.camera.rotation<EOL>self.camera.rotation = self.camera.rotation.to_euler(units='<STR_LIT>')<EOL>... | Draw each visible mesh in the scene from the perspective of the scene's camera and lit by its light, and
applies it to each face of cubetexture, which should be currently bound to an FBO. | f14856:c0:m5 |
def create_opengl_object(gl_gen_function, n=<NUM_LIT:1>): | handle = gl.GLuint(<NUM_LIT:1>)<EOL>gl_gen_function(n, byref(handle)) <EOL>if n > <NUM_LIT:1>:<EOL><INDENT>return [handle.value + el for el in range(n)] <EOL><DEDENT>else:<EOL><INDENT>return handle.value<EOL><DEDENT> | Returns int pointing to an OpenGL texture | f14857:m0 |
def vec(data, dtype=float): | gl_types = {float: gl.GLfloat, int: gl.GLuint}<EOL>try:<EOL><INDENT>gl_dtype = gl_types[dtype]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if gl_dtype == gl.GLuint:<EOL><INDENT>for el in data:<EOL><INDENT>if el < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><D... | Makes GLfloat or GLuint vector containing float or uint args.
By default, newtype is 'float', but can be set to 'int' to make
uint list. | f14857:m1 |
def pairwise(iterable): | a, b = itertools.tee(iterable)<EOL>next(b, None)<EOL>return zip(a, b)<EOL> | s -> (s0,s1), (s1,s2), (s2, s3), ... | f14859:m0 |
def struct_to_ndarray(array): | return array.view(array.dtype[<NUM_LIT:0>]).reshape((array.shape[<NUM_LIT:0>], -<NUM_LIT:1>))<EOL> | Turns returns a view of a structured array as a regular ndarray. | f14859:m1 |
def calculate_normals(vertices): | verts = np.array(vertices, dtype=float)<EOL>normals = np.zeros_like(verts)<EOL>for start, end in pairwise(np.arange(<NUM_LIT:0>, verts.shape[<NUM_LIT:0>] + <NUM_LIT:1>, <NUM_LIT:3>)):<EOL><INDENT>vecs = np.vstack((verts[start + <NUM_LIT:1>] - verts[start], verts[start + <NUM_LIT:2>] - verts[start])) <EOL>vecs /= np.li... | Return Nx3 normal array from Nx3 vertex array. | f14859:m3 |
def notify(self): | self._requires_update = True<EOL> | Flags Observer to perform update() at proper time. | f14860:c2:m1 |
def on_change(self): | pass<EOL> | Callback for if change detected. Meant to be overridable by subclasses. | f14860:c2:m2 |
def __init__(self, indices=None, **kwargs): | <EOL>super(VAO, self).__init__(**kwargs)<EOL>self.id = create_opengl_object(gl.glGenVertexArrays if platform != '<STR_LIT>' else gl.glGenVertexArraysAPPLE)<EOL>self.n_verts = None<EOL>self.drawfun = self._draw_arrays<EOL>self.__element_array_buffer = None<EOL>self.element_array_buffer = indices<EOL> | OpenGL Vertex Array Object. Sends array data in a Vertex Buffer to the GPU. This data can be accessed in
the vertex shader using the 'layout(location = N)' header line, where N = the index of the array given the VAO.
Example: VAO(vertices, normals, texcoords):
Fragshader:
layout(location = 0) in vec3 vertexCoord;
... | f14863:c0:m0 |
def assign_vertex_attrib_location(self, vbo, location): | with vbo:<EOL><INDENT>if self.n_verts:<EOL><INDENT>assert vbo.data.shape[<NUM_LIT:0>] == self.n_verts<EOL><DEDENT>else:<EOL><INDENT>self.n_verts = vbo.data.shape[<NUM_LIT:0>]<EOL><DEDENT>gl.glVertexAttribPointer(location, vbo.data.shape[<NUM_LIT:1>], gl.GL_FLOAT, gl.GL_FALSE, <NUM_LIT:0>, <NUM_LIT:0>)<EOL>gl.glEnableVe... | Load data into a vbo | f14863:c0:m5 |
def __init__(self, file_name): | self.file_name = file_name<EOL>self.bodies = read_wavefront(file_name)<EOL>self.textures = {}<EOL> | Reads Wavefront (.obj) files created in Blender to build ratcave.graphics Mesh objects.
:param file_name: .obj file to read (assumes an accompanying .mtl file has the same base file name.)
:type file_name: str
:return:
:rtype: WavefrontReader | f14865:c0:m0 |
def get_mesh(self, body_name, **kwargs): | body = self.bodies[body_name]<EOL>vertices = body['<STR_LIT:v>']<EOL>normals = body['<STR_LIT>'] if '<STR_LIT>' in body else None<EOL>texcoords = body['<STR_LIT>'] if '<STR_LIT>' in body else None<EOL>mesh = Mesh.from_incomplete_data(vertices=vertices, normals=normals, texcoords=texcoords, **kwargs)<EOL>uniforms = kwar... | Builds Mesh from geom name in the wavefront file. Takes all keyword arguments that Mesh takes. | f14865:c0:m1 |
def __init__(self, **kwargs): | super(UniformCollection, self).__init__()<EOL>for key, value in iteritems(kwargs):<EOL><INDENT>self.data[key] = value<EOL><DEDENT> | Returns a dict-like collection of arrays that can copy itself to shader programs as GLSL Uniforms.
Uniforms can be thought of as pipes to the program on the graphics card. Variables set in UniformCollection can
be directly used in the grpahics card.
Example::
uniforms = Unifor... | f14866:c1:m0 |
def send(self): | for name, array in iteritems(self):<EOL><INDENT>shader_id = c_int(<NUM_LIT:0>)<EOL>gl.glGetIntegerv(gl.GL_CURRENT_PROGRAM, byref(shader_id))<EOL>if shader_id.value == <NUM_LIT:0>:<EOL><INDENT>raise UnboundLocalError("""<STR_LIT>""")<EOL><DEDENT>try:<EOL><INDENT>loc, shader_id_for_array = array.loc<EOL>if shader_id.valu... | Sends all the key-value pairs to the graphics card.
These uniform variables will be available in the currently-bound shader. | f14866:c1:m3 |
@property<EOL><INDENT>def uniforms(self):<DEDENT> | self.update()<EOL>return self._uniforms<EOL> | The dict-like collection of uniform values. To send data to the graphics card, simply add it as a key-value pair.
Example::
mesh.uniforms['diffuse'] = 1., 1., 0. # Will sends a 3-value vector of floats to the graphics card, when drawn. | f14866:c3:m1 |
def __init__(self, vert='<STR_LIT>', frag='<STR_LIT>', geom='<STR_LIT>', lazy=False): | self.id = gl.glCreateProgram() <EOL>self.is_linked = False<EOL>self.is_compiled = False<EOL>self.vert = vert<EOL>self.frag = frag<EOL>self.geom = geom<EOL>self.lazy = lazy<EOL>if not self.lazy:<EOL><INDENT>self.compile()<EOL><DEDENT> | GLSL Shader program object for rendering in OpenGL.
To activate, call the Shader.bind() method, or pass it to a context manager (the 'with' statement).
Examples and inspiration for shader programs can found at https://www.shadertoy.com/.
Args:
- vert (str): The vertex shader program string
- frag (str): The frag... | f14866:c4:m0 |
def bind(self): | if not self.is_linked:<EOL><INDENT>if not self.is_compiled:<EOL><INDENT>self.compile()<EOL><DEDENT>self.link()<EOL><DEDENT>super(self.__class__, self).bind()<EOL> | Activate this Shader, making it the currently-bound program.
Any Mesh.draw() calls after bind() will have their data processed by this Shader. To unbind, call Shader.unbind().
Example::
shader.bind()
mesh.draw()
shader.unbind()
.. note:: Shader.bind() and Sh... | f14866:c4:m2 |
@classmethod<EOL><INDENT>def from_file(cls, vert, frag, **kwargs):<DEDENT> | vert_program = open(vert).read()<EOL>frag_program = open(frag).read()<EOL>return cls(vert=vert_program, frag=frag_program, **kwargs)<EOL> | Reads the shader programs, given the vert and frag filenames
Arguments:
- vert (str): The filename of the vertex shader program (ex: 'vertshader.vert')
- frag (str): The filename of the fragment shader program (ex: 'fragshader.frag')
Returns:
- shader (Shader): The Shader using these files. | f14866:c4:m3 |
def link(self): | gl.glLinkProgram(self.id)<EOL>link_status = c_int(<NUM_LIT:0>)<EOL>gl.glGetProgramiv(self.id, gl.GL_LINK_STATUS, byref(link_status))<EOL>if not link_status:<EOL><INDENT>gl.glGetProgramiv(self.id, gl.GL_INFO_LOG_LENGTH, byref(link_status)) <EOL>buffer = create_string_buffer(link_status.value) <EOL>gl.glGetProgramInfoL... | link the program, making it the active shader.
.. note:: Shader.bind() is preferred here, because link() Requires the Shader to be compiled already. | f14866:c4:m5 |
@abc.abstractmethod<EOL><INDENT>def collides_with(self, xyz):<DEDENT> | pass<EOL> | Returns True if 3-value coordinate 'xyz' is inside the mesh. | f14868:c0:m0 |
def __init__(self, mesh, **kwargs): | self.mesh = mesh<EOL>self.collision_radius = np.linalg.norm(mesh.vertices[:, :<NUM_LIT:3>], axis=<NUM_LIT:1>).max()<EOL> | Parameters
----------
mesh: Mesh instance
kwargs
Returns
------- | f14868:c1:m0 |
def collides_with(self, xyz): | return np.linalg.norm(xyz - self.mesh.position_global) < self.collision_radius<EOL> | Returns True if 3-value coordinate 'xyz' is inside the mesh's collision cube. | f14868:c1:m1 |
def __init__(self, mesh, up_axis='<STR_LIT:y>'): | self.mesh = mesh<EOL>self.up_axis = up_axis<EOL>self._collision_columns = self._non_up_columns[up_axis]<EOL>self.collision_radius = np.linalg.norm(self.mesh.vertices[:, self._collision_columns], axis=<NUM_LIT:1>).max()<EOL> | Parameters
----------
mesh: Mesh instance
up_axis: ('x', 'y', 'z'): Which direction is 'up', which won't factor in the distance calculation.
Returns
------- | f14868:c2:m0 |
def __init__(self, id=None, name='<STR_LIT>', width=<NUM_LIT>, height=<NUM_LIT>, data=None, mipmap=False, **kwargs): | super(Texture, self).__init__(**kwargs)<EOL>self._slot = next(self._slot_counter)<EOL>if self._slot >= self.max_texture_limit:<EOL><INDENT>raise MemoryError("<STR_LIT>")<EOL><DEDENT>self.name = name<EOL>self.mipmap = mipmap<EOL>if id != None:<EOL><INDENT>self.id = id<EOL>self.data = data <EOL><DEDENT>else:<EOL><INDENT... | 2D Color Texture class. Width and height can be set, and will generate a new OpenGL texture if no id is given. | f14869:c0:m0 |
@property<EOL><INDENT>def slot(self):<DEDENT> | return self._slot<EOL> | The texture's ActiveTexture slot. | f14869:c0:m5 |
@property<EOL><INDENT>def max_texture_limit(self):<DEDENT> | max_unit_array = (gl.GLint * <NUM_LIT:1>)()<EOL>gl.glGetIntegerv(gl.GL_MAX_TEXTURE_IMAGE_UNITS, max_unit_array)<EOL>return max_unit_array[<NUM_LIT:0>]<EOL> | The maximum number of textures available for this graphic card's fragment shader. | f14869:c0:m8 |
def _genTex2D(self): | gl.glTexImage2D(self.target0, <NUM_LIT:0>, self.internal_fmt, self.width, self.height, <NUM_LIT:0>, self.pixel_fmt, gl.GL_UNSIGNED_BYTE, <NUM_LIT:0>)<EOL> | Creates an empty texture in OpenGL. | f14869:c0:m9 |
def _apply_filter_settings(self): | <EOL>if self.mipmap:<EOL><INDENT>gl.glTexParameterf(self.target, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR_MIPMAP_LINEAR)<EOL><DEDENT>else:<EOL><INDENT>gl.glTexParameterf(self.target, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR)<EOL><DEDENT>gl.glTexParameterf(self.target, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR)<EOL>gl.glTexPar... | Applies some hard-coded texture filtering settings. | f14869:c0:m11 |
def attach_to_fbo(self): | gl.glFramebufferTexture2DEXT(gl.GL_FRAMEBUFFER_EXT, self.attachment_point, self.target0, self.id, <NUM_LIT:0>)<EOL> | Attach the texture to a bound FBO object, for rendering to texture. | f14869:c0:m12 |
@classmethod<EOL><INDENT>def from_image(cls, img_filename, mipmap=False, **kwargs):<DEDENT> | img = pyglet.image.load(img_filename)<EOL>tex = img.get_mipmapped_texture() if mipmap else img.get_texture()<EOL>gl.glBindTexture(gl.GL_TEXTURE_2D, <NUM_LIT:0>)<EOL>return cls(id=tex.id, data=tex, mipmap=mipmap, **kwargs)<EOL> | Uses Pyglet's image.load function to generate a Texture from an image file. If 'mipmap', then texture will
have mipmap layers calculated. | f14869:c0:m13 |
def __init__(self, name='<STR_LIT>', *args, **kwargs): | try:<EOL><INDENT>super(TextureCube, self).__init__(name=name, *args, **kwargs)<EOL><DEDENT>except gl.lib.GLException as exception:<EOL><INDENT>if self.height != self.width:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>raise exception<EOL><DEDENT><DEDENT> | the Color Cube Texture class. | f14869:c1:m0 |
def _genTex2D(self): | for face in range(<NUM_LIT:6>):<EOL><INDENT>gl.glTexImage2D(self.target0 + face, <NUM_LIT:0>, self.internal_fmt, self.width, self.height, <NUM_LIT:0>,<EOL>self.pixel_fmt, gl.GL_UNSIGNED_BYTE, <NUM_LIT:0>)<EOL><DEDENT> | Generate an empty texture in OpenGL | f14869:c1:m2 |
def __init__(self, name='<STR_LIT>', *args, **kwargs): | super(DepthTexture, self).__init__(name=name, *args, **kwargs)<EOL> | the Color Cube Texture class. | f14869:c2:m0 |
def draw_vr_anaglyph(cube_fbo, vr_scene, active_scene, eye_poses=(<NUM_LIT>, -<NUM_LIT>)): | color_masks = [(True, False, False, True), (False, True, True, True)]<EOL>cam = vr_scene.camera<EOL>orig_cam_position = cam.position.xyz<EOL>for color_mask, eye_pos in zip(color_masks, eye_poses):<EOL><INDENT>gl.glColorMask(*color_mask)<EOL>cam.position.xyz = cam.model_matrix.dot([eye_pos, <NUM_LIT:0.>, <NUM_LIT:0.>, <... | Experimental anaglyph drawing function for VR system with red/blue glasses, used in Sirota lab.
Draws a virtual scene in red and blue, from subject's (heda trackers) perspective in active scene.
Note: assumes shader uses playerPos like ratcave's default shader
Args:
cube_fbo: texture frameBuffer object.
vr_sc... | f14870:m0 |
def _constraint_lb_and_ub_to_gurobi_sense_rhs_and_range_value(lb, ub): | if lb is None and ub is None:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>elif lb is None:<EOL><INDENT>sense = '<STR_LIT:<>'<EOL>rhs = float(ub)<EOL>range_value = <NUM_LIT:0.><EOL><DEDENT>elif ub is None:<EOL><INDENT>sense = '<STR_LIT:>>'<EOL>rhs = float(lb)<EOL>range_value = <NUM_LIT:0.><EOL><DEDENT>elif lb =... | Helper function used by Constraint and Model | f14873:m0 |
def solve_with_glpsol(glp_prob): | from swiglpk import glp_get_row_name, glp_get_col_name, glp_write_lp, glp_get_num_rows, glp_get_num_cols<EOL>row_ids = [glp_get_row_name(glp_prob, i) for i in range(<NUM_LIT:1>, glp_get_num_rows(glp_prob) + <NUM_LIT:1>)]<EOL>col_ids = [glp_get_col_name(glp_prob, i) for i in range(<NUM_LIT:1>, glp_get_num_cols(glp_prob)... | Solve glpk problem with glpsol commandline solver. Mainly for testing purposes.
# Examples
# --------
# >>> problem = glp_create_prob()
# ... glp_read_lp(problem, None, "../tests/data/model.lp")
# ... solution = solve_with_glpsol(problem)
# ... print 'asdf'
# 'asdf'
# >>> print solutio... | f14874:m0 |
def glpk_read_cplex(path): | from swiglpk import glp_create_prob, glp_read_lp<EOL>problem = glp_create_prob()<EOL>glp_read_lp(problem, None, path)<EOL>return problem<EOL> | Reads cplex file and returns glpk problem.
Returns
-------
glp_prob
A glpk problems (same type as returned by glp_create_prob) | f14874:m1 |
def list_available_solvers(): | solvers = dict(GUROBI=False, GLPK=False, MOSEK=False, CPLEX=False, SCIPY=False)<EOL>try:<EOL><INDENT>import gurobipy<EOL>solvers['<STR_LIT>'] = True<EOL>log.debug('<STR_LIT>' % os.path.dirname(gurobipy.__file__))<EOL><DEDENT>except Exception:<EOL><INDENT>log.debug('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>import swiglp... | Determine available solver interfaces (with python bindings).
Returns
-------
dict
A dict like {'GLPK': True, 'GUROBI': False, ...} | f14874:m2 |
def inheritdocstring(name, bases, attrs): | if '<STR_LIT>' not in attrs or not attrs["<STR_LIT>"]:<EOL><INDENT>temp = type('<STR_LIT>', bases, {})<EOL>for cls in inspect.getmro(temp):<EOL><INDENT>if cls.__doc__ is not None:<EOL><INDENT>attrs['<STR_LIT>'] = cls.__doc__<EOL>break<EOL><DEDENT><DEDENT><DEDENT>for attr_name, attr in attrs.items():<EOL><INDENT>if not ... | Use as metaclass to inherit class and method docstrings from parent.
Adapted from http://stackoverflow.com/questions/13937500/inherit-a-parent-class-docstring-as-doc-attribute
Use this on classes defined in solver-specific interfaces to inherit docstrings from the high-level interface. | f14874:m3 |
def method_inheritdocstring(mthd): | if not mthd.__doc__:<EOL><INDENT>pass<EOL><DEDENT> | Use as decorator on a method to inherit doc from parent method of same name | f14874:m4 |
def expr_to_json(expr): | if isinstance(expr, symbolics.Mul):<EOL><INDENT>return {"<STR_LIT:type>": "<STR_LIT>", "<STR_LIT:args>": [expr_to_json(arg) for arg in expr.args]}<EOL><DEDENT>elif isinstance(expr, symbolics.Add):<EOL><INDENT>return {"<STR_LIT:type>": "<STR_LIT>", "<STR_LIT:args>": [expr_to_json(arg) for arg in expr.args]}<EOL><DEDENT>... | Converts a Sympy expression to a json-compatible tree-structure. | f14874:m6 |
def parse_expr(expr, local_dict=None): | if local_dict is None:<EOL><INDENT>local_dict = {}<EOL><DEDENT>if expr["<STR_LIT:type>"] == "<STR_LIT>":<EOL><INDENT>return add([parse_expr(arg, local_dict) for arg in expr["<STR_LIT:args>"]])<EOL><DEDENT>elif expr["<STR_LIT:type>"] == "<STR_LIT>":<EOL><INDENT>return mul([parse_expr(arg, local_dict) for arg in expr["<S... | Parses a json-object created with 'expr_to_json' into a Sympy expression.
If a local_dict argument is passed, symbols with be looked up by name, and a new symbol will
be created only if the name is not in local_dict. | f14874:m7 |
def _evolve_kwargs(self): | valid_evolve_kwargs = (<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>filtered_evolve_kwargs = dict()<EOL>for key in valid_evolve_kwargs:<EOL><INDENT>attr_value = getattr(self, key)<EOL>if attr_value is not None:<EOL><INDENT>filtered_evolve_kwargs[key] = attr_value<EOL><DEDENT><D... | Filter None keyword arguments. Intended to be passed on to algorithm.evolve(...) | f14899:c3:m19 |
def parse_optimization_expression(obj, linear=True, quadratic=False, expression=None, **kwargs): | if expression is None:<EOL><INDENT>expression = obj.expression<EOL><DEDENT>if not (linear or quadratic):<EOL><INDENT>if obj.is_Linear:<EOL><INDENT>linear = True<EOL><DEDENT>elif obj.is_Quadratic:<EOL><INDENT>quadratic = True<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>assert linear o... | Function for parsing the expression of a Constraint or Objective object.
Parameters
----------
object: Constraint or Objective
The optimization expression to be parsed
linear: Boolean
If True the expression will be assumed to be linear
quadratic: Boolean
If True the expression will be assumed to be quadrat... | f14901:m0 |
def _parse_linear_expression(expression, expanded=False, **kwargs): | offset = <NUM_LIT:0><EOL>constant = None<EOL>if expression.is_Add:<EOL><INDENT>coefficients = expression.as_coefficients_dict()<EOL><DEDENT>elif expression.is_Mul:<EOL><INDENT>coefficients = {expression.args[<NUM_LIT:1>]: expression.args[<NUM_LIT:0>]}<EOL><DEDENT>elif expression.is_Symbol:<EOL><INDENT>coefficients = {e... | Parse the coefficients of a linear expression (linearity is assumed).
Returns a dictionary of variable: coefficient pairs. | f14901:m1 |
def _parse_quadratic_expression(expression, expanded=False): | linear_coefficients = {}<EOL>quadratic_coefficients = {}<EOL>offset = <NUM_LIT:0><EOL>if expression.is_Number: <EOL><INDENT>return float(expression), linear_coefficients, quadratic_coefficients<EOL><DEDENT>if expression.is_Mul:<EOL><INDENT>terms = (expression,)<EOL><DEDENT>elif expression.is_Add:<EOL><INDENT>terms = e... | Parse a quadratic expression. It is assumed that the expression is known to be quadratic or linear.
The 'expanded' parameter tells whether the expression has already been expanded. If it hasn't the parsing
might fail and will expand the expression and try again. | f14901:m2 |
def set_variable_bounds(self, name, lower, upper): | self.bounds[name] = (lower, upper)<EOL>self._reset_solution()<EOL> | Set the bounds of a variable | f14902:c0:m5 |
def add_variable(self, name): | if name in self._variables:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" + name + "<STR_LIT>"<EOL>)<EOL><DEDENT>self._variables[name] = len(self._variables)<EOL>self.bounds[name] = (<NUM_LIT:0>, None)<EOL>new_col = np.zeros(shape=[len(self._constraints), <NUM_LIT:1>])<EOL>self._add_col_to_A(new_col)<EOL>self._reset_so... | Add a variable to the problem | f14902:c0:m6 |
def add_constraint(self, name, coefficients={}, ub=<NUM_LIT:0>): | if name in self._constraints:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" + name + "<STR_LIT>"<EOL>)<EOL><DEDENT>self._constraints[name] = len(self._constraints)<EOL>self.upper_bounds = np.append(self.upper_bounds, ub)<EOL>new_row = np.array([[coefficients.get(name, <NUM_LIT:0>) for name in self._variables]])<EOL>sel... | Add a constraint to the problem. The constrain is formulated as a dictionary of variable names to
linear coefficients.
The constraint can only have an upper bound. To make a constraint with a lower bound, multiply
all coefficients by -1. | f14902:c0:m7 |
def remove_variable(self, name): | index = self._get_var_index(name)<EOL>self._A = np.delete(self.A, index, <NUM_LIT:1>)<EOL>del self.bounds[name]<EOL>del self._variables[name]<EOL>self._update_variable_indices()<EOL>self._reset_solution()<EOL> | Remove a variable from the problem. | f14902:c0:m10 |
def remove_constraint(self, name): | index = self._get_constraint_index(name)<EOL>self._A = np.delete(self.A, index, <NUM_LIT:0>)<EOL>self.upper_bounds = np.delete(self.upper_bounds, index)<EOL>del self._constraints[name]<EOL>self._update_constraint_indices()<EOL>self._reset_solution()<EOL> | Remove a constraint from the problem | f14902:c0:m11 |
def set_constraint_bound(self, name, value): | index = self._get_constraint_index(name)<EOL>self.upper_bounds[index] = value<EOL>self._reset_solution()<EOL> | Set the upper bound of a constraint. | f14902:c0:m12 |
def get_var_primal(self, name): | if self._var_primals is None:<EOL><INDENT>return None<EOL><DEDENT>else:<EOL><INDENT>index = self._get_var_index(name)<EOL>return self._var_primals[index]<EOL><DEDENT> | Get the primal value of a variable. Returns None if the problem has not bee optimized. | f14902:c0:m13 |
@property<EOL><INDENT>def A(self):<DEDENT> | assert self._rows_to_be_added is None or self._cols_to_be_added is None<EOL>return self._A<EOL> | The linear coefficient matrix. | f14902:c0:m15 |
def get_constraint_slack(self, name): | if self._slacks is None:<EOL><INDENT>return None<EOL><DEDENT>else:<EOL><INDENT>index = self._get_constraint_index(name)<EOL>return self._slacks[index]<EOL><DEDENT> | Get the value of the slack variable of a constraint. | f14902:c0:m23 |
def optimize(self, method="<STR_LIT>", verbosity=False, tolerance=<NUM_LIT>, **kwargs): | c = np.array([self.objective.get(name, <NUM_LIT:0>) for name in self._variables])<EOL>if self.direction == "<STR_LIT>":<EOL><INDENT>c *= -<NUM_LIT:1><EOL><DEDENT>bounds = list(six.itervalues(self.bounds))<EOL>solution = linprog(c, self.A, self.upper_bounds, bounds=bounds, method=method,<EOL>options={"<STR_LIT>": <NUM_L... | Run the linprog function on the problem. Returns None. | f14902:c0:m24 |
@property<EOL><INDENT>def objective_value(self):<DEDENT> | if self._f is None:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>if self.direction == "<STR_LIT>":<EOL><INDENT>return -self._f + self.offset<EOL><DEDENT>else:<EOL><INDENT>return self._f + self.offset<EOL><DEDENT> | Returns the optimal objective value | f14902:c0:m25 |
def _constraint_lb_and_ub_to_cplex_sense_rhs_and_range_value(lb, ub): | if lb is None and ub is None:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>elif lb is None:<EOL><INDENT>sense = '<STR_LIT:L>'<EOL>rhs = float(ub)<EOL>range_value = <NUM_LIT:0.><EOL><DEDENT>elif ub is None:<EOL><INDENT>sense = '<STR_LIT>'<EOL>rhs = float(lb)<EOL>range_value = <NUM_LIT:0.><EOL><DEDENT>elif lb == ... | Helper function used by Constraint and Model | f14903:m0 |
@property<EOL><INDENT>def lp_method(self):<DEDENT> | lpmethod = self.problem.problem.parameters.lpmethod<EOL>value = lpmethod.get()<EOL>return lpmethod.values[value]<EOL> | The algorithm used to solve LP problems. | f14903:c3:m1 |
@property<EOL><INDENT>def solution_target(self):<DEDENT> | if self.problem is not None:<EOL><INDENT>params = self.problem.problem.parameters<EOL>try:<EOL><INDENT>solution_target = params.optimalitytarget<EOL><DEDENT>except AttributeError: <EOL><INDENT>solution_target = params.solutiontarget <EOL><DEDENT>return _SOLUTION_TARGETS[solution_target.get()]<EOL><DEDENT>else:<EOL><I... | Change whether the QP solver will try to find a globally optimal solution or a local optimum.
This will only | f14903:c3:m12 |
@property<EOL><INDENT>def qp_method(self):<DEDENT> | value = self.problem.problem.parameters.qpmethod.get()<EOL>return self.problem.problem.parameters.qpmethod.values[value]<EOL> | Change the algorithm used to optimize QP problems. | f14903:c3:m14 |
def convert_linear_problem_to_dual(model, sloppy=False, infinity=None, maintain_standard_form=True, prefix="<STR_LIT>", dual_model=None): | if dual_model is None:<EOL><INDENT>dual_model = model.interface.Model()<EOL><DEDENT>maximization = model.objective.direction == "<STR_LIT>"<EOL>if infinity is not None:<EOL><INDENT>neg_infinity = -infinity<EOL><DEDENT>else:<EOL><INDENT>neg_infinity = None<EOL><DEDENT>if maximization:<EOL><INDENT>sign = <NUM_LIT:1><EOL>... | A mathematical optimization problem can be viewed as a primal and a dual problem. If the primal problem is
a minimization problem the dual is a maximization problem, and the optimal value of the dual is a lower bound of
the optimal value of the primal.
For linear problems, strong duality holds, which means that the opt... | f14904:m0 |
@classmethod<EOL><INDENT>def clone(cls, variable, **kwargs):<DEDENT> | return cls(variable.name, lb=variable.lb, ub=variable.ub, type=variable.type, **kwargs)<EOL> | Make a copy of another variable. The variable being copied can be of the same type or belong to
a different solver interface.
Example
----------
>>> var_copy = Variable.clone(old_var) | f14907:c0:m3 |
@property<EOL><INDENT>def name(self):<DEDENT> | return self._name<EOL> | Name of variable. | f14907:c0:m5 |
@property<EOL><INDENT>def lb(self):<DEDENT> | return self._lb<EOL> | Lower bound of variable. | f14907:c0:m7 |
@property<EOL><INDENT>def ub(self):<DEDENT> | return self._ub<EOL> | Upper bound of variable. | f14907:c0:m9 |
def set_bounds(self, lb, ub): | if lb is not None and ub is not None and lb > ub:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>".format(lb, ub)<EOL>)<EOL><DEDENT>self._lb = lb<EOL>self._ub = ub<EOL>if self.problem is not None:<EOL><INDENT>self.problem._pending_modifications.var_lb.append((self, lb))<EOL>self.problem._pending_modifications.var_ub.appen... | Change the lower and upper bounds of a variable. | f14907:c0:m11 |
@property<EOL><INDENT>def type(self):<DEDENT> | return self._type<EOL> | Variable type ('either continuous, integer, or binary'.) | f14907:c0:m12 |
@property<EOL><INDENT>def primal(self):<DEDENT> | if self.problem:<EOL><INDENT>return self._get_primal()<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT> | The primal of variable (None if no solution exists). | f14907:c0:m14 |
@property<EOL><INDENT>def dual(self):<DEDENT> | return None<EOL> | The dual of variable (None if no solution exists). | f14907:c0:m16 |
def __str__(self): | if self.lb is not None:<EOL><INDENT>lb_str = str(self.lb) + "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>lb_str = "<STR_LIT>"<EOL><DEDENT>if self.ub is not None:<EOL><INDENT>ub_str = "<STR_LIT>" + str(self.ub)<EOL><DEDENT>else:<EOL><INDENT>ub_str = "<STR_LIT>"<EOL><DEDENT>return '<STR_LIT>'.join((lb_str, super(Variable, s... | Print a string representation of variable.
Examples
--------
>>> Variable('x', lb=-10, ub=10)
'-10 <= x <= 10' | f14907:c0:m17 |
def __repr__(self): | return self.__str__()<EOL> | Does exactly the same as __str__ for now. | f14907:c0:m18 |
def to_json(self): | json_obj = {<EOL>"<STR_LIT:name>": self.name,<EOL>"<STR_LIT>": self.lb,<EOL>"<STR_LIT>": self.ub,<EOL>"<STR_LIT:type>": self.type<EOL>}<EOL>return json_obj<EOL> | Returns a json-compatible object from the Variable that can be saved using the json module.
Example
--------
>>> import json
>>> with open("path_to_file.json", "w") as outfile:
>>> json.dump(var.to_json(), outfile) | f14907:c0:m22 |
@classmethod<EOL><INDENT>def from_json(cls, json_obj):<DEDENT> | return cls(json_obj["<STR_LIT:name>"], lb=json_obj["<STR_LIT>"], ub=json_obj["<STR_LIT>"], type=json_obj["<STR_LIT:type>"])<EOL> | Constructs a Variable from the provided json-object.
Example
--------
>>> import json
>>> with open("path_to_file.json") as infile:
>>> var = Variable.from_json(json.load(infile)) | f14907:c0:m23 |
@classmethod<EOL><INDENT>def _substitute_variables(cls, expression, model=None, **kwargs):<DEDENT> | interface = sys.modules[cls.__module__]<EOL>variable_substitutions = dict()<EOL>for variable in expression.variables:<EOL><INDENT>if model is not None and variable.name in model.variables:<EOL><INDENT>variable_substitutions[variable] = model.variables[variable.name]<EOL><DEDENT>else:<EOL><INDENT>variable_substitutions[... | Substitutes variables in (optimization)expression (constraint/objective) with variables of the appropriate interface type.
Attributes
----------
expression: Constraint, Objective
An optimization expression.
model: Model or None, optional
A reference to an optimiza... | f14907:c1:m1 |
@property<EOL><INDENT>def name(self):<DEDENT> | return self._name<EOL> | The name of the object | f14907:c1:m3 |
@property<EOL><INDENT>def problem(self):<DEDENT> | return getattr(self, '<STR_LIT>', None)<EOL> | A reference to the model that the object belongs to (or None) | f14907:c1:m5 |
@property<EOL><INDENT>def expression(self):<DEDENT> | return self._get_expression()<EOL> | The mathematical expression defining the objective/constraint. | f14907:c1:m8 |
@property<EOL><INDENT>def variables(self):<DEDENT> | return self.expression.atoms(Variable)<EOL> | Variables in constraint/objective's expression. | f14907:c1:m9 |
@property<EOL><INDENT>def is_Linear(self):<DEDENT> | coeff_dict = self.expression.as_coefficients_dict()<EOL>for key in coeff_dict.keys():<EOL><INDENT>if len(key.free_symbols) < <NUM_LIT:2> and (key.is_Add or key.is_Mul or key.is_Atom):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT>if key.is_Pow and key.args[<NUM_LIT:1>] != <NUM_LIT:1>:<EOL><IND... | Returns True if expression is linear (a polynomial with degree 1 or 0) (read-only). | f14907:c1:m11 |
@property<EOL><INDENT>def is_Quadratic(self):<DEDENT> | if self.expression.is_Atom:<EOL><INDENT>return False<EOL><DEDENT>if all((len(key.free_symbols) < <NUM_LIT:2> and (key.is_Add or key.is_Mul or key.is_Atom)<EOL>for key in self.expression.as_coefficients_dict().keys())):<EOL><INDENT>return False<EOL><DEDENT>if self.expression.is_Add:<EOL><INDENT>terms = self.expression.a... | Returns True if the expression is a polynomial with degree exactly 2 (read-only). | f14907:c1:m12 |
def set_linear_coefficients(self, coefficients): | raise NotImplementedError("<STR_LIT>")<EOL> | Set coefficients of linear terms in constraint or objective.
Existing coefficients for linear or non-linear terms will not be modified.
Note: This method interacts with the low-level solver backend and can only be used on objects that are
associated with a Model. The method is not part of optla... | f14907:c1:m18 |
def get_linear_coefficients(self, variables): | raise NotImplementedError("<STR_LIT>")<EOL> | Get coefficients of linear terms in constraint or objective.
Note: This method interacts with the low-level solver backend and can only be used on objects that are
associated with a Model. The method is not part of optlangs basic interface and should be used mainly where
speed is important.
... | f14907:c1:m19 |
@classmethod<EOL><INDENT>def clone(cls, constraint, model=None, **kwargs):<DEDENT> | return cls(cls._substitute_variables(constraint, model=model), lb=constraint.lb, ub=constraint.ub,<EOL>indicator_variable=constraint.indicator_variable, active_when=constraint.active_when,<EOL>name=constraint.name, sloppy=True, **kwargs)<EOL> | Make a copy of another constraint. The constraint being copied can be of the same type or belong to
a different solver interface.
Parameters
----------
constraint: interface.Constraint (or subclass)
The constraint to copy
model: Model or None
The variables of the new constraint will be taken from this model. I... | f14907:c2:m4 |
@property<EOL><INDENT>def lb(self):<DEDENT> | return self._lb<EOL> | Lower bound of constraint. | f14907:c2:m6 |
@property<EOL><INDENT>def ub(self):<DEDENT> | return self._ub<EOL> | Upper bound of constraint. | f14907:c2:m8 |
@property<EOL><INDENT>def indicator_variable(self):<DEDENT> | return self._indicator_variable<EOL> | The indicator variable of constraint (if available). | f14907:c2:m10 |
@property<EOL><INDENT>def active_when(self):<DEDENT> | return self._active_when<EOL> | Activity relation of constraint to indicator variable (if supported). | f14907:c2:m11 |
@property<EOL><INDENT>def primal(self):<DEDENT> | return None<EOL> | Primal of constraint (None if no solution exists). | f14907:c2:m14 |
@property<EOL><INDENT>def dual(self):<DEDENT> | return None<EOL> | Dual of constraint (None if no solution exists). | f14907:c2:m15 |
def to_json(self): | if self.indicator_variable is None:<EOL><INDENT>indicator = None<EOL><DEDENT>else:<EOL><INDENT>indicator = self.indicator_variable.name<EOL><DEDENT>json_obj = {<EOL>"<STR_LIT:name>": self.name,<EOL>"<STR_LIT>": expr_to_json(self.expression),<EOL>"<STR_LIT>": self.lb,<EOL>"<STR_LIT>": self.ub,<EOL>"<STR_LIT>": indicator... | Returns a json-compatible object from the constraint that can be saved using the json module.
Example
--------
>>> import json
>>> with open("path_to_file.json", "w") as outfile:
>>> json.dump(constraint.to_json(), outfile) | f14907:c2:m17 |
@classmethod<EOL><INDENT>def from_json(cls, json_obj, variables=None):<DEDENT> | if variables is None:<EOL><INDENT>variables = {}<EOL><DEDENT>expression = parse_expr(json_obj["<STR_LIT>"], variables)<EOL>if json_obj["<STR_LIT>"] is None:<EOL><INDENT>indicator = None<EOL><DEDENT>else:<EOL><INDENT>indicator = variables[json_obj["<STR_LIT>"]]<EOL><DEDENT>return cls(<EOL>expression,<EOL>name=json_obj["... | Constructs a Variable from the provided json-object.
Example
--------
>>> import json
>>> with open("path_to_file.json") as infile:
>>> constraint = Constraint.from_json(json.load(infile)) | f14907:c2:m18 |
@classmethod<EOL><INDENT>def clone(cls, objective, model=None, **kwargs):<DEDENT> | return cls(cls._substitute_variables(objective, model=model), name=objective.name,<EOL>direction=objective.direction, sloppy=True, **kwargs)<EOL> | Make a copy of an objective. The objective being copied can be of the same type or belong to
a different solver interface.
Example
----------
>>> new_objective = Objective.clone(old_objective) | f14907:c3:m0 |
@property<EOL><INDENT>def value(self):<DEDENT> | return self._value<EOL> | The objective value. | f14907:c3:m2 |
def __eq__(self, other): | if isinstance(other, Objective):<EOL><INDENT>return self.expression == other.expression and self.direction == other.direction<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT> | Tests *mathematical* equality for two Objectives. Solver specific type does NOT have to match.
Expression and direction must be the same.
Name does not have to match | f14907:c3:m4 |
def _canonicalize(self, expression): | expression = super(Objective, self)._canonicalize(expression)<EOL>if isinstance(expression, sympy.Basic):<EOL><INDENT>expression *= <NUM_LIT:1.><EOL><DEDENT>else: <EOL><INDENT>expression = (<NUM_LIT:1.> * expression).expand()<EOL><DEDENT>return expression<EOL> | For example, changes x + y to 1.*x + 1.*y | f14907:c3:m5 |
@property<EOL><INDENT>def direction(self):<DEDENT> | return self._direction<EOL> | The direction of optimization. Either 'min' or 'max'. | f14907:c3:m6 |
def set_linear_coefficients(self, coefficients): | raise NotImplementedError("<STR_LIT>")<EOL> | Set linear coefficients in objective.
coefficients : dict
A dictionary of the form {variable1: coefficient1, variable2: coefficient2, ...} | f14907:c3:m8 |
def to_json(self): | json_obj = {<EOL>"<STR_LIT:name>": self.name,<EOL>"<STR_LIT>": expr_to_json(self.expression),<EOL>"<STR_LIT>": self.direction<EOL>}<EOL>return json_obj<EOL> | Returns a json-compatible object from the objective that can be saved using the json module.
Example
--------
>>> import json
>>> with open("path_to_file.json", "w") as outfile:
>>> json.dump(obj.to_json(), outfile) | f14907:c3:m9 |
@classmethod<EOL><INDENT>def from_json(cls, json_obj, variables=None):<DEDENT> | if variables is None:<EOL><INDENT>variables = {}<EOL><DEDENT>expression = parse_expr(json_obj["<STR_LIT>"], variables)<EOL>return cls(<EOL>expression,<EOL>direction=json_obj["<STR_LIT>"],<EOL>name=json_obj["<STR_LIT:name>"]<EOL>)<EOL> | Constructs an Objective from the provided json-object.
Example
--------
>>> import json
>>> with open("path_to_file.json") as infile:
>>> obj = Objective.from_json(json.load(infile)) | f14907:c3:m10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.