repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
dahlia/sqlalchemy-imageattach
sqlalchemy_imageattach/entity.py
BaseImageSet.find_thumbnail
def find_thumbnail(self, width=None, height=None): """Finds the thumbnail of the image with the given ``width`` and/or ``height``. :param width: the thumbnail width :type width: :class:`numbers.Integral` :param height: the thumbnail height :type height: :class:`numbers.I...
python
def find_thumbnail(self, width=None, height=None): """Finds the thumbnail of the image with the given ``width`` and/or ``height``. :param width: the thumbnail width :type width: :class:`numbers.Integral` :param height: the thumbnail height :type height: :class:`numbers.I...
Finds the thumbnail of the image with the given ``width`` and/or ``height``. :param width: the thumbnail width :type width: :class:`numbers.Integral` :param height: the thumbnail height :type height: :class:`numbers.Integral` :returns: the thumbnail image :rtype:...
https://github.com/dahlia/sqlalchemy-imageattach/blob/b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8/sqlalchemy_imageattach/entity.py#L871-L901
dahlia/sqlalchemy-imageattach
sqlalchemy_imageattach/entity.py
BaseImageSet.open_file
def open_file(self, store=current_store, use_seek=False): """The shorthand of :meth:`~Image.open_file()` for the :attr:`original`. :param store: the storage which contains the image files :data:`~sqlalchemy_imageattach.context.current_store` by defaul...
python
def open_file(self, store=current_store, use_seek=False): """The shorthand of :meth:`~Image.open_file()` for the :attr:`original`. :param store: the storage which contains the image files :data:`~sqlalchemy_imageattach.context.current_store` by defaul...
The shorthand of :meth:`~Image.open_file()` for the :attr:`original`. :param store: the storage which contains the image files :data:`~sqlalchemy_imageattach.context.current_store` by default :type store: :class:`~sqlalchemy_imageattach.store.Store` ...
https://github.com/dahlia/sqlalchemy-imageattach/blob/b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8/sqlalchemy_imageattach/entity.py#L903-L924
dahlia/sqlalchemy-imageattach
sqlalchemy_imageattach/entity.py
MultipleImageSet.image_sets
def image_sets(self): """(:class:`typing.Iterable`\ [:class:`ImageSubset`]) The set of attached image sets. """ images = self._original_images() for image in images: yield ImageSubset(self, **image.identity_map)
python
def image_sets(self): """(:class:`typing.Iterable`\ [:class:`ImageSubset`]) The set of attached image sets. """ images = self._original_images() for image in images: yield ImageSubset(self, **image.identity_map)
(:class:`typing.Iterable`\ [:class:`ImageSubset`]) The set of attached image sets.
https://github.com/dahlia/sqlalchemy-imageattach/blob/b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8/sqlalchemy_imageattach/entity.py#L1034-L1041
dahlia/sqlalchemy-imageattach
sqlalchemy_imageattach/stores/fs.py
HttpExposedFileSystemStore.wsgi_middleware
def wsgi_middleware(self, app, cors=False): """WSGI middlewares that wraps the given ``app`` and serves actual image files. :: fs_store = HttpExposedFileSystemStore('userimages', 'images/') app = fs_store.wsgi_middleware(app) :param app: the wsgi app to wrap :ty...
python
def wsgi_middleware(self, app, cors=False): """WSGI middlewares that wraps the given ``app`` and serves actual image files. :: fs_store = HttpExposedFileSystemStore('userimages', 'images/') app = fs_store.wsgi_middleware(app) :param app: the wsgi app to wrap :ty...
WSGI middlewares that wraps the given ``app`` and serves actual image files. :: fs_store = HttpExposedFileSystemStore('userimages', 'images/') app = fs_store.wsgi_middleware(app) :param app: the wsgi app to wrap :type app: :class:`~typing.Callable`\ [[], :cl...
https://github.com/dahlia/sqlalchemy-imageattach/blob/b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8/sqlalchemy_imageattach/stores/fs.py#L215-L237
benmoran56/esper
esper.py
World.clear_database
def clear_database(self) -> None: """Remove all Entities and Components from the World.""" self._next_entity_id = 0 self._dead_entities.clear() self._components.clear() self._entities.clear() self.clear_cache()
python
def clear_database(self) -> None: """Remove all Entities and Components from the World.""" self._next_entity_id = 0 self._dead_entities.clear() self._components.clear() self._entities.clear() self.clear_cache()
Remove all Entities and Components from the World.
https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L46-L52
benmoran56/esper
esper.py
World.add_processor
def add_processor(self, processor_instance: Processor, priority=0) -> None: """Add a Processor instance to the World. :param processor_instance: An instance of a Processor, subclassed from the Processor class :param priority: A higher number is processed first. """ asser...
python
def add_processor(self, processor_instance: Processor, priority=0) -> None: """Add a Processor instance to the World. :param processor_instance: An instance of a Processor, subclassed from the Processor class :param priority: A higher number is processed first. """ asser...
Add a Processor instance to the World. :param processor_instance: An instance of a Processor, subclassed from the Processor class :param priority: A higher number is processed first.
https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L54-L65
benmoran56/esper
esper.py
World.remove_processor
def remove_processor(self, processor_type: Processor) -> None: """Remove a Processor from the World, by type. :param processor_type: The class type of the Processor to remove. """ for processor in self._processors: if type(processor) == processor_type: proces...
python
def remove_processor(self, processor_type: Processor) -> None: """Remove a Processor from the World, by type. :param processor_type: The class type of the Processor to remove. """ for processor in self._processors: if type(processor) == processor_type: proces...
Remove a Processor from the World, by type. :param processor_type: The class type of the Processor to remove.
https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L67-L75
benmoran56/esper
esper.py
World.get_processor
def get_processor(self, processor_type: Type[P]) -> P: """Get a Processor instance, by type. This method returns a Processor instance by type. This could be useful in certain situations, such as wanting to call a method on a Processor, from within another Processor. :param proc...
python
def get_processor(self, processor_type: Type[P]) -> P: """Get a Processor instance, by type. This method returns a Processor instance by type. This could be useful in certain situations, such as wanting to call a method on a Processor, from within another Processor. :param proc...
Get a Processor instance, by type. This method returns a Processor instance by type. This could be useful in certain situations, such as wanting to call a method on a Processor, from within another Processor. :param processor_type: The type of the Processor you wish to retrieve. ...
https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L77-L89
benmoran56/esper
esper.py
World.create_entity
def create_entity(self, *components) -> int: """Create a new Entity. This method returns an Entity ID, which is just a plain integer. You can optionally pass one or more Component instances to be assigned to the Entity. :param components: Optional components to be assigned to t...
python
def create_entity(self, *components) -> int: """Create a new Entity. This method returns an Entity ID, which is just a plain integer. You can optionally pass one or more Component instances to be assigned to the Entity. :param components: Optional components to be assigned to t...
Create a new Entity. This method returns an Entity ID, which is just a plain integer. You can optionally pass one or more Component instances to be assigned to the Entity. :param components: Optional components to be assigned to the entity on creation. :return: The next...
https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L91-L109
benmoran56/esper
esper.py
World.delete_entity
def delete_entity(self, entity: int, immediate=False) -> None: """Delete an Entity from the World. Delete an Entity and all of it's assigned Component instances from the world. By default, Entity deletion is delayed until the next call to *World.process*. You can request immediate delet...
python
def delete_entity(self, entity: int, immediate=False) -> None: """Delete an Entity from the World. Delete an Entity and all of it's assigned Component instances from the world. By default, Entity deletion is delayed until the next call to *World.process*. You can request immediate delet...
Delete an Entity from the World. Delete an Entity and all of it's assigned Component instances from the world. By default, Entity deletion is delayed until the next call to *World.process*. You can request immediate deletion, however, by passing the "immediate=True" parameter. This shou...
https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L111-L135
benmoran56/esper
esper.py
World.component_for_entity
def component_for_entity(self, entity: int, component_type: Type[C]) -> C: """Retrieve a Component instance for a specific Entity. Retrieve a Component instance for a specific Entity. In some cases, it may be necessary to access a specific Component instance. For example: directly modif...
python
def component_for_entity(self, entity: int, component_type: Type[C]) -> C: """Retrieve a Component instance for a specific Entity. Retrieve a Component instance for a specific Entity. In some cases, it may be necessary to access a specific Component instance. For example: directly modif...
Retrieve a Component instance for a specific Entity. Retrieve a Component instance for a specific Entity. In some cases, it may be necessary to access a specific Component instance. For example: directly modifying a Component to handle user input. Raises a KeyError if the given Entity ...
https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L137-L149
benmoran56/esper
esper.py
World.components_for_entity
def components_for_entity(self, entity: int) -> Tuple[C, ...]: """Retrieve all Components for a specific Entity, as a Tuple. Retrieve all Components for a specific Entity. The method is probably not appropriate to use in your Processors, but might be useful for saving state, or passing ...
python
def components_for_entity(self, entity: int) -> Tuple[C, ...]: """Retrieve all Components for a specific Entity, as a Tuple. Retrieve all Components for a specific Entity. The method is probably not appropriate to use in your Processors, but might be useful for saving state, or passing ...
Retrieve all Components for a specific Entity, as a Tuple. Retrieve all Components for a specific Entity. The method is probably not appropriate to use in your Processors, but might be useful for saving state, or passing specific Components between World instances. Unlike most other met...
https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L151-L165
benmoran56/esper
esper.py
World.has_component
def has_component(self, entity: int, component_type: Any) -> bool: """Check if a specific Entity has a Component of a certain type. :param entity: The Entity you are querying. :param component_type: The type of Component to check for. :return: True if the Entity has a Component of this ...
python
def has_component(self, entity: int, component_type: Any) -> bool: """Check if a specific Entity has a Component of a certain type. :param entity: The Entity you are querying. :param component_type: The type of Component to check for. :return: True if the Entity has a Component of this ...
Check if a specific Entity has a Component of a certain type. :param entity: The Entity you are querying. :param component_type: The type of Component to check for. :return: True if the Entity has a Component of this type, otherwise False
https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L167-L175
benmoran56/esper
esper.py
World.add_component
def add_component(self, entity: int, component_instance: Any) -> None: """Add a new Component instance to an Entity. Add a Component instance to an Entiy. If a Component of the same type is already assigned to the Entity, it will be replaced. :param entity: The Entity to associate the ...
python
def add_component(self, entity: int, component_instance: Any) -> None: """Add a new Component instance to an Entity. Add a Component instance to an Entiy. If a Component of the same type is already assigned to the Entity, it will be replaced. :param entity: The Entity to associate the ...
Add a new Component instance to an Entity. Add a Component instance to an Entiy. If a Component of the same type is already assigned to the Entity, it will be replaced. :param entity: The Entity to associate the Component with. :param component_instance: A Component instance.
https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L177-L197
benmoran56/esper
esper.py
World.remove_component
def remove_component(self, entity: int, component_type: Any) -> int: """Remove a Component instance from an Entity, by type. A Component instance can be removed by providing it's type. For example: world.delete_component(enemy_a, Velocity) will remove the Velocity instance from the Enti...
python
def remove_component(self, entity: int, component_type: Any) -> int: """Remove a Component instance from an Entity, by type. A Component instance can be removed by providing it's type. For example: world.delete_component(enemy_a, Velocity) will remove the Velocity instance from the Enti...
Remove a Component instance from an Entity, by type. A Component instance can be removed by providing it's type. For example: world.delete_component(enemy_a, Velocity) will remove the Velocity instance from the Entity enemy_a. Raises a KeyError if either the given entity or Component t...
https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L199-L222
benmoran56/esper
esper.py
World._get_component
def _get_component(self, component_type: Type[C]) -> Iterable[Tuple[int, C]]: """Get an iterator for Entity, Component pairs. :param component_type: The Component type to retrieve. :return: An iterator for (Entity, Component) tuples. """ entity_db = self._entities for e...
python
def _get_component(self, component_type: Type[C]) -> Iterable[Tuple[int, C]]: """Get an iterator for Entity, Component pairs. :param component_type: The Component type to retrieve. :return: An iterator for (Entity, Component) tuples. """ entity_db = self._entities for e...
Get an iterator for Entity, Component pairs. :param component_type: The Component type to retrieve. :return: An iterator for (Entity, Component) tuples.
https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L224-L233
benmoran56/esper
esper.py
World._get_components
def _get_components(self, *component_types: Type)-> Iterable[Tuple[int, ...]]: """Get an iterator for Entity and multiple Component sets. :param component_types: Two or more Component types. :return: An iterator for Entity, (Component1, Component2, etc) tuples. """ entit...
python
def _get_components(self, *component_types: Type)-> Iterable[Tuple[int, ...]]: """Get an iterator for Entity and multiple Component sets. :param component_types: Two or more Component types. :return: An iterator for Entity, (Component1, Component2, etc) tuples. """ entit...
Get an iterator for Entity and multiple Component sets. :param component_types: Two or more Component types. :return: An iterator for Entity, (Component1, Component2, etc) tuples.
https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L235-L249
benmoran56/esper
esper.py
World.try_component
def try_component(self, entity: int, component_type: Type): """Try to get a single component type for an Entity. This method will return the requested Component if it exists, but will pass silently if it does not. This allows a way to access optional Componen...
python
def try_component(self, entity: int, component_type: Type): """Try to get a single component type for an Entity. This method will return the requested Component if it exists, but will pass silently if it does not. This allows a way to access optional Componen...
Try to get a single component type for an Entity. This method will return the requested Component if it exists, but will pass silently if it does not. This allows a way to access optional Components that may or may not exist. :param entity: The Entity ID to ...
https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L259-L274
benmoran56/esper
esper.py
World._clear_dead_entities
def _clear_dead_entities(self): """Finalize deletion of any Entities that are marked dead. In the interest of performance, this method duplicates code from the `delete_entity` method. If that method is changed, those changes should be duplicated here as well. """ ...
python
def _clear_dead_entities(self): """Finalize deletion of any Entities that are marked dead. In the interest of performance, this method duplicates code from the `delete_entity` method. If that method is changed, those changes should be duplicated here as well. """ ...
Finalize deletion of any Entities that are marked dead. In the interest of performance, this method duplicates code from the `delete_entity` method. If that method is changed, those changes should be duplicated here as well.
https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L276-L294
benmoran56/esper
esper.py
World._timed_process
def _timed_process(self, *args, **kwargs): """Track Processor execution time for benchmarking.""" for processor in self._processors: start_time = _time.process_time() processor.process(*args, **kwargs) process_time = int(round((_time.process_time() - start_time) * 100...
python
def _timed_process(self, *args, **kwargs): """Track Processor execution time for benchmarking.""" for processor in self._processors: start_time = _time.process_time() processor.process(*args, **kwargs) process_time = int(round((_time.process_time() - start_time) * 100...
Track Processor execution time for benchmarking.
https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L300-L306
benmoran56/esper
esper.py
World.process
def process(self, *args, **kwargs): """Call the process method on all Processors, in order of their priority. Call the *process* method on all assigned Processors, respecting their optional priority setting. In addition, any Entities that were marked for deletion since the last call to ...
python
def process(self, *args, **kwargs): """Call the process method on all Processors, in order of their priority. Call the *process* method on all assigned Processors, respecting their optional priority setting. In addition, any Entities that were marked for deletion since the last call to ...
Call the process method on all Processors, in order of their priority. Call the *process* method on all assigned Processors, respecting their optional priority setting. In addition, any Entities that were marked for deletion since the last call to *World.process*, will be deleted at the...
https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L308-L320
benmoran56/esper
examples/pysdl2_example.py
texture_from_image
def texture_from_image(renderer, image_name): """Create an SDL2 Texture from an image file""" soft_surface = ext.load_image(image_name) texture = SDL_CreateTextureFromSurface(renderer.renderer, soft_surface) SDL_FreeSurface(soft_surface) return texture
python
def texture_from_image(renderer, image_name): """Create an SDL2 Texture from an image file""" soft_surface = ext.load_image(image_name) texture = SDL_CreateTextureFromSurface(renderer.renderer, soft_surface) SDL_FreeSurface(soft_surface) return texture
Create an SDL2 Texture from an image file
https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/examples/pysdl2_example.py#L76-L81
sdss/tree
tasks.py
setup_tree
def setup_tree(ctx, verbose=None, root=None, tree_dir=None, modules_dir=None): ''' Sets up the SDSS tree enviroment ''' print('Setting up the tree') ctx.run('python bin/setup_tree.py -t {0} -r {1} -m {2}'.format(tree_dir, root, modules_dir))
python
def setup_tree(ctx, verbose=None, root=None, tree_dir=None, modules_dir=None): ''' Sets up the SDSS tree enviroment ''' print('Setting up the tree') ctx.run('python bin/setup_tree.py -t {0} -r {1} -m {2}'.format(tree_dir, root, modules_dir))
Sets up the SDSS tree enviroment
https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/tasks.py#L61-L64
sdss/tree
python/tree/tree.py
Tree.set_roots
def set_roots(self, uproot_with=None): ''' Set the roots of the tree in the os environment Parameters: uproot_with (str): A new TREE_DIR path used to override an existing TREE_DIR environment variable ''' # Check for TREE_DIR self.treedir = os.envir...
python
def set_roots(self, uproot_with=None): ''' Set the roots of the tree in the os environment Parameters: uproot_with (str): A new TREE_DIR path used to override an existing TREE_DIR environment variable ''' # Check for TREE_DIR self.treedir = os.envir...
Set the roots of the tree in the os environment Parameters: uproot_with (str): A new TREE_DIR path used to override an existing TREE_DIR environment variable
https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/tree.py#L75-L103
sdss/tree
python/tree/tree.py
Tree.load_config
def load_config(self, config=None): ''' loads a config file Parameters: config (str): Optional name of manual config file to load ''' # Read the config file cfgname = (config or self.config_name) cfgname = 'sdsswork' if cfgname is None else c...
python
def load_config(self, config=None): ''' loads a config file Parameters: config (str): Optional name of manual config file to load ''' # Read the config file cfgname = (config or self.config_name) cfgname = 'sdsswork' if cfgname is None else c...
loads a config file Parameters: config (str): Optional name of manual config file to load
https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/tree.py#L105-L135
sdss/tree
python/tree/tree.py
Tree.branch_out
def branch_out(self, limb=None): ''' Set the individual section branches This adds the various sections of the config file into the tree environment for access later. Optically can specify a specific branch. This does not yet load them into the os environment. Parameters: ...
python
def branch_out(self, limb=None): ''' Set the individual section branches This adds the various sections of the config file into the tree environment for access later. Optically can specify a specific branch. This does not yet load them into the os environment. Parameters: ...
Set the individual section branches This adds the various sections of the config file into the tree environment for access later. Optically can specify a specific branch. This does not yet load them into the os environment. Parameters: limb (str/list): The ...
https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/tree.py#L137-L172
sdss/tree
python/tree/tree.py
Tree.add_limbs
def add_limbs(self, key=None): ''' Add a new section from the tree into the existing os environment Parameters: key (str): The section name to grab from the environment ''' self.branch_out(limb=key) self.add_paths_to_os(key=key)
python
def add_limbs(self, key=None): ''' Add a new section from the tree into the existing os environment Parameters: key (str): The section name to grab from the environment ''' self.branch_out(limb=key) self.add_paths_to_os(key=key)
Add a new section from the tree into the existing os environment Parameters: key (str): The section name to grab from the environment
https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/tree.py#L174-L183
sdss/tree
python/tree/tree.py
Tree.get_paths
def get_paths(self, key): ''' Retrieve a set of environment paths from the config Parameters: key (str): The section name to grab from the environment Returns: self.environ[newkey] (OrderedDict): An ordered dict containing all of the path...
python
def get_paths(self, key): ''' Retrieve a set of environment paths from the config Parameters: key (str): The section name to grab from the environment Returns: self.environ[newkey] (OrderedDict): An ordered dict containing all of the path...
Retrieve a set of environment paths from the config Parameters: key (str): The section name to grab from the environment Returns: self.environ[newkey] (OrderedDict): An ordered dict containing all of the paths from the specified s...
https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/tree.py#L185-L202
sdss/tree
python/tree/tree.py
Tree.add_paths_to_os
def add_paths_to_os(self, key=None, update=None): ''' Add the paths in tree environ into the os environ This code goes through the tree environ and checks for existence in the os environ, then adds them Parameters: key (str): The section name to check agains...
python
def add_paths_to_os(self, key=None, update=None): ''' Add the paths in tree environ into the os environ This code goes through the tree environ and checks for existence in the os environ, then adds them Parameters: key (str): The section name to check agains...
Add the paths in tree environ into the os environ This code goes through the tree environ and checks for existence in the os environ, then adds them Parameters: key (str): The section name to check against / add update (bool): If True, ov...
https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/tree.py#L204-L225
sdss/tree
python/tree/tree.py
Tree.check_paths
def check_paths(self, paths, update=None): ''' Check if the path is in the os environ, and if not add it Paramters: paths (OrderedDict): An ordered dict containing all of the paths from the a given section, as key:val = name:path update (bool): ...
python
def check_paths(self, paths, update=None): ''' Check if the path is in the os environ, and if not add it Paramters: paths (OrderedDict): An ordered dict containing all of the paths from the a given section, as key:val = name:path update (bool): ...
Check if the path is in the os environ, and if not add it Paramters: paths (OrderedDict): An ordered dict containing all of the paths from the a given section, as key:val = name:path update (bool): If True, overwrites existing tree environ...
https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/tree.py#L227-L248
sdss/tree
python/tree/tree.py
Tree.replant_tree
def replant_tree(self, config=None, exclude=None): ''' Replant the tree with a different config setup Parameters: config (str): The config name to reload exclude (list): A list of environment variables to exclude from forced update...
python
def replant_tree(self, config=None, exclude=None): ''' Replant the tree with a different config setup Parameters: config (str): The config name to reload exclude (list): A list of environment variables to exclude from forced update...
Replant the tree with a different config setup Parameters: config (str): The config name to reload exclude (list): A list of environment variables to exclude from forced updates
https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/tree.py#L250-L262
sdss/tree
python/tree/misc/logger.py
print_exception_formatted
def print_exception_formatted(type, value, tb): """A custom hook for printing tracebacks with colours.""" tbtext = ''.join(traceback.format_exception(type, value, tb)) lexer = get_lexer_by_name('pytb', stripall=True) formatter = TerminalFormatter() sys.stderr.write(highlight(tbtext, lexer, formatte...
python
def print_exception_formatted(type, value, tb): """A custom hook for printing tracebacks with colours.""" tbtext = ''.join(traceback.format_exception(type, value, tb)) lexer = get_lexer_by_name('pytb', stripall=True) formatter = TerminalFormatter() sys.stderr.write(highlight(tbtext, lexer, formatte...
A custom hook for printing tracebacks with colours.
https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/misc/logger.py#L49-L55
sdss/tree
python/tree/misc/logger.py
colored_formatter
def colored_formatter(record): """Prints log messages with colours.""" colours = {'info': ('blue', 'normal'), 'debug': ('magenta', 'normal'), 'warning': ('yellow', 'normal'), 'print': ('green', 'normal'), 'error': ('red', 'bold')} levelname = rec...
python
def colored_formatter(record): """Prints log messages with colours.""" colours = {'info': ('blue', 'normal'), 'debug': ('magenta', 'normal'), 'warning': ('yellow', 'normal'), 'print': ('green', 'normal'), 'error': ('red', 'bold')} levelname = rec...
Prints log messages with colours.
https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/misc/logger.py#L58-L98
sdss/tree
python/tree/misc/logger.py
MyLogger._catch_exceptions
def _catch_exceptions(self, exctype, value, tb): """Catches all exceptions and logs them.""" # Now we log it. self.error('Uncaught exception', exc_info=(exctype, value, tb)) # First, we print to stdout with some colouring. print_exception_formatted(exctype, value, tb)
python
def _catch_exceptions(self, exctype, value, tb): """Catches all exceptions and logs them.""" # Now we log it. self.error('Uncaught exception', exc_info=(exctype, value, tb)) # First, we print to stdout with some colouring. print_exception_formatted(exctype, value, tb)
Catches all exceptions and logs them.
https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/misc/logger.py#L205-L212
sdss/tree
python/tree/misc/logger.py
MyLogger._set_defaults
def _set_defaults(self, log_level=logging.INFO, redirect_stdout=False): """Reset logger to its initial state.""" # Remove all previous handlers for handler in self.handlers[:]: self.removeHandler(handler) # Set levels self.setLevel(logging.DEBUG) # Set up t...
python
def _set_defaults(self, log_level=logging.INFO, redirect_stdout=False): """Reset logger to its initial state.""" # Remove all previous handlers for handler in self.handlers[:]: self.removeHandler(handler) # Set levels self.setLevel(logging.DEBUG) # Set up t...
Reset logger to its initial state.
https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/misc/logger.py#L214-L239
sdss/tree
python/tree/misc/logger.py
MyLogger.start_file_logger
def start_file_logger(self, name, log_file_level=logging.DEBUG, log_file_path='./'): """Start file logging.""" log_file_path = os.path.expanduser(log_file_path) / '{}.log'.format(name) logdir = log_file_path.parent try: logdir.mkdir(parents=True, exist_ok=True) ...
python
def start_file_logger(self, name, log_file_level=logging.DEBUG, log_file_path='./'): """Start file logging.""" log_file_path = os.path.expanduser(log_file_path) / '{}.log'.format(name) logdir = log_file_path.parent try: logdir.mkdir(parents=True, exist_ok=True) ...
Start file logging.
https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/misc/logger.py#L241-L265
sdss/tree
bin/setup_tree.py
create_index_table
def create_index_table(environ, envdir): ''' create an html table Parameters: environ (dict): A tree environment dictionary envdir (str): The filepath for the env directory Returns: An html table definition string ''' table_header = """<table id=...
python
def create_index_table(environ, envdir): ''' create an html table Parameters: environ (dict): A tree environment dictionary envdir (str): The filepath for the env directory Returns: An html table definition string ''' table_header = """<table id=...
create an html table Parameters: environ (dict): A tree environment dictionary envdir (str): The filepath for the env directory Returns: An html table definition string
https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/bin/setup_tree.py#L44-L110
sdss/tree
bin/setup_tree.py
create_index_page
def create_index_page(environ, defaults, envdir): ''' create the env index html page Builds the index.html page containing a table of symlinks to datamodel directories Parameters: environ (dict): A tree environment dictionary defaults (dict): The defaults di...
python
def create_index_page(environ, defaults, envdir): ''' create the env index html page Builds the index.html page containing a table of symlinks to datamodel directories Parameters: environ (dict): A tree environment dictionary defaults (dict): The defaults di...
create the env index html page Builds the index.html page containing a table of symlinks to datamodel directories Parameters: environ (dict): A tree environment dictionary defaults (dict): The defaults dictionary from environ['default'] envdir (str): ...
https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/bin/setup_tree.py#L113-L153
sdss/tree
bin/setup_tree.py
create_env
def create_env(environ, mirror=None, verbose=None): ''' create the env symlink directory structure Creates the env folder filled with symlinks to datamodel directories for a given tree config file. Parameters: environ (dict): A tree environment dictionary mirror (bool...
python
def create_env(environ, mirror=None, verbose=None): ''' create the env symlink directory structure Creates the env folder filled with symlinks to datamodel directories for a given tree config file. Parameters: environ (dict): A tree environment dictionary mirror (bool...
create the env symlink directory structure Creates the env folder filled with symlinks to datamodel directories for a given tree config file. Parameters: environ (dict): A tree environment dictionary mirror (bool): If True, use the SAM url location ver...
https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/bin/setup_tree.py#L156-L196
sdss/tree
bin/setup_tree.py
check_sas_base_dir
def check_sas_base_dir(root=None): ''' Check for the SAS_BASE_DIR environment variable Will set the SAS_BASE_DIR in your local environment or prompt you to define one if is undefined Parameters: root (str): Optional override of the SAS_BASE_DIR envvar ''' sasbasedir = root...
python
def check_sas_base_dir(root=None): ''' Check for the SAS_BASE_DIR environment variable Will set the SAS_BASE_DIR in your local environment or prompt you to define one if is undefined Parameters: root (str): Optional override of the SAS_BASE_DIR envvar ''' sasbasedir = root...
Check for the SAS_BASE_DIR environment variable Will set the SAS_BASE_DIR in your local environment or prompt you to define one if is undefined Parameters: root (str): Optional override of the SAS_BASE_DIR envvar
https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/bin/setup_tree.py#L199-L213
sdss/tree
bin/setup_tree.py
write_header
def write_header(term='bash', tree_dir=None, name=None): ''' Write proper file header in a given shell format Parameters: term (str): The type of shell header to write, can be "bash", "tsch", or "modules" tree_dir (str): The path to this repository name (str): ...
python
def write_header(term='bash', tree_dir=None, name=None): ''' Write proper file header in a given shell format Parameters: term (str): The type of shell header to write, can be "bash", "tsch", or "modules" tree_dir (str): The path to this repository name (str): ...
Write proper file header in a given shell format Parameters: term (str): The type of shell header to write, can be "bash", "tsch", or "modules" tree_dir (str): The path to this repository name (str): The name of the configuration Returns: A s...
https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/bin/setup_tree.py#L216-L263
sdss/tree
bin/setup_tree.py
write_file
def write_file(environ, term='bash', out_dir=None, tree_dir=None): ''' Write a tree environment file Loops over the tree environ and writes them out to a bash, tsch, or modules file Parameters: environ (dict): The tree dictionary environment term (str): The type...
python
def write_file(environ, term='bash', out_dir=None, tree_dir=None): ''' Write a tree environment file Loops over the tree environ and writes them out to a bash, tsch, or modules file Parameters: environ (dict): The tree dictionary environment term (str): The type...
Write a tree environment file Loops over the tree environ and writes them out to a bash, tsch, or modules file Parameters: environ (dict): The tree dictionary environment term (str): The type of shell header to write, can be "bash", "tsch", or "modules" tree...
https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/bin/setup_tree.py#L272-L319
sdss/tree
bin/setup_tree.py
get_tree
def get_tree(config=None): ''' Get the tree for a given config Parameters: config (str): The name of the tree config to load Returns: a Python Tree instance ''' path = os.path.dirname(os.path.abspath(__file__)) pypath = os.path.realpath(os.path.join(path, '..', 'pyt...
python
def get_tree(config=None): ''' Get the tree for a given config Parameters: config (str): The name of the tree config to load Returns: a Python Tree instance ''' path = os.path.dirname(os.path.abspath(__file__)) pypath = os.path.realpath(os.path.join(path, '..', 'pyt...
Get the tree for a given config Parameters: config (str): The name of the tree config to load Returns: a Python Tree instance
https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/bin/setup_tree.py#L322-L339
sdss/tree
bin/setup_tree.py
copy_modules
def copy_modules(filespath=None, modules_path=None, verbose=None): ''' Copy over the tree module files into your path ''' # find or define a modules path if not modules_path: modulepath = os.getenv("MODULEPATH") if not modulepath: modules_path = input('Enter the root path for yo...
python
def copy_modules(filespath=None, modules_path=None, verbose=None): ''' Copy over the tree module files into your path ''' # find or define a modules path if not modules_path: modulepath = os.getenv("MODULEPATH") if not modulepath: modules_path = input('Enter the root path for yo...
Copy over the tree module files into your path
https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/bin/setup_tree.py#L342-L380
sdss/tree
bin/setup_tree.py
parse_args
def parse_args(): ''' Parse the arguments ''' parser = argparse.ArgumentParser(prog='setup_tree_modules', usage='%(prog)s [opts]') parser.add_argument('-v', '--verbose', action='store_true', dest='verbose', help='Print extra information.', default=False) parser.add_argument('-r'...
python
def parse_args(): ''' Parse the arguments ''' parser = argparse.ArgumentParser(prog='setup_tree_modules', usage='%(prog)s [opts]') parser.add_argument('-v', '--verbose', action='store_true', dest='verbose', help='Print extra information.', default=False) parser.add_argument('-r'...
Parse the arguments
https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/bin/setup_tree.py#L383-L404
sdss/tree
python/tree/misc/docutree.py
_indent
def _indent(text, level=1): ''' Does a proper indenting for Sphinx rst ''' prefix = ' ' * (4 * level) def prefixed_lines(): for line in text.splitlines(True): yield (prefix + line if line.strip() else line) return ''.join(prefixed_lines())
python
def _indent(text, level=1): ''' Does a proper indenting for Sphinx rst ''' prefix = ' ' * (4 * level) def prefixed_lines(): for line in text.splitlines(True): yield (prefix + line if line.strip() else line) return ''.join(prefixed_lines())
Does a proper indenting for Sphinx rst
https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/misc/docutree.py#L22-L31
sdss/tree
python/tree/misc/docutree.py
_format_command
def _format_command(name, envvars, base=None): ''' Creates a list-table directive for a set of defined environment variables Parameters: name (str): The name of the config section envvars (dict): A dictionary of the environment variable definitions from the config ...
python
def _format_command(name, envvars, base=None): ''' Creates a list-table directive for a set of defined environment variables Parameters: name (str): The name of the config section envvars (dict): A dictionary of the environment variable definitions from the config ...
Creates a list-table directive for a set of defined environment variables Parameters: name (str): The name of the config section envvars (dict): A dictionary of the environment variable definitions from the config base (str): The SAS_BASE to remove f...
https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/misc/docutree.py#L34-L63
sdss/tree
python/tree/misc/docutree.py
TreeDirective._generate_section
def _generate_section(self, name, config, cfg_section='default', remove_sasbase=False): """Generate the relevant Sphinx nodes. Generates a section for the Tree datamodel. Formats a tree section as a list-table directive. Parameters: name (str): The name of ...
python
def _generate_section(self, name, config, cfg_section='default', remove_sasbase=False): """Generate the relevant Sphinx nodes. Generates a section for the Tree datamodel. Formats a tree section as a list-table directive. Parameters: name (str): The name of ...
Generate the relevant Sphinx nodes. Generates a section for the Tree datamodel. Formats a tree section as a list-table directive. Parameters: name (str): The name of the config to be documented, e.g. 'sdsswork' config (dict): The tree di...
https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/misc/docutree.py#L105-L145
sdss/tree
setup.py
get_requirements
def get_requirements(opts): ''' Get the proper requirements file based on the optional argument ''' if opts.dev: name = 'requirements_dev.txt' elif opts.doc: name = 'requirements_doc.txt' else: name = 'requirements.txt' requirements_file = os.path.join(os.path.dirname(__fil...
python
def get_requirements(opts): ''' Get the proper requirements file based on the optional argument ''' if opts.dev: name = 'requirements_dev.txt' elif opts.doc: name = 'requirements_doc.txt' else: name = 'requirements.txt' requirements_file = os.path.join(os.path.dirname(__fil...
Get the proper requirements file based on the optional argument
https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/setup.py#L54-L67
sdss/tree
setup.py
remove_args
def remove_args(parser): ''' Remove custom arguments from the parser ''' arguments = [] for action in list(parser._get_optional_actions()): if '--help' not in action.option_strings: arguments += action.option_strings for arg in arguments: if arg in sys.argv: sys...
python
def remove_args(parser): ''' Remove custom arguments from the parser ''' arguments = [] for action in list(parser._get_optional_actions()): if '--help' not in action.option_strings: arguments += action.option_strings for arg in arguments: if arg in sys.argv: sys...
Remove custom arguments from the parser
https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/setup.py#L70-L80
sarugaku/shellingham
tasks/__init__.py
clean
def clean(ctx): """Clean previously built package artifacts. """ ctx.run(f'python setup.py clean') dist = ROOT.joinpath('dist') print(f'[clean] Removing {dist}') if dist.exists(): shutil.rmtree(str(dist))
python
def clean(ctx): """Clean previously built package artifacts. """ ctx.run(f'python setup.py clean') dist = ROOT.joinpath('dist') print(f'[clean] Removing {dist}') if dist.exists(): shutil.rmtree(str(dist))
Clean previously built package artifacts.
https://github.com/sarugaku/shellingham/blob/295fc3094ef05437597ea0baa02f5cd7a3335d28/tasks/__init__.py#L20-L27
sarugaku/shellingham
tasks/__init__.py
_render_log
def _render_log(): """Totally tap into Towncrier internals to get an in-memory result. """ config = load_config(ROOT) definitions = config['types'] fragments, fragment_filenames = find_fragments( pathlib.Path(config['directory']).absolute(), config['sections'], None, ...
python
def _render_log(): """Totally tap into Towncrier internals to get an in-memory result. """ config = load_config(ROOT) definitions = config['types'] fragments, fragment_filenames = find_fragments( pathlib.Path(config['directory']).absolute(), config['sections'], None, ...
Totally tap into Towncrier internals to get an in-memory result.
https://github.com/sarugaku/shellingham/blob/295fc3094ef05437597ea0baa02f5cd7a3335d28/tasks/__init__.py#L49-L67
sods/paramz
paramz/core/nameable.py
adjust_name_for_printing
def adjust_name_for_printing(name): """ Make sure a name can be printed, alongside used as a variable name. """ if name is not None: name2 = name name = name.replace(" ", "_").replace(".", "_").replace("-", "_m_") name = name.replace("+", "_p_").replace("!", "_I_") name =...
python
def adjust_name_for_printing(name): """ Make sure a name can be printed, alongside used as a variable name. """ if name is not None: name2 = name name = name.replace(" ", "_").replace(".", "_").replace("-", "_m_") name = name.replace("+", "_p_").replace("!", "_I_") name =...
Make sure a name can be printed, alongside used as a variable name.
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/core/nameable.py#L33-L47
sods/paramz
paramz/core/nameable.py
Nameable.name
def name(self, name): """ Set the name of this object. Tell the parent if the name has changed. """ from_name = self.name assert isinstance(name, str) self._name = name if self.has_parent(): self._parent_._name_changed(self, from_name)
python
def name(self, name): """ Set the name of this object. Tell the parent if the name has changed. """ from_name = self.name assert isinstance(name, str) self._name = name if self.has_parent(): self._parent_._name_changed(self, from_name)
Set the name of this object. Tell the parent if the name has changed.
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/core/nameable.py#L65-L74
sods/paramz
paramz/core/nameable.py
Nameable.hierarchy_name
def hierarchy_name(self, adjust_for_printing=True): """ return the name for this object with the parents names attached by dots. :param bool adjust_for_printing: whether to call :func:`~adjust_for_printing()` on the names, recursively ...
python
def hierarchy_name(self, adjust_for_printing=True): """ return the name for this object with the parents names attached by dots. :param bool adjust_for_printing: whether to call :func:`~adjust_for_printing()` on the names, recursively ...
return the name for this object with the parents names attached by dots. :param bool adjust_for_printing: whether to call :func:`~adjust_for_printing()` on the names, recursively
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/core/nameable.py#L76-L88
sods/paramz
paramz/parameterized.py
Parameterized.link_parameter
def link_parameter(self, param, index=None): """ :param parameters: the parameters to add :type parameters: list of or one :py:class:`paramz.param.Param` :param [index]: index of where to put parameters Add all parameters to this param class, you can insert parameters ...
python
def link_parameter(self, param, index=None): """ :param parameters: the parameters to add :type parameters: list of or one :py:class:`paramz.param.Param` :param [index]: index of where to put parameters Add all parameters to this param class, you can insert parameters ...
:param parameters: the parameters to add :type parameters: list of or one :py:class:`paramz.param.Param` :param [index]: index of where to put parameters Add all parameters to this param class, you can insert parameters at any given index using the :func:`list.insert` syntax
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/parameterized.py#L128-L186
sods/paramz
paramz/parameterized.py
Parameterized.unlink_parameter
def unlink_parameter(self, param): """ :param param: param object to remove from being a parameter of this parameterized object. """ if not param in self.parameters: try: raise HierarchyError("{} does not belong to this object {}, remove parameters directly fr...
python
def unlink_parameter(self, param): """ :param param: param object to remove from being a parameter of this parameterized object. """ if not param in self.parameters: try: raise HierarchyError("{} does not belong to this object {}, remove parameters directly fr...
:param param: param object to remove from being a parameter of this parameterized object.
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/parameterized.py#L195-L226
sods/paramz
paramz/parameterized.py
Parameterized.grep_param_names
def grep_param_names(self, regexp): """ create a list of parameters, matching regular expression regexp """ if not isinstance(regexp, _pattern_type): regexp = compile(regexp) found_params = [] def visit(innerself, regexp): if (innerself is not self) and regexp...
python
def grep_param_names(self, regexp): """ create a list of parameters, matching regular expression regexp """ if not isinstance(regexp, _pattern_type): regexp = compile(regexp) found_params = [] def visit(innerself, regexp): if (innerself is not self) and regexp...
create a list of parameters, matching regular expression regexp
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/parameterized.py#L282-L292
sods/paramz
paramz/parameterized.py
Parameterized._repr_html_
def _repr_html_(self, header=True): """Representation of the parameters in html for notebook display.""" name = adjust_name_for_printing(self.name) + "." names = self.parameter_names() desc = self._description_str iops = OrderedDict() for opname in self._index_operations:...
python
def _repr_html_(self, header=True): """Representation of the parameters in html for notebook display.""" name = adjust_name_for_printing(self.name) + "." names = self.parameter_names() desc = self._description_str iops = OrderedDict() for opname in self._index_operations:...
Representation of the parameters in html for notebook display.
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/parameterized.py#L382-L412
sods/paramz
paramz/parameterized.py
Parameterized.build_pydot
def build_pydot(self, G=None): # pragma: no cover """ Build a pydot representation of this model. This needs pydot installed. Example Usage:: np.random.seed(1000) X = np.random.normal(0,1,(20,2)) beta = np.random.uniform(0,1,(2,1)) Y = X.dot(beta...
python
def build_pydot(self, G=None): # pragma: no cover """ Build a pydot representation of this model. This needs pydot installed. Example Usage:: np.random.seed(1000) X = np.random.normal(0,1,(20,2)) beta = np.random.uniform(0,1,(2,1)) Y = X.dot(beta...
Build a pydot representation of this model. This needs pydot installed. Example Usage:: np.random.seed(1000) X = np.random.normal(0,1,(20,2)) beta = np.random.uniform(0,1,(2,1)) Y = X.dot(beta) m = RidgeRegression(X, Y) G = m.build_pydot(...
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/parameterized.py#L450-L501
sods/paramz
paramz/param.py
Param.gradient
def gradient(self): """ Return a view on the gradient, which is in the same shape as this parameter is. Note: this is not the real gradient array, it is just a view on it. To work on the real gradient array use: self.full_gradient """ if getattr(self, '_gradient_array_',...
python
def gradient(self): """ Return a view on the gradient, which is in the same shape as this parameter is. Note: this is not the real gradient array, it is just a view on it. To work on the real gradient array use: self.full_gradient """ if getattr(self, '_gradient_array_',...
Return a view on the gradient, which is in the same shape as this parameter is. Note: this is not the real gradient array, it is just a view on it. To work on the real gradient array use: self.full_gradient
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/param.py#L139-L148
sods/paramz
paramz/param.py
Param._setup_observers
def _setup_observers(self): """ Setup the default observers 1: pass through to parent, if present """ if self.has_parent(): self.add_observer(self._parent_, self._parent_._pass_through_notify_observers, -np.inf)
python
def _setup_observers(self): """ Setup the default observers 1: pass through to parent, if present """ if self.has_parent(): self.add_observer(self._parent_, self._parent_._pass_through_notify_observers, -np.inf)
Setup the default observers 1: pass through to parent, if present
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/param.py#L211-L218
sods/paramz
paramz/param.py
Param._repr_html_
def _repr_html_(self, indices=None, iops=None, lx=None, li=None, lls=None): """Representation of the parameter in html for notebook display.""" filter_ = self._current_slice_ vals = self.flat if indices is None: indices = self._indices(filter_) if iops is None: ravi =...
python
def _repr_html_(self, indices=None, iops=None, lx=None, li=None, lls=None): """Representation of the parameter in html for notebook display.""" filter_ = self._current_slice_ vals = self.flat if indices is None: indices = self._indices(filter_) if iops is None: ravi =...
Representation of the parameter in html for notebook display.
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/param.py#L275-L311
sods/paramz
paramz/param.py
Param.build_pydot
def build_pydot(self,G): # pragma: no cover """ Build a pydot representation of this model. This needs pydot installed. Example Usage: np.random.seed(1000) X = np.random.normal(0,1,(20,2)) beta = np.random.uniform(0,1,(2,1)) Y = X.dot(beta) m = RidgeRegr...
python
def build_pydot(self,G): # pragma: no cover """ Build a pydot representation of this model. This needs pydot installed. Example Usage: np.random.seed(1000) X = np.random.normal(0,1,(20,2)) beta = np.random.uniform(0,1,(2,1)) Y = X.dot(beta) m = RidgeRegr...
Build a pydot representation of this model. This needs pydot installed. Example Usage: np.random.seed(1000) X = np.random.normal(0,1,(20,2)) beta = np.random.uniform(0,1,(2,1)) Y = X.dot(beta) m = RidgeRegression(X, Y) G = m.build_pydot() G.write_png('ex...
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/param.py#L349-L389
sods/paramz
paramz/core/observable.py
Observable.add_observer
def add_observer(self, observer, callble, priority=0): """ Add an observer `observer` with the callback `callble` and priority `priority` to this observers list. """ self.observers.add(priority, observer, callble)
python
def add_observer(self, observer, callble, priority=0): """ Add an observer `observer` with the callback `callble` and priority `priority` to this observers list. """ self.observers.add(priority, observer, callble)
Add an observer `observer` with the callback `callble` and priority `priority` to this observers list.
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/core/observable.py#L49-L54
sods/paramz
paramz/core/observable.py
Observable.remove_observer
def remove_observer(self, observer, callble=None): """ Either (if callble is None) remove all callables, which were added alongside observer, or remove callable `callble` which was added alongside the observer `observer`. """ to_remove = [] for poc in self...
python
def remove_observer(self, observer, callble=None): """ Either (if callble is None) remove all callables, which were added alongside observer, or remove callable `callble` which was added alongside the observer `observer`. """ to_remove = [] for poc in self...
Either (if callble is None) remove all callables, which were added alongside observer, or remove callable `callble` which was added alongside the observer `observer`.
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/core/observable.py#L56-L73
sods/paramz
paramz/core/observable.py
Observable.notify_observers
def notify_observers(self, which=None, min_priority=None): """ Notifies all observers. Which is the element, which kicked off this notification loop. The first argument will be self, the second `which`. .. note:: notifies only observers with priority p > min_prior...
python
def notify_observers(self, which=None, min_priority=None): """ Notifies all observers. Which is the element, which kicked off this notification loop. The first argument will be self, the second `which`. .. note:: notifies only observers with priority p > min_prior...
Notifies all observers. Which is the element, which kicked off this notification loop. The first argument will be self, the second `which`. .. note:: notifies only observers with priority p > min_priority! :param min_priority: only notify observers with priori...
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/core/observable.py#L75-L96
sods/paramz
paramz/core/constrainable.py
Constrainable.constrain_fixed
def constrain_fixed(self, value=None, warning=True, trigger_parent=True): """ Constrain this parameter to be fixed to the current value it carries. This does not override the previous constraints, so unfixing will restore the constraint set before fixing. :param warning: print ...
python
def constrain_fixed(self, value=None, warning=True, trigger_parent=True): """ Constrain this parameter to be fixed to the current value it carries. This does not override the previous constraints, so unfixing will restore the constraint set before fixing. :param warning: print ...
Constrain this parameter to be fixed to the current value it carries. This does not override the previous constraints, so unfixing will restore the constraint set before fixing. :param warning: print a warning for overwriting constraints.
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/core/constrainable.py#L52-L68
sods/paramz
paramz/core/constrainable.py
Constrainable.unconstrain_fixed
def unconstrain_fixed(self): """ This parameter will no longer be fixed. If there was a constraint on this parameter when fixing it, it will be constraint with that previous constraint. """ unconstrained = self.unconstrain(__fixed__) self._highest_parent_._set_un...
python
def unconstrain_fixed(self): """ This parameter will no longer be fixed. If there was a constraint on this parameter when fixing it, it will be constraint with that previous constraint. """ unconstrained = self.unconstrain(__fixed__) self._highest_parent_._set_un...
This parameter will no longer be fixed. If there was a constraint on this parameter when fixing it, it will be constraint with that previous constraint.
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/core/constrainable.py#L71-L82
sods/paramz
paramz/core/constrainable.py
Constrainable.constrain
def constrain(self, transform, warning=True, trigger_parent=True): """ :param transform: the :py:class:`paramz.transformations.Transformation` to constrain the this parameter to. :param warning: print a warning if re-constraining parameters. Constrain the param...
python
def constrain(self, transform, warning=True, trigger_parent=True): """ :param transform: the :py:class:`paramz.transformations.Transformation` to constrain the this parameter to. :param warning: print a warning if re-constraining parameters. Constrain the param...
:param transform: the :py:class:`paramz.transformations.Transformation` to constrain the this parameter to. :param warning: print a warning if re-constraining parameters. Constrain the parameter to the given :py:class:`paramz.transformations.Transformation`.
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/core/constrainable.py#L138-L156
sods/paramz
paramz/core/constrainable.py
Constrainable.constrain_positive
def constrain_positive(self, warning=True, trigger_parent=True): """ :param warning: print a warning if re-constraining parameters. Constrain this parameter to the default positive constraint. """ self.constrain(Logexp(), warning=warning, trigger_parent=trigger_parent)
python
def constrain_positive(self, warning=True, trigger_parent=True): """ :param warning: print a warning if re-constraining parameters. Constrain this parameter to the default positive constraint. """ self.constrain(Logexp(), warning=warning, trigger_parent=trigger_parent)
:param warning: print a warning if re-constraining parameters. Constrain this parameter to the default positive constraint.
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/core/constrainable.py#L167-L173
sods/paramz
paramz/core/constrainable.py
Constrainable.constrain_negative
def constrain_negative(self, warning=True, trigger_parent=True): """ :param warning: print a warning if re-constraining parameters. Constrain this parameter to the default negative constraint. """ self.constrain(NegativeLogexp(), warning=warning, trigger_parent=trigger_parent)
python
def constrain_negative(self, warning=True, trigger_parent=True): """ :param warning: print a warning if re-constraining parameters. Constrain this parameter to the default negative constraint. """ self.constrain(NegativeLogexp(), warning=warning, trigger_parent=trigger_parent)
:param warning: print a warning if re-constraining parameters. Constrain this parameter to the default negative constraint.
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/core/constrainable.py#L175-L181
sods/paramz
paramz/core/constrainable.py
Constrainable.constrain_bounded
def constrain_bounded(self, lower, upper, warning=True, trigger_parent=True): """ :param lower, upper: the limits to bound this parameter to :param warning: print a warning if re-constraining parameters. Constrain this parameter to lie within the given range. """ self.co...
python
def constrain_bounded(self, lower, upper, warning=True, trigger_parent=True): """ :param lower, upper: the limits to bound this parameter to :param warning: print a warning if re-constraining parameters. Constrain this parameter to lie within the given range. """ self.co...
:param lower, upper: the limits to bound this parameter to :param warning: print a warning if re-constraining parameters. Constrain this parameter to lie within the given range.
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/core/constrainable.py#L183-L190
sods/paramz
paramz/__init__.py
load
def load(file_or_path): """ Load a previously pickled model, using `m.pickle('path/to/file.pickle)'` :param file_name: path/to/file.pickle """ from pickle import UnpicklingError _python3 = True try: import cPickle as pickle _python3 = False except ImportError: #python3 ...
python
def load(file_or_path): """ Load a previously pickled model, using `m.pickle('path/to/file.pickle)'` :param file_name: path/to/file.pickle """ from pickle import UnpicklingError _python3 = True try: import cPickle as pickle _python3 = False except ImportError: #python3 ...
Load a previously pickled model, using `m.pickle('path/to/file.pickle)'` :param file_name: path/to/file.pickle
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/__init__.py#L52-L78
sods/paramz
paramz/core/gradcheckable.py
Gradcheckable.checkgrad
def checkgrad(self, verbose=0, step=1e-6, tolerance=1e-3, df_tolerance=1e-12): """ Check the gradient of this parameter with respect to the highest parent's objective function. This is a three point estimate of the gradient, wiggling at the parameters with a stepsize step. ...
python
def checkgrad(self, verbose=0, step=1e-6, tolerance=1e-3, df_tolerance=1e-12): """ Check the gradient of this parameter with respect to the highest parent's objective function. This is a three point estimate of the gradient, wiggling at the parameters with a stepsize step. ...
Check the gradient of this parameter with respect to the highest parent's objective function. This is a three point estimate of the gradient, wiggling at the parameters with a stepsize step. The check passes if either the ratio or the difference between numerical and analytical g...
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/core/gradcheckable.py#L44-L69
sods/paramz
paramz/optimization/optimization.py
opt_tnc.opt
def opt(self, x_init, f_fp=None, f=None, fp=None): """ Run the TNC optimizer """ tnc_rcstrings = ['Local minimum', 'Converged', 'XConverged', 'Maximum number of f evaluations reached', 'Line search failed', 'Function is constant'] assert f_fp != None, "TNC requires...
python
def opt(self, x_init, f_fp=None, f=None, fp=None): """ Run the TNC optimizer """ tnc_rcstrings = ['Local minimum', 'Converged', 'XConverged', 'Maximum number of f evaluations reached', 'Line search failed', 'Function is constant'] assert f_fp != None, "TNC requires...
Run the TNC optimizer
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/optimization/optimization.py#L75-L98
sods/paramz
paramz/optimization/optimization.py
opt_lbfgsb.opt
def opt(self, x_init, f_fp=None, f=None, fp=None): """ Run the optimizer """ rcstrings = ['Converged', 'Maximum number of f evaluations reached', 'Error'] assert f_fp != None, "BFGS requires f_fp" opt_dict = {} if self.xtol is not None: print("WARNI...
python
def opt(self, x_init, f_fp=None, f=None, fp=None): """ Run the optimizer """ rcstrings = ['Converged', 'Maximum number of f evaluations reached', 'Error'] assert f_fp != None, "BFGS requires f_fp" opt_dict = {} if self.xtol is not None: print("WARNI...
Run the optimizer
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/optimization/optimization.py#L105-L132
sods/paramz
paramz/optimization/optimization.py
opt_bfgs.opt
def opt(self, x_init, f_fp=None, f=None, fp=None): """ Run the optimizer """ rcstrings = ['','Maximum number of iterations exceeded', 'Gradient and/or function calls not changing'] opt_dict = {} if self.xtol is not None: print("WARNING: bfgs doesn't have an ...
python
def opt(self, x_init, f_fp=None, f=None, fp=None): """ Run the optimizer """ rcstrings = ['','Maximum number of iterations exceeded', 'Gradient and/or function calls not changing'] opt_dict = {} if self.xtol is not None: print("WARNING: bfgs doesn't have an ...
Run the optimizer
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/optimization/optimization.py#L139-L159
sods/paramz
paramz/optimization/optimization.py
opt_simplex.opt
def opt(self, x_init, f_fp=None, f=None, fp=None): """ The simplex optimizer does not require gradients. """ statuses = ['Converged', 'Maximum number of function evaluations made', 'Maximum number of iterations reached'] opt_dict = {} if self.xtol is not None: ...
python
def opt(self, x_init, f_fp=None, f=None, fp=None): """ The simplex optimizer does not require gradients. """ statuses = ['Converged', 'Maximum number of function evaluations made', 'Maximum number of iterations reached'] opt_dict = {} if self.xtol is not None: ...
The simplex optimizer does not require gradients.
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/optimization/optimization.py#L166-L188
sods/paramz
paramz/caching.py
Cacher.combine_inputs
def combine_inputs(self, args, kw, ignore_args): "Combines the args and kw in a unique way, such that ordering of kwargs does not lead to recompute" inputs= args + tuple(c[1] for c in sorted(kw.items(), key=lambda x: x[0])) # REMOVE the ignored arguments from input and PREVENT it from being chec...
python
def combine_inputs(self, args, kw, ignore_args): "Combines the args and kw in a unique way, such that ordering of kwargs does not lead to recompute" inputs= args + tuple(c[1] for c in sorted(kw.items(), key=lambda x: x[0])) # REMOVE the ignored arguments from input and PREVENT it from being chec...
Combines the args and kw in a unique way, such that ordering of kwargs does not lead to recompute
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/caching.py#L90-L94
sods/paramz
paramz/caching.py
Cacher.prepare_cache_id
def prepare_cache_id(self, combined_args_kw): "get the cacheid (conc. string of argument self.ids in order)" cache_id = "".join(self.id(a) for a in combined_args_kw) return cache_id
python
def prepare_cache_id(self, combined_args_kw): "get the cacheid (conc. string of argument self.ids in order)" cache_id = "".join(self.id(a) for a in combined_args_kw) return cache_id
get the cacheid (conc. string of argument self.ids in order)
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/caching.py#L96-L99
sods/paramz
paramz/caching.py
Cacher.ensure_cache_length
def ensure_cache_length(self): "Ensures the cache is within its limits and has one place free" if len(self.order) == self.limit: # we have reached the limit, so lets release one element cache_id = self.order.popleft() combined_args_kw = self.cached_inputs[cache_id] ...
python
def ensure_cache_length(self): "Ensures the cache is within its limits and has one place free" if len(self.order) == self.limit: # we have reached the limit, so lets release one element cache_id = self.order.popleft() combined_args_kw = self.cached_inputs[cache_id] ...
Ensures the cache is within its limits and has one place free
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/caching.py#L101-L132
sods/paramz
paramz/caching.py
Cacher.add_to_cache
def add_to_cache(self, cache_id, inputs, output): """This adds cache_id to the cache, with inputs and output""" self.inputs_changed[cache_id] = False self.cached_outputs[cache_id] = output self.order.append(cache_id) self.cached_inputs[cache_id] = inputs for a in inputs: ...
python
def add_to_cache(self, cache_id, inputs, output): """This adds cache_id to the cache, with inputs and output""" self.inputs_changed[cache_id] = False self.cached_outputs[cache_id] = output self.order.append(cache_id) self.cached_inputs[cache_id] = inputs for a in inputs: ...
This adds cache_id to the cache, with inputs and output
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/caching.py#L134-L147
sods/paramz
paramz/caching.py
Cacher.on_cache_changed
def on_cache_changed(self, direct, which=None): """ A callback funtion, which sets local flags when the elements of some cached inputs change this function gets 'hooked up' to the inputs when we cache them, and upon their elements being changed we update here. """ for what in [d...
python
def on_cache_changed(self, direct, which=None): """ A callback funtion, which sets local flags when the elements of some cached inputs change this function gets 'hooked up' to the inputs when we cache them, and upon their elements being changed we update here. """ for what in [d...
A callback funtion, which sets local flags when the elements of some cached inputs change this function gets 'hooked up' to the inputs when we cache them, and upon their elements being changed we update here.
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/caching.py#L194-L204
sods/paramz
paramz/caching.py
Cacher.reset
def reset(self): """ Totally reset the cache """ [a().remove_observer(self, self.on_cache_changed) if (a() is not None) else None for [a, _] in self.cached_input_ids.values()] self.order = collections.deque() self.cached_inputs = {} # point from cache_ids to a list of [...
python
def reset(self): """ Totally reset the cache """ [a().remove_observer(self, self.on_cache_changed) if (a() is not None) else None for [a, _] in self.cached_input_ids.values()] self.order = collections.deque() self.cached_inputs = {} # point from cache_ids to a list of [...
Totally reset the cache
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/caching.py#L206-L223
sods/paramz
paramz/caching.py
FunctionCache.disable_caching
def disable_caching(self): "Disable the cache of this object. This also removes previously cached results" self.caching_enabled = False for c in self.values(): c.disable_cacher()
python
def disable_caching(self): "Disable the cache of this object. This also removes previously cached results" self.caching_enabled = False for c in self.values(): c.disable_cacher()
Disable the cache of this object. This also removes previously cached results
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/caching.py#L246-L250
sods/paramz
paramz/caching.py
FunctionCache.enable_caching
def enable_caching(self): "Enable the cache of this object." self.caching_enabled = True for c in self.values(): c.enable_cacher()
python
def enable_caching(self): "Enable the cache of this object." self.caching_enabled = True for c in self.values(): c.enable_cacher()
Enable the cache of this object.
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/caching.py#L252-L256
sods/paramz
paramz/optimization/scg.py
SCG
def SCG(f, gradf, x, optargs=(), maxiters=500, max_f_eval=np.inf, xtol=None, ftol=None, gtol=None): """ Optimisation through Scaled Conjugate Gradients (SCG) f: the objective function gradf : the gradient function (should return a 1D np.ndarray) x : the initial condition Returns x the opti...
python
def SCG(f, gradf, x, optargs=(), maxiters=500, max_f_eval=np.inf, xtol=None, ftol=None, gtol=None): """ Optimisation through Scaled Conjugate Gradients (SCG) f: the objective function gradf : the gradient function (should return a 1D np.ndarray) x : the initial condition Returns x the opti...
Optimisation through Scaled Conjugate Gradients (SCG) f: the objective function gradf : the gradient function (should return a 1D np.ndarray) x : the initial condition Returns x the optimal value for x flog : a list of all the objective values function_eval number of fn evaluations sta...
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/optimization/scg.py#L44-L174
sods/paramz
paramz/core/lists_and_dicts.py
ObserverList.remove
def remove(self, priority, observer, callble): """ Remove one observer, which had priority and callble. """ self.flush() for i in range(len(self) - 1, -1, -1): p,o,c = self[i] if priority==p and observer==o and callble==c: del self._poc[i]
python
def remove(self, priority, observer, callble): """ Remove one observer, which had priority and callble. """ self.flush() for i in range(len(self) - 1, -1, -1): p,o,c = self[i] if priority==p and observer==o and callble==c: del self._poc[i]
Remove one observer, which had priority and callble.
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/core/lists_and_dicts.py#L78-L86
sods/paramz
paramz/core/lists_and_dicts.py
ObserverList.add
def add(self, priority, observer, callble): """ Add an observer with priority and callble """ #if observer is not None: ins = 0 for pr, _, _ in self: if priority > pr: break ins += 1 self._poc.insert(ins, (priority, weakref....
python
def add(self, priority, observer, callble): """ Add an observer with priority and callble """ #if observer is not None: ins = 0 for pr, _, _ in self: if priority > pr: break ins += 1 self._poc.insert(ins, (priority, weakref....
Add an observer with priority and callble
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/core/lists_and_dicts.py#L91-L101
sods/paramz
paramz/core/index_operations.py
ParameterIndexOperations.properties_for
def properties_for(self, index): """ Returns a list of properties, such that each entry in the list corresponds to the element of the index given. Example: let properties: 'one':[1,2,3,4], 'two':[3,5,6] >>> properties_for([2,3,5]) [['one'], ['one', 'two'], ['two...
python
def properties_for(self, index): """ Returns a list of properties, such that each entry in the list corresponds to the element of the index given. Example: let properties: 'one':[1,2,3,4], 'two':[3,5,6] >>> properties_for([2,3,5]) [['one'], ['one', 'two'], ['two...
Returns a list of properties, such that each entry in the list corresponds to the element of the index given. Example: let properties: 'one':[1,2,3,4], 'two':[3,5,6] >>> properties_for([2,3,5]) [['one'], ['one', 'two'], ['two']]
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/core/index_operations.py#L132-L143
sods/paramz
paramz/core/index_operations.py
ParameterIndexOperations.properties_dict_for
def properties_dict_for(self, index): """ Return a dictionary, containing properties as keys and indices as index Thus, the indices for each constraint, which is contained will be collected as one dictionary Example: let properties: 'one':[1,2,3,4], 'two':[3,5,6] ...
python
def properties_dict_for(self, index): """ Return a dictionary, containing properties as keys and indices as index Thus, the indices for each constraint, which is contained will be collected as one dictionary Example: let properties: 'one':[1,2,3,4], 'two':[3,5,6] ...
Return a dictionary, containing properties as keys and indices as index Thus, the indices for each constraint, which is contained will be collected as one dictionary Example: let properties: 'one':[1,2,3,4], 'two':[3,5,6] >>> properties_dict_for([2,3,5]) {'one':[2,3], '...
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/core/index_operations.py#L145-L159
sods/paramz
paramz/model.py
Model.optimize
def optimize(self, optimizer=None, start=None, messages=False, max_iters=1000, ipython_notebook=True, clear_after_finish=False, **kwargs): """ Optimize the model using self.log_likelihood and self.log_likelihood_gradient, as well as self.priors. kwargs are passed to the optimizer. They can be: ...
python
def optimize(self, optimizer=None, start=None, messages=False, max_iters=1000, ipython_notebook=True, clear_after_finish=False, **kwargs): """ Optimize the model using self.log_likelihood and self.log_likelihood_gradient, as well as self.priors. kwargs are passed to the optimizer. They can be: ...
Optimize the model using self.log_likelihood and self.log_likelihood_gradient, as well as self.priors. kwargs are passed to the optimizer. They can be: :param max_iters: maximum number of function evaluations :type max_iters: int :messages: True: Display messages during optimisation, "...
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/model.py#L65-L116
sods/paramz
paramz/model.py
Model.optimize_restarts
def optimize_restarts(self, num_restarts=10, robust=False, verbose=True, parallel=False, num_processes=None, **kwargs): """ Perform random restarts of the model, and set the model to the best seen solution. If the robust flag is set, exceptions raised during optimizations will b...
python
def optimize_restarts(self, num_restarts=10, robust=False, verbose=True, parallel=False, num_processes=None, **kwargs): """ Perform random restarts of the model, and set the model to the best seen solution. If the robust flag is set, exceptions raised during optimizations will b...
Perform random restarts of the model, and set the model to the best seen solution. If the robust flag is set, exceptions raised during optimizations will be handled silently. If _all_ runs fail, the model is reset to the existing parameter values. \*\*kwargs are passed to the ...
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/model.py#L118-L190
sods/paramz
paramz/model.py
Model._grads
def _grads(self, x): """ Gets the gradients from the likelihood and the priors. Failures are handled robustly. The algorithm will try several times to return the gradients, and will raise the original exception if the objective cannot be computed. :param x: the paramete...
python
def _grads(self, x): """ Gets the gradients from the likelihood and the priors. Failures are handled robustly. The algorithm will try several times to return the gradients, and will raise the original exception if the objective cannot be computed. :param x: the paramete...
Gets the gradients from the likelihood and the priors. Failures are handled robustly. The algorithm will try several times to return the gradients, and will raise the original exception if the objective cannot be computed. :param x: the parameters of the model. :type x: np.arra...
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/model.py#L225-L246
sods/paramz
paramz/model.py
Model._objective
def _objective(self, x): """ The objective function passed to the optimizer. It combines the likelihood and the priors. Failures are handled robustly. The algorithm will try several times to return the objective, and will raise the original exception if the objective can...
python
def _objective(self, x): """ The objective function passed to the optimizer. It combines the likelihood and the priors. Failures are handled robustly. The algorithm will try several times to return the objective, and will raise the original exception if the objective can...
The objective function passed to the optimizer. It combines the likelihood and the priors. Failures are handled robustly. The algorithm will try several times to return the objective, and will raise the original exception if the objective cannot be computed. :param x: the param...
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/model.py#L248-L269
sods/paramz
paramz/model.py
Model._checkgrad
def _checkgrad(self, target_param=None, verbose=False, step=1e-6, tolerance=1e-3, df_tolerance=1e-12): """ Check the gradient of the ,odel by comparing to a numerical estimate. If the verbose flag is passed, individual components are tested (and printed) :param verbose: If True...
python
def _checkgrad(self, target_param=None, verbose=False, step=1e-6, tolerance=1e-3, df_tolerance=1e-12): """ Check the gradient of the ,odel by comparing to a numerical estimate. If the verbose flag is passed, individual components are tested (and printed) :param verbose: If True...
Check the gradient of the ,odel by comparing to a numerical estimate. If the verbose flag is passed, individual components are tested (and printed) :param verbose: If True, print a "full" checking of each parameter :type verbose: bool :param step: The size of the step around wh...
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/model.py#L284-L408
sods/paramz
paramz/model.py
Model._repr_html_
def _repr_html_(self): """Representation of the model in html for notebook display.""" model_details = [['<b>Model</b>', self.name + '<br>'], ['<b>Objective</b>', '{}<br>'.format(float(self.objective_function()))], ["<b>Number of Parameters</b>", '{}<br>...
python
def _repr_html_(self): """Representation of the model in html for notebook display.""" model_details = [['<b>Model</b>', self.name + '<br>'], ['<b>Objective</b>', '{}<br>'.format(float(self.objective_function()))], ["<b>Number of Parameters</b>", '{}<br>...
Representation of the model in html for notebook display.
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/model.py#L410-L427
sods/paramz
paramz/core/indexable.py
Indexable.add_index_operation
def add_index_operation(self, name, operations): """ Add index operation with name to the operations given. raises: attribute error if operations exist. """ if name not in self._index_operations: self._add_io(name, operations) else: raise Attribut...
python
def add_index_operation(self, name, operations): """ Add index operation with name to the operations given. raises: attribute error if operations exist. """ if name not in self._index_operations: self._add_io(name, operations) else: raise Attribut...
Add index operation with name to the operations given. raises: attribute error if operations exist.
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/core/indexable.py#L81-L90
sods/paramz
paramz/core/indexable.py
Indexable._disconnect_parent
def _disconnect_parent(self, *args, **kw): """ From Parentable: disconnect the parent and set the new constraints to constr """ for name, iop in list(self._index_operations.items()): iopc = iop.copy() iop.clear() self.remove_index_operation(nam...
python
def _disconnect_parent(self, *args, **kw): """ From Parentable: disconnect the parent and set the new constraints to constr """ for name, iop in list(self._index_operations.items()): iopc = iop.copy() iop.clear() self.remove_index_operation(nam...
From Parentable: disconnect the parent and set the new constraints to constr
https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/core/indexable.py#L110-L125