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>for face, rotation in enumerate([[<NUM_LIT>, -<NUM_LIT>, <NUM_LIT:0>], [<NUM_LIT>, <NUM_LIT>, <NUM_LIT:0>], [<NUM_LIT>, <NUM_LIT:0>, <NUM_LIT:0>], [-<NUM_LIT>, <NUM_LIT:0>, <NUM_LIT:0>], [<NUM_LIT>, <NUM_LIT:0>, <NUM_LIT:0>], [<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT>]]): <EOL><INDENT>self.camera.rotation.xyz = rotation<EOL>cubetexture.attach_to_fbo(face)<EOL>self.draw(**kwargs)<EOL><DEDENT>self.camera.rotation = old_rotation<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><DEDENT><DEDENT>return (gl_dtype * len(data))(*data)<EOL> | 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.linalg.norm(vecs, axis=<NUM_LIT:1>, keepdims=True) <EOL>normal = np.cross(*vecs) <EOL>normals[start:end, :] = normal / np.linalg.norm(normal)<EOL><DEDENT>return normals<EOL> | 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;
layout(location = 1) in vec2 texCoord;
layout(location = 2) in vec3 normalCoord; | 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.glEnableVertexAttribArray(location)<EOL><DEDENT> | 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 = kwargs['<STR_LIT>'] if '<STR_LIT>' in kwargs else {}<EOL>if '<STR_LIT>' in body:<EOL><INDENT>material_props = {self.material_property_map[key]: value for key, value in iteritems(body['<STR_LIT>'])}<EOL>for key, value in iteritems(material_props):<EOL><INDENT>if isinstance(value, str):<EOL><INDENT>if key == '<STR_LIT>':<EOL><INDENT>if not value in self.textures:<EOL><INDENT>self.textures[value] = Texture.from_image(value)<EOL><DEDENT>mesh.textures.append(self.textures[value])<EOL><DEDENT>else:<EOL><INDENT>setattr(mesh, key, value)<EOL><DEDENT><DEDENT>elif hasattr(value, '<STR_LIT>'): <EOL><INDENT>mesh.uniforms[key] = value<EOL><DEDENT>elif key in ['<STR_LIT:d>', '<STR_LIT>']: <EOL><INDENT>mesh.uniforms[key] = value<EOL><DEDENT>elif key in ['<STR_LIT>', '<STR_LIT>']: <EOL><INDENT>mesh.uniforms[key] = float(value)<EOL><DEDENT>else:<EOL><INDENT>print('<STR_LIT>'.format(key, value))<EOL><DEDENT><DEDENT><DEDENT>return mesh<EOL> | 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 = UniformCollection()
uniforms['diffuse'] = 1., 1., 0.
uniforms['model_matrix'] = numpyp.eye(4)
In the shader, this would be used by initializing the uniform variable, for example::
uniform vec3 diffuse;
uniform mat4 model_matrix;
Any key-value pairs are sent to a bound shader program when UniformCollection.send() is called.
More information about GLSL Uniforms can be found at https://www.khronos.org/opengl/wiki/Uniform_(GLSL)
.. note:: This class isn't usually constructed directly. It can be found as 'uniforms' attributes
of Meshes and Cameras. | 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.value != shader_id_for_array:<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT><DEDENT>except (AttributeError, Exception) as e:<EOL><INDENT>array.loc = (gl.glGetUniformLocation(shader_id.value, name.encode('<STR_LIT:ascii>')), shader_id.value)<EOL><DEDENT>if array.ndim == <NUM_LIT:2>: <EOL><INDENT>try:<EOL><INDENT>pointer = array.pointer<EOL><DEDENT>except AttributeError:<EOL><INDENT>array.pointer = array.ctypes.data_as(POINTER(c_float * <NUM_LIT:16>)).contents<EOL>pointer = array.pointer<EOL><DEDENT>gl.glUniformMatrix4fv(array.loc[<NUM_LIT:0>], <NUM_LIT:1>, True, pointer)<EOL><DEDENT>else:<EOL><INDENT>sendfun = self._sendfuns[array.dtype.kind][len(array) - <NUM_LIT:1>] <EOL>sendfun(array.loc[<NUM_LIT:0>], *array)<EOL><DEDENT><DEDENT> | 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 fragment shader program string
- geom (str): The geometry shader program
Example::
shader = Shader.from_file(vert='vertshader.vert', frag='fragshader.frag')
with shader:
mesh.draw() | 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 Shader.unbind() can be also be called implicitly by using the 'with' statement.
Example of with statement with Shader::
with shader:
mesh.draw() | 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.glGetProgramInfoLog(self.id, link_status, None, buffer) <EOL>print(buffer.value) <EOL><DEDENT>self.is_linked = True<EOL> | 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>self.id = create_opengl_object(gl.glGenTextures)<EOL>self.width = width<EOL>self.height = height<EOL>self.bind()<EOL>self._genTex2D()<EOL>self._apply_filter_settings()<EOL><DEDENT>self.unbind()<EOL> | 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.glTexParameterf(self.target, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE)<EOL>gl.glTexParameterf(self.target, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE)<EOL> | 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.>, <NUM_LIT:1.>])[:<NUM_LIT:3>] <EOL>cam.uniforms['<STR_LIT>'] = cam.position.xyz<EOL>with cube_fbo as fbo:<EOL><INDENT>vr_scene.draw360_to_texture(fbo.texture)<EOL><DEDENT>cam.position.xyz = orig_cam_position<EOL>active_scene.draw()<EOL><DEDENT> | 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_scene: virtual scene object
active_scene: active scene object
eye_poses: the eye positions
Returns: | 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 == ub:<EOL><INDENT>sense = '<STR_LIT:=>'<EOL>rhs = float(lb)<EOL>range_value = <NUM_LIT:0.><EOL><DEDENT>elif lb > ub:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>sense = '<STR_LIT:=>'<EOL>rhs = float(lb)<EOL>range_value = float(ub - lb)<EOL><DEDENT>return sense, rhs, range_value<EOL> | 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) + <NUM_LIT:1>)]<EOL>with tempfile.NamedTemporaryFile(suffix="<STR_LIT>", delete=True) as tmp_file:<EOL><INDENT>tmp_file_name = tmp_file.name<EOL>glp_write_lp(glp_prob, None, tmp_file_name)<EOL>cmd = ['<STR_LIT>', '<STR_LIT>', tmp_file_name, '<STR_LIT>', tmp_file_name + '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>term = check_output(cmd)<EOL>log.info(term)<EOL><DEDENT>try:<EOL><INDENT>with open(tmp_file_name + '<STR_LIT>') as sol_handle:<EOL><INDENT>solution = dict()<EOL>for i, line in enumerate(sol_handle.readlines()):<EOL><INDENT>if i <= <NUM_LIT:1> or line == '<STR_LIT:\n>':<EOL><INDENT>pass<EOL><DEDENT>elif i <= len(row_ids):<EOL><INDENT>solution[row_ids[i - <NUM_LIT:2>]] = line.strip().split('<STR_LIT:U+0020>')<EOL><DEDENT>elif i <= len(row_ids) + len(col_ids) + <NUM_LIT:1>:<EOL><INDENT>solution[col_ids[i - <NUM_LIT:2> - len(row_ids)]] = line.strip().split('<STR_LIT:U+0020>')<EOL><DEDENT>else:<EOL><INDENT>print(i)<EOL>print(line)<EOL>raise Exception("<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT><DEDENT>finally:<EOL><INDENT>os.remove(tmp_file_name + "<STR_LIT>")<EOL><DEDENT>return solution<EOL> | 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 solution
# 0.839784
# Returns
# -------
# dict
# A dictionary containing the objective value (key ='objval')
# and variable primals. | 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 swiglpk<EOL>solvers['<STR_LIT>'] = True<EOL>log.debug('<STR_LIT>' % os.path.dirname(swiglpk.__file__))<EOL><DEDENT>except Exception:<EOL><INDENT>log.debug('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>import mosek<EOL>solvers['<STR_LIT>'] = True<EOL>log.debug('<STR_LIT>' % os.path.dirname(mosek.__file__))<EOL><DEDENT>except Exception:<EOL><INDENT>log.debug('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>import cplex<EOL>solvers['<STR_LIT>'] = True<EOL>log.debug('<STR_LIT>' % os.path.dirname(cplex.__file__))<EOL><DEDENT>except Exception:<EOL><INDENT>log.debug('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>from scipy import optimize<EOL>optimize.linprog<EOL>solvers["<STR_LIT>"] = True<EOL>log.debug("<STR_LIT>" % optimize.__file__)<EOL><DEDENT>except (ImportError, AttributeError):<EOL><INDENT>log.debug("<STR_LIT>")<EOL><DEDENT>return solvers<EOL> | 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 attr.__doc__:<EOL><INDENT>for cls in inspect.getmro(temp):<EOL><INDENT>try:<EOL><INDENT>if getattr(cls, attr_name).__doc__ is not None:<EOL><INDENT>attr.__doc__ = getattr(cls, attr_name).__doc__<EOL>break<EOL><DEDENT><DEDENT>except (AttributeError, TypeError):<EOL><INDENT>continue<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return type(name, bases, attrs)<EOL> | 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>elif isinstance(expr, symbolics.Symbol):<EOL><INDENT>return {"<STR_LIT:type>": "<STR_LIT>", "<STR_LIT:name>": expr.name}<EOL><DEDENT>elif isinstance(expr, symbolics.Pow):<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, (float, int)):<EOL><INDENT>return {"<STR_LIT:type>": "<STR_LIT>", "<STR_LIT:value>": expr}<EOL><DEDENT>elif isinstance(expr, symbolics.Real):<EOL><INDENT>return {"<STR_LIT:type>": "<STR_LIT>", "<STR_LIT:value>": float(expr)}<EOL><DEDENT>elif isinstance(expr, symbolics.Integer):<EOL><INDENT>return {"<STR_LIT:type>": "<STR_LIT>", "<STR_LIT:value>": int(expr)}<EOL><DEDENT>else:<EOL><INDENT>raise NotImplementedError("<STR_LIT>" + str(type(expr)))<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["<STR_LIT:args>"]])<EOL><DEDENT>elif expr["<STR_LIT:type>"] == "<STR_LIT>":<EOL><INDENT>return Pow(parse_expr(arg, local_dict) for arg in expr["<STR_LIT:args>"])<EOL><DEDENT>elif expr["<STR_LIT:type>"] == "<STR_LIT>":<EOL><INDENT>try:<EOL><INDENT>return local_dict[expr["<STR_LIT:name>"]]<EOL><DEDENT>except KeyError:<EOL><INDENT>return symbolics.Symbol(expr["<STR_LIT:name>"])<EOL><DEDENT><DEDENT>elif expr["<STR_LIT:type>"] == "<STR_LIT>":<EOL><INDENT>return symbolics.sympify(expr["<STR_LIT:value>"])<EOL><DEDENT>else:<EOL><INDENT>raise NotImplementedError(expr["<STR_LIT:type>"] + "<STR_LIT>")<EOL><DEDENT> | 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><DEDENT>return {}<EOL> | 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 or quadratic<EOL>if quadratic:<EOL><INDENT>offset, linear_coefficients, quadratic_coefficients = _parse_quadratic_expression(expression, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>offset, linear_coefficients = _parse_linear_expression(expression, **kwargs)<EOL>quadratic_coefficients = {}<EOL><DEDENT>return offset, linear_coefficients, quadratic_coefficients<EOL> | 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 quadratic
expression: Sympy expression or None (optional)
An expression can be passed explicitly to avoid getting the expression from the solver.
If this is used then 'linear' or 'quadratic' should be True.
If both linear and quadratic are False, the is_Linear and is_Quadratic methods will be used to determine how it should be parsed
Returns
----------
A tuple of (linear_coefficients, quadratic_coefficients)
linear_coefficients is a dictionary of {variable: coefficient} pairs
quadratic_coefficients is a dictionary of {frozenset(variables): coefficient} pairs | 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 = {expression: <NUM_LIT:1>}<EOL><DEDENT>elif expression.is_Number:<EOL><INDENT>coefficients = {}<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>".format(expression))<EOL><DEDENT>for var in coefficients:<EOL><INDENT>if not (var.is_Symbol):<EOL><INDENT>if var == one:<EOL><INDENT>constant = var<EOL>offset = float(coefficients[var])<EOL><DEDENT>elif expanded:<EOL><INDENT>raise ValueError("<STR_LIT>".format(expression))<EOL><DEDENT>else:<EOL><INDENT>coefficients = _parse_linear_expression(expression, expanded=True, **kwargs)<EOL><DEDENT><DEDENT><DEDENT>if constant is not None:<EOL><INDENT>del coefficients[constant]<EOL><DEDENT>return offset, coefficients<EOL> | 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 = expression.args<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>".format(type(expression)))<EOL><DEDENT>try:<EOL><INDENT>for term in terms:<EOL><INDENT>if term.is_Number:<EOL><INDENT>offset += float(term)<EOL>continue<EOL><DEDENT>if term.is_Pow:<EOL><INDENT>term = <NUM_LIT:1.0> * term<EOL><DEDENT>assert term.is_Mul, "<STR_LIT>".format(type(term))<EOL>factors = term.args<EOL>coef = factors[<NUM_LIT:0>]<EOL>vars = factors[<NUM_LIT:1>:]<EOL>assert len(vars) <= <NUM_LIT:2>, "<STR_LIT>"<EOL>if len(vars) == <NUM_LIT:2>:<EOL><INDENT>key = frozenset(vars)<EOL>quadratic_coefficients[key] = quadratic_coefficients.get(key, <NUM_LIT:0>) + coef<EOL><DEDENT>else:<EOL><INDENT>var = vars[<NUM_LIT:0>]<EOL>if var.is_Symbol:<EOL><INDENT>linear_coefficients[var] = linear_coefficients.get(var, <NUM_LIT:0>) + coef<EOL><DEDENT>elif var.is_Pow:<EOL><INDENT>var, exponent = var.args<EOL>if exponent != <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>key = frozenset((var,))<EOL>quadratic_coefficients[key] = quadratic_coefficients.get(key, <NUM_LIT:0>) + coef<EOL><DEDENT><DEDENT><DEDENT>if quadratic_coefficients:<EOL><INDENT>assert all(var.is_Symbol for var in frozenset.union(*quadratic_coefficients)) <EOL><DEDENT>if linear_coefficients:<EOL><INDENT>assert all(var.is_Symbol for var in linear_coefficients)<EOL><DEDENT><DEDENT>except Exception as e:<EOL><INDENT>if expanded:<EOL><INDENT>raise e<EOL><DEDENT>else:<EOL><INDENT>return _parse_quadratic_expression(expression.expand(), expanded=True)<EOL><DEDENT><DEDENT>return offset, linear_coefficients, quadratic_coefficients<EOL> | 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_solution()<EOL> | 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>self._add_row_to_A(new_row)<EOL>self._reset_solution()<EOL> | 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_LIT>, "<STR_LIT>": verbosity, "<STR_LIT>": tolerance}, **kwargs)<EOL>self._solution = solution<EOL>self._status = solution.status<EOL>if SCIPY_STATUS[self._status] == interface.OPTIMAL:<EOL><INDENT>self._var_primals = solution.x<EOL>self._slacks = solution.slack<EOL><DEDENT>else:<EOL><INDENT>self._var_primals = None<EOL>self._slacks = None<EOL><DEDENT>self._f = solution.fun<EOL> | 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 == ub:<EOL><INDENT>sense = '<STR_LIT:E>'<EOL>rhs = float(lb)<EOL>range_value = <NUM_LIT:0.><EOL><DEDENT>elif lb > ub:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>sense = '<STR_LIT:R>'<EOL>rhs = float(lb)<EOL>range_value = float(ub - lb)<EOL><DEDENT>return sense, rhs, range_value<EOL> | 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><INDENT>return None<EOL><DEDENT> | 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><DEDENT>else:<EOL><INDENT>sign = -<NUM_LIT:1><EOL><DEDENT>coefficients = {}<EOL>dual_objective = {}<EOL>for constraint in model.constraints:<EOL><INDENT>if constraint.expression == <NUM_LIT:0>:<EOL><INDENT>continue <EOL><DEDENT>if not (sloppy or constraint.is_Linear):<EOL><INDENT>raise ValueError("<STR_LIT>" + str(constraint))<EOL><DEDENT>if constraint.lb is None and constraint.ub is None:<EOL><INDENT>continue <EOL><DEDENT>if not maintain_standard_form and constraint.lb == constraint.ub:<EOL><INDENT>const_var = model.interface.Variable(prefix + constraint.name + "<STR_LIT>", lb=neg_infinity, ub=infinity)<EOL>dual_model.add(const_var)<EOL>if constraint.lb != <NUM_LIT:0>:<EOL><INDENT>dual_objective[const_var] = sign * constraint.lb<EOL><DEDENT>for variable, coef in constraint.expression.as_coefficients_dict().items():<EOL><INDENT>if variable == <NUM_LIT:1>: <EOL><INDENT>continue<EOL><DEDENT>coefficients.setdefault(variable.name, {})[const_var] = sign * coef<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if constraint.lb is not None:<EOL><INDENT>lb_var = model.interface.Variable(prefix + constraint.name + "<STR_LIT>", lb=<NUM_LIT:0>, ub=infinity)<EOL>dual_model.add(lb_var)<EOL>if constraint.lb != <NUM_LIT:0>:<EOL><INDENT>dual_objective[lb_var] = -sign * constraint.lb<EOL><DEDENT><DEDENT>if constraint.ub is not None:<EOL><INDENT>ub_var = model.interface.Variable(prefix + constraint.name + "<STR_LIT>", lb=<NUM_LIT:0>, ub=infinity)<EOL>dual_model.add(ub_var)<EOL>if constraint.ub != <NUM_LIT:0>:<EOL><INDENT>dual_objective[ub_var] = sign * constraint.ub<EOL><DEDENT><DEDENT>assert constraint.expression.is_Add or constraint.expression.is_Mul,"<STR_LIT>" + str(type(constraint.expression))<EOL>if constraint.expression.is_Add:<EOL><INDENT>coefficients_dict = constraint.expression.as_coefficients_dict()<EOL><DEDENT>else: <EOL><INDENT>coefficients_dict = {constraint.expression.args[<NUM_LIT:1>]: constraint.expression.args[<NUM_LIT:0>]}<EOL><DEDENT>for variable, coef in coefficients_dict.items():<EOL><INDENT>if variable == <NUM_LIT:1>: <EOL><INDENT>continue<EOL><DEDENT>if constraint.lb is not None:<EOL><INDENT>coefficients.setdefault(variable.name, {})[lb_var] = -sign * coef<EOL><DEDENT>if constraint.ub is not None:<EOL><INDENT>coefficients.setdefault(variable.name, {})[ub_var] = sign * coef<EOL><DEDENT><DEDENT><DEDENT><DEDENT>for variable in model.variables:<EOL><INDENT>if not (sloppy or variable.type == "<STR_LIT>"):<EOL><INDENT>raise ValueError("<STR_LIT>" + str(variable))<EOL><DEDENT>if not sloppy and (variable.lb is None or variable.lb < <NUM_LIT:0>):<EOL><INDENT>raise ValueError("<STR_LIT>" + variable.name + "<STR_LIT>")<EOL><DEDENT>if variable.lb > <NUM_LIT:0>:<EOL><INDENT>bound_var = model.interface.Variable(prefix + variable.name + "<STR_LIT>", lb=<NUM_LIT:0>, ub=infinity)<EOL>dual_model.add(bound_var)<EOL>coefficients.setdefault(variable.name, {})[bound_var] = -sign * <NUM_LIT:1><EOL>dual_objective[bound_var] = -sign * variable.lb<EOL><DEDENT>if variable.ub is not None:<EOL><INDENT>bound_var = model.interface.Variable(prefix + variable.name + "<STR_LIT>", lb=<NUM_LIT:0>, ub=infinity)<EOL>dual_model.add(bound_var)<EOL>coefficients.setdefault(variable.name, {})[bound_var] = sign * <NUM_LIT:1><EOL>if variable.ub != <NUM_LIT:0>:<EOL><INDENT>dual_objective[bound_var] = sign * variable.ub<EOL><DEDENT><DEDENT><DEDENT>primal_objective_dict = model.objective.expression.as_coefficients_dict()<EOL>for variable in model.variables:<EOL><INDENT>expr = optlang.symbolics.add([(coef * dual_var) for dual_var, coef in coefficients[variable.name].items()])<EOL>obj_coef = primal_objective_dict[variable]<EOL>if maximization:<EOL><INDENT>const = model.interface.Constraint(expr, lb=obj_coef, name=prefix + variable.name)<EOL><DEDENT>else:<EOL><INDENT>const = model.interface.Constraint(expr, ub=obj_coef, name=prefix + variable.name)<EOL><DEDENT>dual_model.add(const)<EOL><DEDENT>expr = optlang.symbolics.add([(coef * dual_var) for dual_var, coef in dual_objective.items() if coef != <NUM_LIT:0>])<EOL>if maximization:<EOL><INDENT>objective = model.interface.Objective(expr, direction="<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>objective = model.interface.Objective(expr, direction="<STR_LIT>")<EOL><DEDENT>dual_model.objective = objective<EOL>return dual_model<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 optimal values of the primal and dual are equal
(duality gap = 0).
This functions takes an optlang Model representing a primal linear problem and returns a new Model representing
the dual optimization problem. The provided model must have a linear objective, linear constraints and only
continuous variables. Furthermore, the problem must be in standard form, i.e. all variables should be non-negative.
Both minimization and maximization problems are allowed. The objective direction of the dual will always be
opposite of the primal.
Attributes:
----------
model: optlang.interface.Model
The primal problem to be dualized
sloppy: Boolean (default False)
If True, linearity, variable types and standard form will not be checked. Only use if you know the primal is
valid
infinity: Numeric or None
If not None this value will be used as bounds instead of unbounded variables.
maintain_standard_form: Boolean (default True)
If False the returned dual problem will not be in standard form, but will have fewer variables and/or constraints
prefix: str
The string that will be prepended to all variable and constraint names in the returned dual problem.
dual_model: optlang.interface.Model or None (default)
If not None, the dual variables and constraints will be added to this model. Note the objective will also be
set to the dual objective. If None a new model will be created.
Returns:
----------
dual_problem: optlang.interface.Model (same solver as the primal) | 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.append((self, ub))<EOL><DEDENT> | 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, self).__str__(), ub_str))<EOL> | 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[variable] = interface.Variable.clone(variable)<EOL><DEDENT><DEDENT>adjusted_expression = expression.expression.xreplace(variable_substitutions)<EOL>return adjusted_expression<EOL> | 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 optimization model that should be searched for appropriate variables first. | 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><INDENT>return False<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return True<EOL><DEDENT> | 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.args<EOL>is_quad = False<EOL>for term in terms:<EOL><INDENT>if len(term.free_symbols) > <NUM_LIT:2>:<EOL><INDENT>return False<EOL><DEDENT>if term.is_Pow:<EOL><INDENT>if not term.args[<NUM_LIT:1>].is_Number or term.args[<NUM_LIT:1>] > <NUM_LIT:2>:<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>is_quad = True<EOL><DEDENT><DEDENT>elif term.is_Mul:<EOL><INDENT>if len(term.free_symbols) == <NUM_LIT:2>:<EOL><INDENT>is_quad = True<EOL><DEDENT>if term.args[<NUM_LIT:1>].is_Pow:<EOL><INDENT>if not term.args[<NUM_LIT:1>].args[<NUM_LIT:1>].is_Number or term.args[<NUM_LIT:1>].args[<NUM_LIT:1>] > <NUM_LIT:2>:<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>is_quad = True<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return is_quad<EOL><DEDENT>else:<EOL><INDENT>if isinstance(self.expression, sympy.Basic):<EOL><INDENT>sympy_expression = self.expression<EOL><DEDENT>else:<EOL><INDENT>sympy_expression = sympy.sympify(self.expression)<EOL><DEDENT>poly = sympy_expression.as_poly(*sympy_expression.atoms(sympy.Symbol))<EOL>if poly is None:<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>return poly.is_quadratic<EOL><DEDENT><DEDENT> | 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 optlangs basic interface and should be used mainly where
speed is important.
Parameters
----------
coefficients : dict
A dictionary like {variable1: coefficient1, variable2: coefficient2, ...}
Returns
-------
None | 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.
Parameters
----------
variables : iterable
An iterable of Variable objects
Returns
-------
Coefficients : dict
{var1: coefficient, var2: coefficient ...} | 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. If None, new variables will be
constructed.
Example
----------
>>> const_copy = Constraint.clone(old_constraint) | 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,<EOL>"<STR_LIT>": self.active_when<EOL>}<EOL>return json_obj<EOL> | 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["<STR_LIT:name>"],<EOL>lb=json_obj["<STR_LIT>"],<EOL>ub=json_obj["<STR_LIT>"],<EOL>indicator_variable=indicator,<EOL>active_when=json_obj["<STR_LIT>"]<EOL>)<EOL> | 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.