Search is not available for this dataset
text
stringlengths
75
104k
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...
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...
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)
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. """ ...
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...
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...
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...
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...
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...
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)
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...
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...
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...
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...
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...
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()
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: ...
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()
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...
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 = [] ...
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:...
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...
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...
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 ...
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
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)
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 ...
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 ...
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...
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...
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. ...
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...
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", ...
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"...
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":...
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: ...
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]) ...
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...
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....
def set_elements(self, elabels = None, types = None, stypes = "", conn = None, esets = {}, surfaces = {}, materials = "", **kwargs): ""...
def set_fields(self, fields = None, **kwargs): """ Sets the fields. """ self.fields = [] if fields != None: for field in fields: self.fields.append(field)
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)
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...
def space(self): """ Returns the dimension of the embedded space of each element. """ return self.elements.type.argiope.map( lambda t: ELEMENTS[t].space)
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)
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']...
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...
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...
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...
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)
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...
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...
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:]),...
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...
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...
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"]))
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, ...
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)
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 =...
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", ...
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...
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...
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 ...
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...
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)
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: ...
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...
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()
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...
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...
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...
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...
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))]...
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...
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") ...
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...
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...
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...
def err_msg(self, instance, value): """Return an error message for use in exceptions thrown by subclasses. """ if not hasattr(self, "name"): # err_msg will be called by the composed descriptor return "" return ( "Attempted to set the {f_type} ...
def exc_thrown_by_descriptor(): """Return True if the last exception was thrown by a Descriptor instance. """ traceback = sys.exc_info()[2] tb_locals = traceback.tb_frame.f_locals # relying on naming convention to get the object that threw # the exception ...
def _set_data(self): """ This method will be called to set Series data """ if getattr(self, 'data', False) and not getattr(self, '_x', False) and not getattr(self, '_y', False): _x = XVariable() _y = YVariable() _x.contribute_to_class(self, 'X', self.d...
def _get_axis_mode(self, axis): "will get the axis mode for the current series" if all([isinstance(getattr(s, axis), TimeVariable) for s in self._series]): return 'time' return None
def _set_options(self): "sets the graph ploting options" # this is aweful # FIXME: Axis options should be passed completly by a GraphOption if 'xaxis' in self._options.keys(): self._options['xaxis'].update( {'mode' : self._get_axis_mode(XAxis._var_name...
def create_init(attrs): """Create an __init__ method that sets all the attributes necessary for the function the Descriptor invokes to check the value. """ args = ", ".join(attrs) vals = ", ".join(['getattr(self, "{}")'.format(attr) for attr in attrs]) attr_lines = "\n ".join( ["...
def create_setter(func, attrs): """Create the __set__ method for the descriptor.""" def _set(self, instance, value, name=None): args = [getattr(self, attr) for attr in attrs] if not func(value, *args): raise ValueError(self.err_msg(instance, value)) return _set
def make_class(clsname, func, attrs): """Turn a funcs list element into a class object.""" clsdict = {"__set__": create_setter(func, attrs)} if len(attrs) > 0: clsdict["__init__"] = create_init(attrs) clsobj = type(str(clsname), (Descriptor, ), clsdict) clsobj.__doc__ = docstrings.get(clsnam...
def cycle(self): """ Cycles through notifications with latest results from data feeds. """ messages = self.poll_datafeeds() notifications = self.process_notifications(messages) self.draw_notifications(notifications)
def try_convert(value): """Convert value to a numeric value or raise a ValueError if that isn't possible. """ convertible = ForceNumeric.is_convertible(value) if not convertible or isinstance(value, bool): raise ValueError if isinstance(str(value), str): ...
def str_to_num(str_value): """Convert str_value to an int or a float, depending on the numeric value represented by str_value. """ str_value = str(str_value) try: return int(str_value) except ValueError: return float(str_value)
def plot(parser, token): """ Tag to plot graphs into the template """ tokens = token.split_contents() tokens.pop(0) graph = tokens.pop(0) attrs = dict([token.split("=") for token in tokens]) if 'id' not in attrs.keys(): attrs['id'] = ''.join([chr(choice(range(65, 90))) for i i...
def force_unicode(raw): '''Try really really hard to get a Unicode copy of a string. First try :class:`BeautifulSoup.UnicodeDammit` to try to force to Unicode; if that fails, assume UTF-8 encoding, and ignore all errors. :param str raw: string to coerce :return: Unicode approximation of `raw` ...
def make_clean_html(raw, stream_item=None, encoding=None): '''Get a clean text representation of presumed HTML. Treat `raw` as though it is HTML, even if we have no idea what it really is, and attempt to get a properly formatted HTML document with all HTML-escaped characters converted to their unicode....
def uniform_html(html): '''Takes a utf-8-encoded string of HTML as input and returns a new HTML string with fixed quoting and close tags, which generally should not break any of the offsets and makes it easier for functions like :func:`streamcorpus_pipeline.offsets.char_offsets_to_xpaths` to ope...
def is_matching_mime_type(self, mime_type): '''This implements the MIME-type matching logic for deciding whether to run `make_clean_html` ''' if len(self.include_mime_types) == 0: return True if mime_type is None: return False mime_type = mime_typ...
def domain_name_cleanse(raw_string): '''extract a lower-case, no-slashes domain name from a raw string that might be a URL ''' try: parts = urlparse(raw_string) domain = parts.netloc.split(':')[0] except: domain = '' if not domain: domain = raw_string if not d...
def domain_name_left_cuts(domain): '''returns a list of strings created by splitting the domain on '.' and successively cutting off the left most portion ''' cuts = [] if domain: parts = domain.split('.') for i in range(len(parts)): cuts.append( '.'.join(parts[i:])) r...
def make_hash_kw(self, tok): '''Get a Murmur hash and a normalized token. `tok` may be a :class:`unicode` string or a UTF-8-encoded byte string. :data:`DOCUMENT_HASH_KEY`, hash value 0, is reserved for the document count, and this function remaps that value. :param tok...
def collect_words(self, si): '''Collect all of the words to be indexed from a stream item. This scans `si` for all of the configured tagger IDs. It collects all of the token values (the :attr:`streamcorpus.Token.token`) and returns a :class:`collections.Counter` of them. ...
def index(self, si): '''Record index records for a single document. Which indexes this creates depends on the parameters to the constructor. This records all of the requested indexes for a single document. ''' if not si.body.clean_visible: logger.warn('stre...
def invert_hash(self, tok_hash): '''Get strings that correspond to some hash. No string will correspond to :data:`DOCUMENT_HASH_KEY`; use :data:`DOCUMENT_HASH_KEY_REPLACEMENT` instead. :param int tok_hash: Murmur hash to query :return: list of :class:`unicode` strings ...