class FEGridIdxSlice(HasTraits): '''General implementation of a slice within the FEGrid ''' implements(IFEGridSlice) fe_grid = WeakRef('ibvpy.mesh.fe_grid.FEGrid') grid_slice = Any dof_grid_slice = Property(depends_on='fe_grid.dof_grid') @cached_property def _get_dof_grid_slice(self): return self.fe_grid.dof_grid[self.grid_slice] geo_grid_slice = Property(depends_on='fe_grid.geo_grid') @cached_property def _get_geo_grid_slice(self): return self.fe_grid.geo_grid[self.grid_slice] elem_grid = Property def _get_elem_grid(self): return self.dof_grid_slice.elem_grid elems = Property def _get_elems(self): return self.dof_grid_slice.elems dof_nodes = Property def _get_dof_nodes(self): return self.dof_grid_slice.nodes dofs = Property def _get_dofs(self): return self.dof_grid_slice.dofs dof_X = Property def _get_dof_X(self): return self.dof_grid_slice.point_X_arr geo_nodes = Property def _get_geo_nodes(self): return self.geo_grid_slice.nodes geo_x = Property def _get_geo_x(self): return self.geo_grid_slice.point_x_arr geo_X = Property def _get_geo_X(self): return self.geo_grid_slice.point_X_arr
class CellView(HasTraits): '''Get the element numbers. ''' implements(ICellView) cell_idx = Int(-1) cell_grid = WeakRef(ICellArraySource) def set_cell(self, cell_idx): '''Method to be overloaded by subclasses. The subclass can fetch the data required from the cell_grid ''' self.cell_idx = cell_idx self.set_cell_traits() def set_cell_traits(self): '''Specialize this function to fetch the cell data from the array source. ''' pass def redraw(self): '''No plotting defined by default''' pass view = View(Item('cell_idx'), resizable=True)
class MongoAgentDB(HasTraits): implements(IAgentStorage) db_name = 'pynetsym_agents' def __init__(self): self.client = MongoClient() self.client.drop_database(self.db_name) self.agents_db = self.client[self.db_name].agents def _mktypename(self, obj): cls = type(obj) return '%s.%s' % (cls.__module__, cls.__name__) def store(self, node): node.id = int(node.id) state = node.__getstate__() del state['__traits_version__'] state['__agenttype__'] = self._mktypename(node) self.agents_db.update(dict(_id=node.id), {'$set': state}, upsert=True) def recover(self, identifier): identifier = int(identifier) state = self.agents_db.find_one({'_id': identifier}) agent_type = \ jsonpickle.unpickler.loadclass(state.pop('__agenttype__')) del state['_id'] return agent_type(**state)
class NxRandomSelector(RepeatedNodesRandomSelector): implements(IRandomSelector) # FIXME: this can be made faster! graph = DelegatesTo('graph_container', prefix='nx_graph') def random_edge(self): return random.choice(self.graph.edges()) def random_node(self): return random.choice(self.graph.nodes()) def prepare_preferential_attachment(self): self.repeated_nodes = np.zeros( dtype=np.int32, shape=(self.graph.number_of_edges() * 2 + self.graph.number_of_nodes())) degrees = nx.degree(self.graph) counter = 0 for node, degree in degrees.iteritems(): extraction_probability = degree + 1 self.repeated_nodes[counter:counter + extraction_probability] = node counter += extraction_probability self._initialized_preferential_attachment = True
class MinimalClassInfo(HasTraits): """ Structure to hold module and name of a class. Users can supply their own version of this if they wish by assigning ClassLibrary.class_factory to their own class or factory method. The only requirements are that it take module and name as keyword arguments. """ implements(IMinimalClassInfo) ########################################################################## # IBasicFunctionInfo traits ########################################################################## # The name of the class. name = Str # The name of the module/package where the class lives. module = Str ########################################################################## # object interface ########################################################################## def __repr__(self): return '%s(%s, %s)' % (self.__class__.__name__, self.module, self.name) def __eq__(self, other): """ Objects are considered equal if modules and names are the same. """ return (self.name == other.name) and (self.module == other.module)
class SystemMetrics(MSystemMetrics, HasTraits): """ The toolkit specific implementation of a SystemMetrics. See the ISystemMetrics interface for the API documentation. """ implements(ISystemMetrics) #### 'ISystemMetrics' interface ########################################### screen_width = Property(Int) screen_height = Property(Int) dialog_background_color = Property(Tuple) ########################################################################### # Private interface. ########################################################################### def _get_screen_width(self): return QtGui.QApplication.instance().desktop().screenGeometry().width() def _get_screen_height(self): return QtGui.QApplication.instance().desktop().screenGeometry().height( ) def _get_dialog_background_color(self): color = QtGui.QApplication.instance().palette().color( QtGui.QPalette.Window) return (color.redF(), color.greenF(), color.blueF())
class FileResourceProtocol(HasTraits): """ A resource protocol for a local file system. """ implements(IResourceProtocol) ########################################################################### # 'IResourceProtocol' interface. ########################################################################### def file(self, address): """ Return a readable file-like object for the specified address. """ # Opened in binary mode to be consistent with package resources. This # means, for example, that line-endings will not be converted. try: f = file(address, 'rb') except IOError, e: if e.errno == errno.ENOENT: raise NoSuchResourceError(address) else: raise return f
class TileManager(HasTraits): """ Base class for tile managers """ implements(ITileManager) min_level = Int(0) max_level = Int(17) tile_ready = Event process_raw = Callable def get_tile_size(self): """ Return size of tile """ return 256 def get_tile(self, zoom, row, col): """ Request a tile at row and col for a particular zoom level """ raise Exception() def convert_to_tilenum(self, x, y, zoom): """ Convert screen space to a particular tile reference """ raise Exception()
class ConstantFrictionAndFreeLength(RF): ''' ''' implements(IRF) title = Str('pull-out with constant friction and free length ') tau = Float(8, auto_set=False, enter_set=True, distr=['uniform']) # free length l = Float(1, auto_set=False, enter_set=True, distr=['uniform', 'norm']) E = Float(70e9, auto_set=False, enter_set=True, distr=['uniform']) A = Float(5.30929158457e-10, auto_set=False, enter_set=True, distr=['uniform', 'weibull_min']) # waviness in strains slack = Float(0.1, auto_set=False, enter_set=True, distr=['uniform']) u = Float(auto_set=False, enter_set=True, ctrl_range=(0.0, 1.0, 10)) def __call__(self, u, tau, l, E, A, slack): return -l * (1 + slack) * tau * Heaviside(u - l * (slack)) + \ + sqrt((l * (1 + slack) * tau) ** 2 + 2 * E * A * (u - (l * slack)) * Heaviside(u - l * (slack)))
class LorenzIPlottable2dAdapter(Adapter, IModel3dIPlottable2dMixin): implements(IPlottable2d) adaptee = Instance(Lorenz) plot_type = Str('line')
class MOTD(HasTraits): """ The 'Message of the Day' implementation! """ implements(IMOTD) # The default message is used when there are no other messages! DEFAULT_MESSAGE = Message(author='Anon', text='Work hard and be good to your Mother') # The list of possible messages. messages = List(IMessage) ########################################################################### # 'IMOTD' interface. ########################################################################### def motd(self): """ Prints a random message. """ if len(self.messages) > 0: message = choice(self.messages) else: message = self.DEFAULT_MESSAGE return message
class PhiFnGeneralExtended(PhiFnGeneral): implements(IPhiFn) factor_eps_fail = Float(1.0) def get_value(self, e_max, *c_list): ''' Evaluate the integrity of a particular microplane. Overload the 'get_value' method of 'PhiFnGeneral' and add an additional constant level and a drop down to zero after failure strain has been reached. ''' eps_last = self.mfn.xdata[-1] phi_last = self.mfn.ydata[-1] eps_fail = eps_last * self.factor_eps_fail if e_max <= eps_last: return super(PhiFnGeneralExtended, self).get_value(e_max, *c_list) elif (e_max > eps_last and e_max < eps_fail): return phi_last else: return 1e-50 def get_plot_range(self): '''plot the extended phi function''' return self.mfn.xdata[ 0], self.mfn.xdata[-1] * self.factor_eps_fail * 1.1
class SDomain(IBVResource): implements(ISDomain) # service specifiers - used to link the service to this object service_class = 'ibvpy.plugins.sdomain_service.SDomainService' service_attrib = 'sdomain' subdomains = List([]) xdomains = List([]) dots = WeakRef(ITStepperEval) def new_scontext(self): ''' Setup a new spatial context. ''' sctx = SContext() sctx.sdomain = self return sctx def register_mv_pipelines(self, e): ''' Register the visualization pipelines in mayavi engine (empty by default) ''' pass traits_view = View(Item('dots@', show_label=False), resizable=True, scrollable=True)
class RosslerIPlottable2dAdapter(Adapter, IModel3dIPlottable2dMixin): implements(IPlottable2d) adaptee = Instance(Rossler) plot_type = Str('line')
class AgentDB(HasTraits): implements(IAgentStorage) pickling_module = Instance(ISerialize, allow_none=False) storage = Dict(key_trait=Either(CInt, Str), value_trait=Str, allow_none=False) def __init__(self, pickling_module, storage): """ Creates a new AgentDB. :param pickling_module: something that is able to pickle Python objects. Pickle interface expected (loads and dumps). :param storage: object that can store pickled objects. Dictionary __getitem__/__setitem__ interface expected. :type storage: :class:`collections.MutableMapping """ self.storage = storage self.pickling_module = pickling_module def recover(self, identifier): try: node = self.pickling_module.loads(self.storage[identifier]) return node except KeyError as e: raise MissingNode(e) def store(self, node): s = self.pickling_module.dumps(node) self.storage[node.id] = s
class FECellView(CellView): geo_view = Instance(GeoCellView) def _geo_view_default(self): return GeoCellView() dof_view = Instance(DofCellView) def _dof_view_default(self): return DofCellView() implements(ICellView) @on_trait_change('cell_grid') def _reset_view_links(self): self.geo_view.cell_grid = self.cell_grid.geo_grid self.dof_view.cell_grid = self.cell_grid.dof_grid def set_cell_traits(self): self.dof_view.cell_idx = self.cell_idx self.dof_view.set_cell_traits() self.geo_view.cell_idx = self.cell_idx self.geo_view.set_cell_traits() def redraw(self): self.dof_view.redraw() self.geo_view.redraw() traits_view = View(HSplit(Item('geo_view@', show_label=False), Item('dof_view@', show_label=False)), resizable=True, scrollable=True, width=0.6, height=0.2)
class AnITabularAdapter ( HasPrivateTraits ): implements( ITabularAdapter ) #-- Implementation of the ITabularAdapter Interface ------------------------ # The row index of the current item being adapted: row = Int # The current column id being adapted (if any): column = Any # Current item being adapted: item = Any # The current value (if any): value = Any # The list of columns the adapter supports. The items in the list have the # same format as the *columns* trait in the *TabularAdapter* class, with the # additional requirement that the *string* values must correspond to a # *string* value in the associated *TabularAdapter* class. columns = List( Str ) # Does the adapter know how to handle the current *item* or not: accepts = Bool( True ) # Does the value of *accepts* depend only upon the type of *item*? is_cacheable = Bool( True )
class WXContainer(WXComponent): """ A wxPython implementation of Container. The WXContainer class serves as a base class for other container widgets. It is not meant to be used directly. See Also -------- Container """ implements(IContainerImpl) #--------------------------------------------------------------------------- # IContainerImpl interface #--------------------------------------------------------------------------- def create_style_handler(self): """ Creates and sets the window style handler. """ pass def initialize_style(self): """ Initializes the style for the window. """ pass
class TaskPane(MTaskPane): """ The toolkit-specific implementation of a TaskPane. See the ITaskPane interface for API documentation. """ implements(ITaskPane) ########################################################################### # 'ITaskPane' interface. ########################################################################### def create(self, parent): """ Create and set the toolkit-specific control that represents the pane. """ self.control = QtGui.QWidget(parent) def destroy(self): """ Destroy the toolkit-specific control that represents the pane. """ if self.control is not None: self.control.hide() self.control.setParent(None) self.control = None def set_focus(self): """ Gives focus to the control that represents the pane. """ if self.control is not None: set_focus(self.control)
class CBShortFiber(RF): ''' Micromechanical response of a short fiber bridging a crack ''' implements(IRF) xi = Float(distr=['weibull_min', 'uniform']) E_f = Float(distr=['uniform', 'norm']) r = Float(distr=['uniform', 'norm']) le = Float(distr=['uniform']) tau = Float(distr=['norm', 'uniform', 'weibull_min']) snub = Float(distr=['uniform', 'norm']) phi = Float(distr=['sin2x', 'uniform']) w = Float C_code = '' def __call__(self, w, tau, r, E_f, le, phi, snub, xi, epsm_softening): T = 2. * tau / r # debonding stage ef0_deb = np.sqrt(T * w / E_f) # crack opening at which debonding is finished w0 = le ** 2 * T / E_f # pulling out stage - the fiber is pulled out from the # side with the shorter embedded length only ef0_pull = (le + w0 - w) * T / E_f ef0 = (ef0_deb * (w < w0) + ef0_pull * (w > w0)) * np.exp(phi*snub) + epsm_softening # include breaking strain ef0 = ef0 * (ef0 < xi) * (ef0 > 0.0) return ef0
class FETS1D52ULRH(FETSEval): ''' Fe Bar 2 nodes, deformation ''' implements(IFETSEval) debug_on = True # Dimensional mapping dim_slice = slice(0, 1) n_e_dofs = Int(4) n_nodal_dofs = Int(2) dof_r = Array(value=[[-1], [1]]) geo_r = Array(value=[[-1], [1]]) vtk_r = Array(value=[[-1.], [1.]]) vtk_cells = [[0, 1]] vtk_cell_types = 'Line' def _get_ip_coords(self): offset = 1e-6 return np.array([[-1 + offset, 0., 0.], [1 - offset, 0., 0.]]) def _get_ip_weights(self): return np.array([1., 1.], dtype=float) # Integration parameters # ngp_r = 2 def get_N_geo_mtx(self, r_pnt): ''' Return geometric shape functions @param r_pnt: ''' r = r_pnt[0] N_mtx = np.array([[0.5 - r / 2., 0.5 + r / 2.]]) return N_mtx def get_dNr_geo_mtx(self, r_pnt): ''' Return the matrix of shape function derivatives. Used for the conrcution of the Jacobi matrix. ''' return np.array([[-1. / 2, 1. / 2]]) def get_N_mtx(self, r_pnt): ''' Return shape functions @param r_pnt:local coordinates ''' return self.get_N_geo_mtx(r_pnt) def get_dNr_mtx(self, r_pnt): ''' Return the derivatives of the shape functions ''' return self.get_dNr_geo_mtx(r_pnt)
class ImageResource(MImageResource, HasTraits): """ The toolkit specific implementation of an ImageResource. See the IImageResource interface for the API documentation. """ implements(IImageResource) #### Private interface #################################################### # The resource manager reference for the image. _ref = Any #### 'ImageResource' interface ############################################ absolute_path = Property(Unicode) name = Unicode search_path = List ########################################################################### # 'ImageResource' interface. ########################################################################### def create_bitmap(self, size=None): return self.create_image(size).ConvertToBitmap() def create_icon(self, size=None): ref = self._get_ref(size) if ref is not None: icon = wx.Icon(self.absolute_path, wx.BITMAP_TYPE_ICO) else: image = self._get_image_not_found_image() # We have to convert the image to a bitmap first and then create an # icon from that. bmp = image.ConvertToBitmap() icon = wx.EmptyIcon() icon.CopyFromBitmap(bmp) return icon ########################################################################### # Private interface. ########################################################################### def _get_absolute_path(self): # FIXME: This doesn't quite wotk the new notion of image size. We # should find out who is actually using this trait, and for what! # (AboutDialog uses it to include the path name in some HTML.) ref = self._get_ref() if ref is not None: absolute_path = os.path.abspath(self._ref.filename) else: absolute_path = self._get_image_not_found().absolute_path return absolute_path
class BasicAdapter(HasTraits): """ Adapter for previewing, other things. What is shown in "MATERIAL" tab. populate_object() method used to show an instance of the material. """ implements(IAdapter) mat_class = 'bulk' #<-- Don't change, needed by layer_editor name=Str('Basic Material') source=Str('Abstract Base Class for material') notes=Str('Not Found') matobject = Instance(IMaterial) preview = Button hide_preview = Button testview = Any # SHows material after preview fired apikey = 'basic' #<-- Materials API identifier def _preview_fired(self): """ View the material as plot""" if self.matobject == None: self.populate_object() self.testview = self.matobject.mview # self.matobject.edit_traits(kind='livemodal') #Modal screws up objects for some reason # self.destroy_object() def populate_object(self): """Instantiate selected object.""" # Imports must be in here because some objects need to access apikey, # but have infinite recursion if importing materials. For example, # if composite materials needs to set materia1 to a composite material, # this will lead to recursive imports. from materialapi import ALLMATERIALS self.matobject = ALLMATERIALS[self.apikey]() def destroy_object(self): """Method used to destroy an object; not sure if ever will be useful or if it even destroys the object...""" self.matobject = None self.testview = None def _hide_preview_fired(self): self.destroy_object() basicgroup=Group( Item('name', style='readonly'), #THESE ARENT READ ONLY! Item('source', style='readonly'), Item('notes'), Item('preview', show_label=False, visible_when='testview is None'), Item('hide_preview', show_label=False, visible_when='testview is not None'), Item('testview', visible_when='testview is not None', show_label=False, editor=InstanceEditor(), style='custom', ) ) traitsview= View(Include('basicgroup'), resizable=True, )
class Lorenz(HasTraits): """ The model object for the Lorenz attractor. """ implements(IModel3d) #### 'IModel3d' interface ################################################# name = Unicode('Lorenz Attractor') points = Property( Array, depends_on=['prandtl', 'rayleigh', 'beta', 'initial_point', 'times']) #### 'Lorenz' interface ################################################### # Equation parameters. prandtl = Float(10.0, auto_set=False, enter_set=True) rayleigh = Float(28.0, auto_set=False, enter_set=True) beta = Float(8.0 / 3.0, auto_set=False, enter_set=True) # Integration parameters. initial_point = Array(value=[0.0, 1.0, 0.0]) time_start = Float(0.0) time_stop = Float(100.0) time_step = Float(0.01) times = Property(Array, depends_on='time_start, time_stop, time_step') # Configuration view. view = View(Item('prandtl'), Item('rayleigh'), Item('beta'), Item('initial_point'), Item('time_start'), Item('time_stop'), Item('time_step'), resizable=True) ########################################################################### # 'Lorenz' interface. ########################################################################### def compute_step(self, point, time): x, y, z = point return array([ self.prandtl * (y - x), x * (self.rayleigh - z) - y, x * y - self.beta * z ]) ########################################################################### # Protected interface. ########################################################################### @cached_property def _get_points(self): return odeint(self.compute_step, self.initial_point, self.times) @cached_property def _get_times(self): return arange(self.time_start, self.time_stop, self.time_step)
class MyClass(object): implements(IMyMarkerInterface) def __init__(self): self.val = 2 def blah(self): pass
class SampleList(HasTraits): implements(IList) data = List(Int, [10, 20, 30]) def get_list(self): return self.data
class AboutDialog(MAboutDialog, Dialog): """ The toolkit specific implementation of an AboutDialog. See the IAboutDialog interface for the API documentation. """ implements(IAboutDialog) #### 'IAboutDialog' interface ############################################# additions = List(Unicode) image = Instance(ImageResource, ImageResource('about')) ########################################################################### # Protected 'IDialog' interface. ########################################################################### def _create_contents(self, parent): label = QtGui.QLabel() if parent.parent() is not None: title = parent.parent().windowTitle() else: title = "" # Set the title. self.title = "About %s" % title # Load the image to be displayed in the about box. image = self.image.create_image() path = self.image.absolute_path # The additional strings. additions = '<br />'.join(self.additions) # Get the version numbers. py_version = sys.version[0:sys.version.find("(")] qt_version = QtCore.__version__ # Set the page contents. label.setText(_DIALOG_TEXT % (path, additions, py_version, qt_version)) # Create the button. buttons = QtGui.QDialogButtonBox() if self.ok_label: buttons.addButton(self.ok_label, QtGui.QDialogButtonBox.AcceptRole) else: buttons.addButton(QtGui.QDialogButtonBox.Ok) buttons.connect(buttons, QtCore.SIGNAL('accepted()'), parent, QtCore.SLOT('accept()')) lay = QtGui.QVBoxLayout() lay.addWidget(label) lay.addWidget(buttons) parent.setLayout(lay)
class DirectoryDialog(MDirectoryDialog, Dialog): """ The toolkit specific implementation of a DirectoryDialog. See the IDirectoryDialog interface for the API documentation. """ implements(IDirectoryDialog) #### 'IDirectoryDialog' interface ######################################### default_path = Unicode message = Unicode new_directory = Bool(True) path = Unicode ########################################################################### # Protected 'IDialog' interface. ########################################################################### def _create_contents(self, parent): # In wx this is a canned dialog. pass ########################################################################### # 'IWindow' interface. ########################################################################### def close(self): # Get the path of the chosen directory. self.path = unicode(self.control.GetPath()) # Let the window close as normal. super(DirectoryDialog, self).close() ########################################################################### # Protected 'IWidget' interface. ########################################################################### def _create_control(self, parent): # The default style. style = wx.OPEN # Create the wx style depending on which buttons are required etc. if self.new_directory: style = style | wx.DD_NEW_DIR_BUTTON if self.message: message = self.message else: message = "Choose a directory" # Create the actual dialog. return wx.DirDialog(parent, message=message, defaultPath=self.default_path, style=style)
class DirectoryDialog(MDirectoryDialog, Dialog): """ The toolkit specific implementation of a DirectoryDialog. See the IDirectoryDialog interface for the API documentation. """ implements(IDirectoryDialog) #### 'IDirectoryDialog' interface ######################################### default_path = Unicode message = Unicode new_directory = Bool(True) path = Unicode ########################################################################### # Protected 'IDialog' interface. ########################################################################### def _create_contents(self, parent): # In PyQt this is a canned dialog. pass ########################################################################### # 'IWindow' interface. ########################################################################### def close(self): # Get the path of the chosen directory. files = self.control.selectedFiles() if files: self.path = unicode(files[0]) else: self.path = '' # Let the window close as normal. super(DirectoryDialog, self).close() ########################################################################### # Protected 'IWidget' interface. ########################################################################### def _create_control(self, parent): dlg = QtGui.QFileDialog(parent, self.title, self.default_path) dlg.setViewMode(QtGui.QFileDialog.Detail) dlg.setFileMode(QtGui.QFileDialog.DirectoryOnly) if not self.new_directory: dlg.setReadOnly(True) if self.message: dlg.setLabelText(QtGui.QFileDialog.LookIn, self.message) return dlg
class SpringDOTSEval( TStepperEval ): ''' Domain with uniform FE-time-step-eval. ''' implements( ITStepperEval ) sdomain = Instance( IFEUniformDomain ) ##### check the three following operators ### # they might be deleted def new_cntl_var( self ): return zeros( self.sdomain.n_dofs, float_ ) def new_resp_var( self ): return zeros( self.sdomain.n_dofs, float_ ) def new_tangent_operator( self ): ''' Return the tangent operator used for the time stepping ''' return SysMtxArray() # cached zeroed array for element stiffnesses k_arr = Property( Array, depends_on = 'sdomain.+changed_structure' ) @cached_property def _get_k_arr( self ): return zeros( ( self.sdomain.n_elems, 2, 2 ), dtype = 'float_' ) F_int = Property( Array, depends_on = 'sdomain.+changed_structure' ) @cached_property def _get_F_int( self ): return zeros( self.sdomain.n_dofs, float_ ) k_mtx = Property( Array, depends_on = 'sdomain.+changed_structure' ) @cached_property def _get_k_mtx( self ): k = self.sdomain.k_value return array( [[ k, -k ], [ -k, k ]], dtype = 'float_' ) def get_corr_pred( self, sctx, U, dU, tn, tn1, F_int, *args, **kw ): # in order to avoid allocation of the array in every time step # of the computation k_arr = self.k_arr k_arr[...] = self.k_mtx[None, :, :] tstepper = self.sdomain.tstepper U = tstepper.U_k # @todo - avoid the loop - use numpy array operator for i in range( self.sdomain.n_elems ): ix = self.sdomain.elem_dof_map[i] u = U[ ix ] f = dot( self.k_mtx, u ) F_int[ ix ] += f return SysMtxArray( mtx_arr = k_arr, dof_map_arr = self.sdomain.elem_dof_map )