INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Fake event handler same as: py: meth: WorldView. on_menu_exit () but force - disables mouse exclusivity.
def on_menu_exit(self,new): """ Fake event handler, same as :py:meth:`WorldView.on_menu_exit()` but force-disables mouse exclusivity. """ super(WorldViewMouseRotatable,self).on_menu_exit(new) self.world.peng.window.toggle_exclusivity(False)
Keyboard event handler handling only the escape key. If an escape key press is detected mouse exclusivity is toggled via: py: meth: PengWindow. toggle_exclusivity () \.
def on_key_press(self,symbol,modifiers): """ Keyboard event handler handling only the escape key. If an escape key press is detected, mouse exclusivity is toggled via :py:meth:`PengWindow.toggle_exclusivity()`\ . """ if symbol == key.ESCAPE: self.world.peng.w...
Handles mouse motion and rotates the attached camera accordingly. For more information about how to customize mouse movement see the class documentation here: py: class: WorldViewMouseRotatable () \.
def on_mouse_motion(self, x, y, dx, dy): """ Handles mouse motion and rotates the attached camera accordingly. For more information about how to customize mouse movement, see the class documentation here :py:class:`WorldViewMouseRotatable()`\ . """ if not self.world.peng...
Start a new step. returns a context manager which allows you to report an error
def step(self, step_name): """Start a new step. returns a context manager which allows you to report an error""" @contextmanager def step_context(step_name): if self.event_receiver.current_case is not None: raise Exception('cannot open a step within a step') ...
Converts the given resource name to a file path. A resource path is of the format <app >: <cat1 >. <cat2 >. <name > where cat1 and cat2 can be repeated as often as desired. ext is the file extension to use e. g.. png or similar. As an example the resource name peng3d: some. category. foo with the extension. png results...
def resourceNameToPath(self,name,ext=""): """ Converts the given resource name to a file path. A resource path is of the format ``<app>:<cat1>.<cat2>.<name>`` where cat1 and cat2 can be repeated as often as desired. ``ext`` is the file extension to use, e.g. ``.png`` or...
Returns whether or not the resource with the given name and extension exists. This must not mean that the resource is meaningful it simply signals that the file exists.
def resourceExists(self,name,ext=""): """ Returns whether or not the resource with the given name and extension exists. This must not mean that the resource is meaningful, it simply signals that the file exists. """ return os.path.exists(self.resourceNameToPath(name,ext)...
Adds a new texture category with the given name. If the category already exists it will be overridden.
def addCategory(self,name): """ Adds a new texture category with the given name. If the category already exists, it will be overridden. """ self.categories[name]={} self.categoriesTexCache[name]={} self.categoriesTexBin[name]=pyglet.image.atlas.TextureBin...
Gets the texture associated with the given name and category. category must have been created using: py: meth: addCategory () before. If it was loaded previously a cached version will be returned. If it was not loaded it will be loaded and inserted into the cache. See: py: meth: loadTex () for more information.
def getTex(self,name,category): """ Gets the texture associated with the given name and category. ``category`` must have been created using :py:meth:`addCategory()` before. If it was loaded previously, a cached version will be returned. If it was not loaded, it ...
Loads the texture of the given name and category. All textures currently must be PNG files although support for more formats may be added soon. If the texture cannot be found a missing texture will instead be returned. See: py: meth: getMissingTexture () for more information. Currently all texture mipmaps will be gener...
def loadTex(self,name,category): """ Loads the texture of the given name and category. All textures currently must be PNG files, although support for more formats may be added soon. If the texture cannot be found, a missing texture will instead be returned. See :py:meth...
Returns a texture to be used as a placeholder for missing textures. A default missing texture file is provided in the assets folder of the source distribution. It consists of a simple checkerboard pattern of purple and black this image may be copied to any project using peng3d for similar behavior. If this texture cann...
def getMissingTexture(self): """ Returns a texture to be used as a placeholder for missing textures. A default missing texture file is provided in the assets folder of the source distribution. It consists of a simple checkerboard pattern of purple and black, this image may be co...
Adds a new texture from the given image. img may be any object that supports Pyglet - style copying in form of the blit_to_texture () method. This can be used to add textures that come from non - file sources e. g. Render - to - texture.
def addFromTex(self,name,img,category): """ Adds a new texture from the given image. ``img`` may be any object that supports Pyglet-style copying in form of the ``blit_to_texture()`` method. This can be used to add textures that come from non-file sources, e.g. Render-t...
Gets the model object by the given name. If it was loaded previously a cached version will be returned. If it was not loaded it will be loaded and inserted into the cache.
def getModel(self,name): """ Gets the model object by the given name. If it was loaded previously, a cached version will be returned. If it was not loaded, it will be loaded and inserted into the cache. """ if name in self.modelobjcache: return self.m...
Loads the model of the given name. The model will also be inserted into the cache.
def loadModel(self,name): """ Loads the model of the given name. The model will also be inserted into the cache. """ m = model.Model(self.peng,self,name) self.modelobjcache[name]=m self.peng.sendEvent("peng3d:rsrc.model.load",{"peng":self.peng,"name":name...
Gets the model data associated with the given name. If it was loaded a cached copy will be returned. It it was not loaded it will be loaded and cached.
def getModelData(self,name): """ Gets the model data associated with the given name. If it was loaded, a cached copy will be returned. It it was not loaded, it will be loaded and cached. """ if name in self.modelcache: return self.modelcache[name] ...
Loads the model data of the given name. The model file must always be a. json file.
def loadModelData(self,name): """ Loads the model data of the given name. The model file must always be a .json file. """ path = self.resourceNameToPath(name,".json") try: data = json.load(open(path,"r")) except Exception: # Tempor...
Sets the background of the Container. Similar to: py: meth: peng3d. gui. SubMenu. setBackground () \ but only effects the region covered by the Container.
def setBackground(self,bg): """ Sets the background of the Container. Similar to :py:meth:`peng3d.gui.SubMenu.setBackground()`\ , but only effects the region covered by the Container. """ self.bg = bg if isinstance(bg,list) or isinstance(bg,tuple): if...
Adds a widget to this container. Note that trying to add the Container to itself will be ignored.
def addWidget(self,widget): """ Adds a widget to this container. Note that trying to add the Container to itself will be ignored. """ if self is widget: # Prevents being able to add the container to itself, causing a recursion loop on redraw return se...
Draws the submenu and its background. Note that this leaves the OpenGL state set to 2d drawing and may modify the scissor settings.
def draw(self): """ Draws the submenu and its background. Note that this leaves the OpenGL state set to 2d drawing and may modify the scissor settings. """ if not self.visible: # Simple visibility check, has to be tested to see if it works properly ...
Redraws the background and any child widgets.
def on_redraw(self): """ Redraws the background and any child widgets. """ x,y = self.pos sx,sy = self.size self.bg_vlist.vertices = [x,y, x+sx,y, x+sx,y+sy, x,y+sy] self.stencil_vlist.vertices = [x,y, x+sx,y, x+sx,y+sy, x,y+sy] if isinstance(self.bg,Backg...
Redraws the background and contents including scrollbar. This method will also check the scrollbar for any movement and will be automatically called on movement of the slider.
def on_redraw(self): """ Redraws the background and contents, including scrollbar. This method will also check the scrollbar for any movement and will be automatically called on movement of the slider. """ n = self._scrollbar.n self.offset_y = -n # Causes the con...
AABB Collision checker that can be used for most axis - aligned collisions. Intended for use in widgets to check if the mouse is within the bounds of a particular widget.
def mouse_aabb(mpos,size,pos): """ AABB Collision checker that can be used for most axis-aligned collisions. Intended for use in widgets to check if the mouse is within the bounds of a particular widget. """ return pos[0]<=mpos[0]<=pos[0]+size[0] and pos[1]<=mpos[1]<=pos[1]+size[1]
Adds a category with the given name. If the category already exists a: py: exc: KeyError will be thrown. Use: py: meth: updateCategory () instead if you want to update a category.
def addCategory(self,name,nmin=0,n=0,nmax=100): """ Adds a category with the given name. If the category already exists, a :py:exc:`KeyError` will be thrown. Use :py:meth:`updateCategory()` instead if you want to update a category. """ assert isinstance(name,base...
Smartly updates the given category. Only values that are given will be updated others will be left unchanged. If the category does not exist a: py: exc: KeyError will be thrown. Use: py: meth: addCategory () instead if you want to add a category.
def updateCategory(self,name,nmin=None,n=None,nmax=None): """ Smartly updates the given category. Only values that are given will be updated, others will be left unchanged. If the category does not exist, a :py:exc:`KeyError` will be thrown. Use :py:meth:`addCat...
Deletes the category with the given name. If the category does not exist a: py: exc: KeyError will be thrown.
def deleteCategory(self,name): """ Deletes the category with the given name. If the category does not exist, a :py:exc:`KeyError` will be thrown. """ if name not in self.categories: raise KeyError("No Category with name '%s'"%name) del self.categories...
Helper property containing the percentage this slider is filled. This property is read - only.
def p(self): """ Helper property containing the percentage this slider is "filled". This property is read-only. """ return (self.n-self.nmin)/max((self.nmax-self.nmin),1)
Adds a new layer to the stack optionally at the specified z - value. layer must be an instance of Layer or subclasses. z can be used to override the index of the layer in the stack. Defaults to - 1 for appending.
def addLayer(self,layer,z=-1): """ Adds a new layer to the stack, optionally at the specified z-value. ``layer`` must be an instance of Layer or subclasses. ``z`` can be used to override the index of the layer in the stack. Defaults to ``-1`` for appending. """ ...
Map a buffer region using this attribute as an accessor.
def _get_region(self, buffer, start, count): '''Map a buffer region using this attribute as an accessor. The returned region can be modified as if the buffer was a contiguous array of this attribute (though it may actually be interleaved or otherwise non-contiguous). The return...
Draw vertices in the domain.
def _draw(self, mode, vertex_list=None): '''Draw vertices in the domain. If `vertex_list` is not specified, all vertices in the domain are drawn. This is the most efficient way to render primitives. If `vertex_list` specifies a `VertexList`, only primitives in that list will b...
Patches the: py: mod: pyglet. graphics. vertexattribute \: py: mod: pyglet. graphics. vertexbuffer and: py: mod: pyglet. graphics. vertexdomain modules. This patch is only needed with Python 3. x and will be applied automatically when initializing: py: class: Peng () \. The patches consist of simply converting some lis...
def patch_float2int(): """ Patches the :py:mod:`pyglet.graphics.vertexattribute`\ , :py:mod:`pyglet.graphics.vertexbuffer` and :py:mod:`pyglet.graphics.vertexdomain` modules. This patch is only needed with Python 3.x and will be applied automatically when initializing :py:class:`Peng()`\ . The...
Registers the given pyglet - style event handler for the given pyglet event. This function allows pyglet - style event handlers to receive events bridged through the peng3d event system. Internally this function creates a lambda function that decodes the arguments and then calls the pyglet - style event handler. The ra...
def register_pyglet_handler(peng,func,event,raiseErrors=False): """ Registers the given pyglet-style event handler for the given pyglet event. This function allows pyglet-style event handlers to receive events bridged through the peng3d event system. Internally, this function creates a lambda f...
Adds a callback to the specified action. All other positional and keyword arguments will be stored and passed to the function upon activation.
def addAction(self,action,func,*args,**kwargs): """ Adds a callback to the specified action. All other positional and keyword arguments will be stored and passed to the function upon activation. """ if not hasattr(self,"actions"): self.actions = {} if...
Helper method that calls all callbacks registered for the given action.
def doAction(self,action): """ Helper method that calls all callbacks registered for the given action. """ if not hasattr(self,"actions"): return for f,args,kwargs in self.actions.get(action,[]): f(*args,**kwargs)
Generates a new ID. If reuse_ids was false the new ID will be read from an internal counter which is also automatically increased. This means that the newly generated ID is already reserved. If reuse_ids was true this method starts counting up from start_id until it finds an ID that is not currently known. Note that th...
def genNewID(self): """ Generates a new ID. If ``reuse_ids`` was false, the new ID will be read from an internal counter which is also automatically increased. This means that the newly generated ID is already reserved. If ``reuse_ids`` was true, this method sta...
Registers a name to the registry. name is the name of the object and must be a string. force_id can be optionally set to override the automatic ID generation and force a specific ID. Note that using force_id is discouraged since it may cause problems when reuse_ids is false.
def register(self,name,force_id=None): """ Registers a name to the registry. ``name`` is the name of the object and must be a string. ``force_id`` can be optionally set to override the automatic ID generation and force a specific ID. Note that u...
Takes in an object and normalizes it to its ID/ integer representation. Currently only integers and strings may be passed in else a: py: exc: TypeError will be thrown.
def normalizeID(self,in_id): """ Takes in an object and normalizes it to its ID/integer representation. Currently, only integers and strings may be passed in, else a :py:exc:`TypeError` will be thrown. """ if isinstance(in_id,int): assert in_id in sel...
Takes in an object and normalizes it to its name/ string. Currently only integers and strings may be passed in else a: py: exc: TypeError will be thrown.
def normalizeName(self,in_name): """ Takes in an object and normalizes it to its name/string. Currently, only integers and strings may be passed in, else a :py:exc:`TypeError` will be thrown. """ if isinstance(in_name,str): assert in_name in self._dat...
Sets the view used to the specified name \. The name must be known to the world or else a: py: exc: ValueError is raised.
def setView(self,name): """ Sets the view used to the specified ``name``\ . The name must be known to the world or else a :py:exc:`ValueError` is raised. """ if name not in self.world.views: raise ValueError("Invalid viewname for world!") self.viewnam...
Sets up the attributes used by: py: class: Layer3D () and calls: py: meth: Layer3D. predraw () \.
def predraw(self): """ Sets up the attributes used by :py:class:`Layer3D()` and calls :py:meth:`Layer3D.predraw()`\ . """ self.cam = self.view.cam super(LayerWorld,self).predraw()
Adds the given layer at the given Z Index. If z_index is not given the Z Index specified by the layer will be used.
def addLayer(self,layer,z_index=None): """ Adds the given layer at the given Z Index. If ``z_index`` is not given, the Z Index specified by the layer will be used. """ if z_index is None: z_index = layer.z_index i = 0 for l,z in self.layers: ...
Redraws the given layer.: raises ValueError: If there is no Layer with the given name.
def redraw_layer(self,name): """ Redraws the given layer. :raises ValueError: If there is no Layer with the given name. """ if name not in self._layers: raise ValueError("Layer %s not part of widget, cannot redraw") self._layers[name].on_redraw()
Draws all layers of this LayeredWidget. This should normally be unneccessary since it is recommended that layers use Vertex Lists instead of OpenGL Immediate Mode.
def draw(self): """ Draws all layers of this LayeredWidget. This should normally be unneccessary, since it is recommended that layers use Vertex Lists instead of OpenGL Immediate Mode. """ super(LayeredWidget,self).draw() for layer,_ in self.layers: l...
Deletes all layers within this LayeredWidget before deleting itself. Recommended to call if you are removing the widget but not yet exiting the interpreter.
def delete(self): """ Deletes all layers within this LayeredWidget before deleting itself. Recommended to call if you are removing the widget, but not yet exiting the interpreter. """ for layer,_ in self.layers: layer.delete() self.layers = [] ...
Called when the Layer should be redrawn. If a subclass uses the: py: meth: initialize () Method it is very important to also call the Super Class Method to prevent crashes.
def on_redraw(self): """ Called when the Layer should be redrawn. If a subclass uses the :py:meth:`initialize()` Method, it is very important to also call the Super Class Method to prevent crashes. """ super(WidgetLayer,self).on_redraw() if not self._initialized:...
Property to be used for setting and getting the border of the layer. Note that setting this property causes an immediate redraw.
def border(self): """ Property to be used for setting and getting the border of the layer. Note that setting this property causes an immediate redraw. """ if callable(self._border): return util.WatchingList(self._border(*(self.widget.pos+self.widget.size)),se...
Property to be used for setting and getting the offset of the layer. Note that setting this property causes an immediate redraw.
def offset(self): """ Property to be used for setting and getting the offset of the layer. Note that setting this property causes an immediate redraw. """ if callable(self._offset): return util.WatchingList(self._offset(*(self.widget.pos+self.widget.size)),se...
Returns the absolute position and size of the layer. This method is intended for use in vertex position calculation as the border and offset have already been applied. The returned value is a 4 - tuple of ( sx sy ex ey ) \. The two values starting with an s are the start position or the lower - left corner. The second ...
def getPos(self): """ Returns the absolute position and size of the layer. This method is intended for use in vertex position calculation, as the border and offset have already been applied. The returned value is a 4-tuple of ``(sx,sy,ex,ey)``\ . The two values ...
Returns the size of the layer with the border size already subtracted.
def getSize(self): """ Returns the size of the layer, with the border size already subtracted. """ return self.widget.size[0]-self.border[0]*2,self.widget.size[1]-self.border[1]*2
Adds an image to the internal registry. rsrc should be a 2 - tuple of ( resource_name category ) \.
def addImage(self,name,rsrc): """ Adds an image to the internal registry. ``rsrc`` should be a 2-tuple of ``(resource_name,category)``\ . """ self.imgs[name]=self.widget.peng.resourceMgr.getTex(*rsrc)
Switches the active image to the given name.: raises ValueError: If there is no such image
def switchImage(self,name): """ Switches the active image to the given name. :raises ValueError: If there is no such image """ if name not in self.imgs: raise ValueError("No image of name '%s'"%name) elif self.cur_img==name: return ...
Re - draws the text by calculating its position. Currently the text will always be centered on the position of the layer.
def redraw_label(self): """ Re-draws the text by calculating its position. Currently, the text will always be centered on the position of the layer. """ # Convenience variables x,y,_,_ = self.getPos() sx,sy = self.getSize() self._label.x ...
Re - draws the text by calculating its position. Currently the text will always be centered on the position of the layer.
def redraw_label(self): """ Re-draws the text by calculating its position. Currently, the text will always be centered on the position of the layer. """ # Convenience variables x,y,_,_ = self.getPos() sx,sy = self.getSize() if self.font_n...
Overrideable function that generates the colors to be used by various styles. Should return a 5 - tuple of ( bg o i s h ) \. bg is the base color of the background. o is the outer color it is usually the same as the background color. i is the inner color it is usually lighter than the background color. s is the shadow ...
def getColors(self): """ Overrideable function that generates the colors to be used by various styles. Should return a 5-tuple of ``(bg,o,i,s,h)``\ . ``bg`` is the base color of the background. ``o`` is the outer color, it is usually the same as the bac...
Called to generate the vertices used by this layer. The length of the output of this method should be three times the: py: attr: n_vertices attribute. See the source code of this method for more information about the order of the vertices.
def genVertices(self): """ Called to generate the vertices used by this layer. The length of the output of this method should be three times the :py:attr:`n_vertices` attribute. See the source code of this method for more information about the order of the vertices. ...
DEPRECATED Reads a mesh saved in the HDF5 format.
def read_h5(hdfstore, group = ""): """ DEPRECATED Reads a mesh saved in the HDF5 format. """ m = Mesh() m.elements.data = hdf["elements/connectivity"] m.nodes.data = hdf["nodes/xyz"] for key in hdf.keys(): if key.startswith("/nodes/sets"): k = key.replace("/nodes/sets/", "") m.nodes.s...
Reads a GMSH MSH file and returns a: class: Mesh instance.: arg path: path to MSH file.: type path: str
def read_msh(path): """ Reads a GMSH MSH file and returns a :class:`Mesh` instance. :arg path: path to MSH file. :type path: str """ elementMap = { 15:"point1", 1:"line2", 2:"tri3", 3:"quad4", 4:"tetra4", 5:"hexa8", ...
Reads Abaqus inp file
def read_inp(path): """ Reads Abaqus inp file """ def lineInfo(line): out = {"type": "data"} if line[0] == "*": if line[1] == "*": out["type"] = "comment" out["text"] = line[2:] else: out["type"] = "command" words = line[1:].split(",") out["value"...
Dumps the mesh to XDMF format.
def write_xdmf(mesh, path, dataformat = "XML"): """ Dumps the mesh to XDMF format. """ pattern = Template(open(MODPATH + "/templates/mesh/xdmf.xdmf").read()) attribute_pattern = Template(open(MODPATH + "/templates/mesh/xdmf_attribute.xdmf").read()) # MAPPINGS cell_map = { "tri3": 4, "quad4":...
Exports the mesh to the INP format.
def write_inp(mesh, path = None, maxwidth = 40, sections = "solid"): """ Exports the mesh to the INP format. """ def set_to_inp(sets, keyword): ss = "" for sk in sets.keys(): labels = sets[sk].loc[sets[sk]].index.values labels = list(labels) labels.sort() if len(labels)!= 0: ...
Connectivity builder using Numba for speed boost.
def _make_conn(shape): """ Connectivity builder using Numba for speed boost. """ shape = np.array(shape) Ne = shape.prod() if len(shape) == 2: nx, ny = np.array(shape) +1 conn = np.zeros((Ne, 4), dtype = np.int32) counter = 0 pattern = np.array([0,1,1+nx,nx]) ...
Returns a structured mesh.: arg shape: 2 or 3 integers ( eg: shape = ( 10 10 10 )).: type shape: tuple: arg dim: 2 or 3 floats ( eg: dim = ( 4. 2. 1. )): type dim: tuple.. note::
def structured_mesh(shape = (2,2,2), dim = (1.,1.,1.)): """ Returns a structured mesh. :arg shape: 2 or 3 integers (eg: shape = (10, 10, 10)). :type shape: tuple :arg dim: 2 or 3 floats (eg: dim = (4., 2., 1.)) :type dim: tuple .. note:: This function does not use GMSH for...
r Sets the node data.: arg nlabels: node labels. Items be strictly positive and int typed in 1D array - like with shape: math: ( N_n ).: type nlabels: 1D uint typed array - like: arg coords: node coordinates. Must be float typed 2D array - like of shape: math: ( N_n \ times 3 ).: type coords: 2D float typed array - lik...
def set_nodes(self, nlabels = [], coords = [], nsets = {}, **kwargs): r""" Sets the node data. :arg nlabels: node labels. Items be strictly positive and int typed in 1D array-like with shape :math:`(N_n)`. :type nlabels: 1D uint typed array-like :arg coords: node coordinates....
Sets the element data.: arg elabels: element labels. Items be strictly positive and int typed in 1D array - like with shape: math: ( N_e ).: type elabels: 1D uint typed array - like: arg types: element types chosen among argiope specific element types.: type types: str typed array - like: arg stypes: element types chos...
def set_elements(self, elabels = None, types = None, stypes = "", conn = None, esets = {}, surfaces = {}, materials = "", **kwargs): ""...
Sets the fields.
def set_fields(self, fields = None, **kwargs): """ Sets the fields. """ self.fields = [] if fields != None: for field in fields: self.fields.append(field)
Add the fields into the list of fields.
def add_fields(self, fields = None, **kwargs): """ Add the fields into the list of fields. """ if fields != None: for field in fields: self.fields.append(field)
Checks element definitions.
def check_elements(self): """ Checks element definitions. """ # ELEMENT TYPE CHECKING existing_types = set(self.elements.type.argiope.values.flatten()) allowed_types = set(ELEMENTS.keys()) if (existing_types <= allowed_types) == False: raise ValueError("Element types {0} not in know el...
Returns the dimension of the embedded space of each element.
def space(self): """ Returns the dimension of the embedded space of each element. """ return self.elements.type.argiope.map( lambda t: ELEMENTS[t].space)
Returns the number of vertices of eache element according to its type/
def nvert(self): """ Returns the number of vertices of eache element according to its type/ """ return self.elements.type.argiope.map( lambda t: ELEMENTS[t].nvert)
Returns the decomposition of the elements. Inputs: * into: must be in [ edges faces simplices angles ] * loc: None or labels of the chosen elements. * at: must be in [ labels coords ]
def split(self, into = "edges", loc = None, at = "labels", sort_index = True): """ Returns the decomposition of the elements. Inputs: * into: must be in ['edges', 'faces', 'simplices', 'angles'] * loc: None or labels of the chosen elements. * at: must be in ['labels', 'coords']...
Returns a dataframe containing volume and centroids of all the elements.
def centroids_and_volumes(self, sort_index = True): """ Returns a dataframe containing volume and centroids of all the elements. """ elements = self.elements out = [] for etype, group in self.elements.groupby([("type", "argiope", "")]): etype_info = ELEMENTS[etype] simplices_info = e...
Returns the internal angles of all elements and the associated statistics
def angles(self, zfill = 3): """ Returns the internal angles of all elements and the associated statistics """ elements = self.elements.sort_index(axis = 1) etypes = elements[("type", "argiope")].unique() out = [] for etype in etypes: etype_info = ELEMENTS[etype] angles_info = e...
Returns the aspect ratio of all elements.
def edges(self, zfill = 3): """ Returns the aspect ratio of all elements. """ edges = self.split("edges", at = "coords").unstack() edges["lx"] = edges.x[1]-edges.x[0] edges["ly"] = edges.y[1]-edges.y[0] edges["lz"] = edges.z[1]-edges.z[0] edges["l"] = np.linalg.norm(edges[["lx", "ly", "l...
Returns mesh quality and geometric stats.
def stats(self): """ Returns mesh quality and geometric stats. """ cv = self.centroids_and_volumes() angles = self.angles() edges = self.edges() return pd.concat([cv , angles[["stats"]], edges[["stats"]] ], axis = 1).sort_index(axis = 1)
Makes a node set from an element set.
def element_set_to_node_set(self, tag): """ Makes a node set from an element set. """ nodes, elements = self.nodes, self.elements loc = (elements.conn[elements[("sets", tag, "")]] .stack().stack().unique()) loc = loc[loc != 0] nodes[("sets", tag)] = False nodes.loc[loc, ("sets...
Converts a node set to surface.
def node_set_to_surface(self, tag): """ Converts a node set to surface. """ # Create a dummy node with label 0 nodes = self.nodes.copy() dummy = nodes.iloc[0].copy() dummy["coords"] *= np.nan dummy["sets"] = True nodes.loc[0] = dummy # Getting element surfaces element_surface...
Creates elements sets corresponding to a surface.
def surface_to_element_sets(self, tag): """ Creates elements sets corresponding to a surface. """ surface = self.elements.surfaces[tag] for findex in surface.keys(): if surface[findex].sum() != 0: self.elements[("sets", "_SURF_{0}_FACE{1}" .format(tag, findex[1:]),...
Returns the mesh as matplotlib polygon collection. ( tested only for 2D meshes )
def to_polycollection(self, *args, **kwargs): """ Returns the mesh as matplotlib polygon collection. (tested only for 2D meshes) """ from matplotlib import collections nodes, elements = self.nodes, self.elements.reset_index() verts = [] index = [] for etype, gro...
Returns the mesh as a matplotlib. tri. Triangulation instance. ( 2D only )
def to_triangulation(self): """ Returns the mesh as a matplotlib.tri.Triangulation instance. (2D only) """ from matplotlib.tri import Triangulation conn = self.split("simplices").unstack() coords = self.nodes.coords.copy() node_map = pd.Series(data = np.arange(len(coords)), index = coords.i...
Returns fields metadata as a dataframe.
def fields_metadata(self): """ Returns fields metadata as a dataframe. """ return (pd.concat([f.metadata() for f in self.fields], axis = 1) .transpose() .sort_values(["step_num", "frame", "label", "position"]))
Returns metadata as a dataframe.
def metadata(self): """ Returns metadata as a dataframe. """ return pd.Series({ "part": self.part, "step_num": self.step_num, "step_label": self.step_label, "frame": self.frame, "frame_value": self.frame_value, "label": self.label, ...
Checks if required directories exist and creates them if needed.
def make_directories(self): """ Checks if required directories exist and creates them if needed. """ if os.path.isdir(self.workdir) == False: os.mkdir(self.workdir)
Runs the post - proc script.
def run_postproc(self): """ Runs the post-proc script. """ t0 = time.time() if self.verbose: print('#### POST-PROCESSING "{0}" USING POST-PROCESSOR "{1}"'.format(self.label, self.solver.upper())) if self.solver == "abaqus": command =...
Makes the mesh using gmsh.
def run_gmsh(self): """ Makes the mesh using gmsh. """ argiope.utils.run_gmsh(gmsh_path = self.gmsh_path, gmsh_space = self.gmsh_space, gmsh_options = self.gmsh_options, name = self.file_name + ".geo", ...
Reads an history output report.
def read_history_report(path, steps, x_name = None): """ Reads an history output report. """ data = pd.read_csv(path, delim_whitespace = True) if x_name != None: data[x_name] = data.X del data["X"] data["step"] = 0 t = 0. for i in range(len(steps)): dt = steps[i].duration loc = data...
Reads a field output report.
def read_field_report(path, data_flag = "*DATA", meta_data_flag = "*METADATA"): """ Reads a field output report. """ text = open(path).read() mdpos = text.find(meta_data_flag) dpos = text.find(data_flag) mdata = io.StringIO( "\n".join(text[mdpos:dpos].split("\n")[1:])) data = io.StringIO( "\n".join(text...
Converts a list - like to string with given line width.
def list_to_string(l = range(200), width = 40, indent = " "): """ Converts a list-like to string with given line width. """ l = [str(v) + "," for v in l] counter = 0 out = "" + indent for w in l: s = len(w) if counter + s > width: out += "\n" + indent ...
Returns an Abaqus INP formated string for a given linear equation.
def _equation(nodes = (1, 2), dofs = (1, 1), coefficients = (1., 1.), comment = None): """ Returns an Abaqus INP formated string for a given linear equation. """ N = len(nodes) if comment == None: out = "" else: out = "**EQUATION: {0}\n".format(comment) out+= "*E...
Returns a set as inp string with unsorted option.
def _unsorted_set(df, label, **kwargs): """ Returns a set as inp string with unsorted option. """ out = "*NSET, NSET={0}, UNSORTED\n".format(label) labels = df.index.values return out + argiope.utils.list_to_string(labels, **kwargs)
Parses the API response and raises appropriate errors if raise_errors was set to True
def parse_response(self, response): """Parses the API response and raises appropriate errors if raise_errors was set to True :param response: response from requests http call :returns: dictionary of response :rtype: dict """ payload = None try: ...
Builds the url for the specified method and arguments and returns the response as a dictionary.
def _get(self, method, **kwargs): """Builds the url for the specified method and arguments and returns the response as a dictionary. """ payload = kwargs.copy() payload['api_key'] = self.api_key payload['api_secret'] = self.api_secret to = payload.pop('to', None...
Returns the material definition as a string in Abaqus INP format.
def write_inp(self): """ Returns the material definition as a string in Abaqus INP format. """ template = self.get_template() return template.substitute({"class": self.__class__.__name__, "label": self.label}).strip()
Returns the material definition as a string in Abaqus INP format.
def write_inp(self): """ Returns the material definition as a string in Abaqus INP format. """ template = self.get_template() plastic_table = self.get_plastic_table() return template.substitute({ "class": self.__class__.__name__, "label": self.label, "young_modulus": self...
Calculates the plastic data
def get_plastic_table(self): """ Calculates the plastic data """ E = self.young_modulus sy = self.yield_stress n = self.hardening_exponent eps_max = self.max_strain Np = self.strain_data_points ey = sy/E s = 10.**np.linspace(0., np.log10(eps_max/ey), Np) strain = e...
Calculates the plastic data
def get_plastic_table(self): """ Calculates the plastic data """ K = self.consistency sy = self.yield_stress n = self.hardening_exponent eps_max = self.max_strain Np = self.strain_data_points plastic_strain = np.linspace(0., eps_max, Np) stress = sy + K * plastic_strain...
Returns the DNA/ DNA melting temp using nearest - neighbor thermodynamics.
def temp(s, DNA_c=5000.0, Na_c=10.0, Mg_c=20.0, dNTPs_c=10.0, uncorrected=False): ''' Returns the DNA/DNA melting temp using nearest-neighbor thermodynamics. This function returns better results than EMBOSS DAN because it uses updated thermodynamics values and takes into account initialization paramete...
Writes a xy_report based on xy data.
def write_xy_report(odb, path, tags, columns, steps): """ Writes a xy_report based on xy data. """ xyData = [session.XYDataFromHistory(name = columns[i], odb = odb, outputVariableName = tags[i], steps = steps) for i in xrange(len(tags))]...
Writes a field report and rewrites it in a cleaner format.
def write_field_report(odb, path, label, argiope_class, variable, instance, output_position, step = -1, frame = -1, sortItem='Node Label'): """ Writes a field report and rewrites it in a cleaner format. """ stepKeys = get_steps(odb) step = xrange(len(stepKeys))[step] frame = xrange(g...
Display a dashboard from the dashboard file ( s ) provided in the DASHBOARDS Paths and/ or URLs for dashboards ( URLs must secrets with http or https )
def start(dashboards, once, secrets): """Display a dashboard from the dashboard file(s) provided in the DASHBOARDS Paths and/or URLs for dashboards (URLs must secrets with http or https) """ if secrets is None: secrets = os.path.join(os.path.expanduser("~"), "/.doodledashboard/secrets") ...
View the output of the datafeeds and/ or notifications used in your DASHBOARDS
def view(action, dashboards, secrets): """View the output of the datafeeds and/or notifications used in your DASHBOARDS""" if secrets is None: secrets = os.path.join(os.path.expanduser("~"), "/.doodledashboard/secrets") try: loaded_secrets = try_read_secrets_file(secrets) except Invali...
List components that are available on your machine
def list(component_type): """List components that are available on your machine""" config_loader = initialise_component_loader() component_types = sorted({ "displays": lambda: config_loader.load_by_type(ComponentType.DISPLAY), "datafeeds": lambda: config_loader.load_by_type(ComponentType.D...
Parses the section of configuration pertaining to a component: param config: dict of specific config section: return:
def parse(self, config): """ Parses the section of configuration pertaining to a component :param config: dict of specific config section :return: """ if "type" not in config: raise InvalidConfigurationException("The dashboard configuration has no...