idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
21,000
def locate ( self , store = current_store ) : if not isinstance ( store , Store ) : raise TypeError ( 'store must be an instance of ' 'sqlalchemy_imageattach.store.Store, not ' + repr ( store ) ) return store . locate ( self )
Gets the URL of the image from the store .
21,001
def _original_images ( self , ** kwargs ) : def test ( image ) : if not image . original : return False for filter , value in kwargs . items ( ) : if getattr ( image , filter ) != value : return False return True if Session . object_session ( self . instance ) is None : images = [ ] for image , store in self . _stored_...
A list of the original images .
21,002
def from_file ( self , file , store = current_store , extra_args = None , extra_kwargs = None ) : if isinstance ( file , cgi . FieldStorage ) : file = file . file data = io . BytesIO ( ) shutil . copyfileobj ( file , data ) data . seek ( 0 ) return self . from_raw_file ( data , store , original = True , extra_args = ex...
Stores the file for the image into the store .
21,003
def clear_database ( self ) -> None : 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 .
21,004
def add_processor ( self , processor_instance : Processor , priority = 0 ) -> None : assert issubclass ( processor_instance . __class__ , Processor ) processor_instance . priority = priority processor_instance . world = self self . _processors . append ( processor_instance ) self . _processors . sort ( key = lambda pro...
Add a Processor instance to the World .
21,005
def remove_processor ( self , processor_type : Processor ) -> None : for processor in self . _processors : if type ( processor ) == processor_type : processor . world = None self . _processors . remove ( processor )
Remove a Processor from the World by type .
21,006
def get_processor ( self , processor_type : Type [ P ] ) -> P : for processor in self . _processors : if type ( processor ) == processor_type : return processor
Get a Processor instance by type .
21,007
def create_entity ( self , * components ) -> int : self . _next_entity_id += 1 for component in components : self . add_component ( self . _next_entity_id , component ) return self . _next_entity_id
Create a new Entity .
21,008
def delete_entity ( self , entity : int , immediate = False ) -> None : if immediate : for component_type in self . _entities [ entity ] : self . _components [ component_type ] . discard ( entity ) if not self . _components [ component_type ] : del self . _components [ component_type ] del self . _entities [ entity ] s...
Delete an Entity from the World .
21,009
def component_for_entity ( self , entity : int , component_type : Type [ C ] ) -> C : return self . _entities [ entity ] [ component_type ]
Retrieve a Component instance for a specific Entity .
21,010
def components_for_entity ( self , entity : int ) -> Tuple [ C , ... ] : return tuple ( self . _entities [ entity ] . values ( ) )
Retrieve all Components for a specific Entity as a Tuple .
21,011
def has_component ( self , entity : int , component_type : Any ) -> bool : return component_type in self . _entities [ entity ]
Check if a specific Entity has a Component of a certain type .
21,012
def add_component ( self , entity : int , component_instance : Any ) -> None : component_type = type ( component_instance ) if component_type not in self . _components : self . _components [ component_type ] = set ( ) self . _components [ component_type ] . add ( entity ) if entity not in self . _entities : self . _ent...
Add a new Component instance to an Entity .
21,013
def remove_component ( self , entity : int , component_type : Any ) -> int : self . _components [ component_type ] . discard ( entity ) if not self . _components [ component_type ] : del self . _components [ component_type ] del self . _entities [ entity ] [ component_type ] if not self . _entities [ entity ] : del sel...
Remove a Component instance from an Entity by type .
21,014
def _get_component ( self , component_type : Type [ C ] ) -> Iterable [ Tuple [ int , C ] ] : entity_db = self . _entities for entity in self . _components . get ( component_type , [ ] ) : yield entity , entity_db [ entity ] [ component_type ]
Get an iterator for Entity Component pairs .
21,015
def _get_components ( self , * component_types : Type ) -> Iterable [ Tuple [ int , ... ] ] : entity_db = self . _entities comp_db = self . _components try : for entity in set . intersection ( * [ comp_db [ ct ] for ct in component_types ] ) : yield entity , [ entity_db [ entity ] [ ct ] for ct in component_types ] exc...
Get an iterator for Entity and multiple Component sets .
21,016
def try_component ( self , entity : int , component_type : Type ) : if component_type in self . _entities [ entity ] : yield self . _entities [ entity ] [ component_type ] else : return None
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 .
21,017
def _clear_dead_entities ( self ) : for entity in self . _dead_entities : for component_type in self . _entities [ entity ] : self . _components [ component_type ] . discard ( entity ) if not self . _components [ component_type ] : del self . _components [ component_type ] del self . _entities [ entity ] self . _dead_e...
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 .
21,018
def _timed_process ( self , * args , ** kwargs ) : for processor in self . _processors : start_time = _time . process_time ( ) processor . process ( * args , ** kwargs ) process_time = int ( round ( ( _time . process_time ( ) - start_time ) * 1000 , 2 ) ) self . process_times [ processor . __class__ . __name__ ] = proc...
Track Processor execution time for benchmarking .
21,019
def process ( self , * args , ** kwargs ) : self . _clear_dead_entities ( ) self . _process ( * args , ** kwargs )
Call the process method on all Processors in order of their priority .
21,020
def texture_from_image ( renderer , image_name ) : 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
21,021
def setup_tree ( ctx , verbose = None , root = None , tree_dir = None , modules_dir = None ) : 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
21,022
def set_roots ( self , uproot_with = None ) : self . treedir = os . environ . get ( 'TREE_DIR' , None ) if not uproot_with else uproot_with if not self . treedir : treefilepath = os . path . dirname ( os . path . abspath ( __file__ ) ) if 'python/' in treefilepath : self . treedir = treefilepath . rsplit ( '/' , 2 ) [ ...
Set the roots of the tree in the os environment
21,023
def load_config ( self , config = None ) : cfgname = ( config or self . config_name ) cfgname = 'sdsswork' if cfgname is None else cfgname assert isinstance ( cfgname , six . string_types ) , 'config name must be a string' config_name = cfgname if cfgname . endswith ( '.cfg' ) else '{0}.cfg' . format ( cfgname ) self ....
loads a config file
21,024
def branch_out ( self , limb = None ) : if not limb : limbs = self . _cfg . sections ( ) else : limb = limb if isinstance ( limb , list ) else [ limb ] limbs = [ 'general' ] limbs . extend ( limb ) for leaf in limbs : leaf = leaf if leaf in self . _cfg . sections ( ) else leaf . upper ( ) self . environ [ leaf ] = Orde...
Set the individual section branches
21,025
def add_limbs ( self , key = None ) : self . branch_out ( limb = key ) self . add_paths_to_os ( key = key )
Add a new section from the tree into the existing os environment
21,026
def get_paths ( self , key ) : newkey = key if key in self . environ else key . upper ( ) if key . upper ( ) in self . environ else None if newkey : return self . environ [ newkey ] else : raise KeyError ( 'Key {0} not found in tree environment' . format ( key ) )
Retrieve a set of environment paths from the config
21,027
def add_paths_to_os ( self , key = None , update = None ) : if key is not None : allpaths = key if isinstance ( key , list ) else [ key ] else : allpaths = [ k for k in self . environ . keys ( ) if 'default' not in k ] for key in allpaths : paths = self . get_paths ( key ) self . check_paths ( paths , update = update )
Add the paths in tree environ into the os environ
21,028
def check_paths ( self , paths , update = None ) : exclude = [ ] if not self . exclude else self . exclude if isinstance ( self . exclude , list ) else [ self . exclude ] for pathname , path in paths . items ( ) : if update and pathname . upper ( ) not in exclude : os . environ [ pathname . upper ( ) ] = os . path . no...
Check if the path is in the os environ and if not add it
21,029
def replant_tree ( self , config = None , exclude = None ) : self . __init__ ( key = self . key , config = config , update = True , exclude = exclude )
Replant the tree with a different config setup
21,030
def print_exception_formatted ( type , value , tb ) : tbtext = '' . join ( traceback . format_exception ( type , value , tb ) ) lexer = get_lexer_by_name ( 'pytb' , stripall = True ) formatter = TerminalFormatter ( ) sys . stderr . write ( highlight ( tbtext , lexer , formatter ) )
A custom hook for printing tracebacks with colours .
21,031
def colored_formatter ( record ) : colours = { 'info' : ( 'blue' , 'normal' ) , 'debug' : ( 'magenta' , 'normal' ) , 'warning' : ( 'yellow' , 'normal' ) , 'print' : ( 'green' , 'normal' ) , 'error' : ( 'red' , 'bold' ) } levelname = record . levelname . lower ( ) if levelname == 'error' : return if levelname . lower ( ...
Prints log messages with colours .
21,032
def _catch_exceptions ( self , exctype , value , tb ) : self . error ( 'Uncaught exception' , exc_info = ( exctype , value , tb ) ) print_exception_formatted ( exctype , value , tb )
Catches all exceptions and logs them .
21,033
def _set_defaults ( self , log_level = logging . INFO , redirect_stdout = False ) : for handler in self . handlers [ : ] : self . removeHandler ( handler ) self . setLevel ( logging . DEBUG ) self . fh = None self . sh = logging . StreamHandler ( ) self . sh . emit = colored_formatter self . addHandler ( self . sh ) se...
Reset logger to its initial state .
21,034
def start_file_logger ( self , name , log_file_level = logging . DEBUG , log_file_path = './' ) : 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 ) if log_file_path . exists ( ) : strtime = date...
Start file logging .
21,035
def create_index_page ( environ , defaults , envdir ) : header = footer = index = header . format ( ** defaults ) index += create_index_table ( environ , envdir ) index += footer . format ( ** defaults ) return index
create the env index html page Builds the index . html page containing a table of symlinks to datamodel directories
21,036
def create_env ( environ , mirror = None , verbose = None ) : defaults = environ [ 'default' ] . copy ( ) defaults [ 'url' ] = "https://data.mirror.sdss.org" if mirror else "https://data.sdss.org" defaults [ 'location' ] = "SDSS-IV Science Archive Mirror (SAM)" if mirror else "SDSS-IV Science Archive Server (SAS)" if n...
create the env symlink directory structure Creates the env folder filled with symlinks to datamodel directories for a given tree config file .
21,037
def check_sas_base_dir ( root = None ) : sasbasedir = root or os . getenv ( "SAS_BASE_DIR" ) if not sasbasedir : sasbasedir = input ( 'Enter a path for SAS_BASE_DIR: ' ) os . environ [ 'SAS_BASE_DIR' ] = sasbasedir
Check for the SAS_BASE_DIR environment variable
21,038
def write_file ( environ , term = 'bash' , out_dir = None , tree_dir = None ) : name = environ [ 'default' ] [ 'name' ] header = write_header ( term = term , name = name , tree_dir = tree_dir ) exts = { 'bash' : '.sh' , 'tsch' : '.csh' , 'modules' : '.module' } ext = exts [ term ] if term == 'bash' : cmd = 'export {0}=...
Write a tree environment file
21,039
def get_tree ( config = None ) : path = os . path . dirname ( os . path . abspath ( __file__ ) ) pypath = os . path . realpath ( os . path . join ( path , '..' , 'python' ) ) if pypath not in sys . path : sys . path . append ( pypath ) os . chdir ( pypath ) from tree . tree import Tree tree = Tree ( config = config ) r...
Get the tree for a given config
21,040
def copy_modules ( filespath = None , modules_path = None , verbose = None ) : if not modules_path : modulepath = os . getenv ( "MODULEPATH" ) if not modulepath : modules_path = input ( 'Enter the root path for your module files:' ) else : split_mods = modulepath . split ( ':' ) if len ( split_mods ) > 1 : if verbose :...
Copy over the tree module files into your path
21,041
def _indent ( text , level = 1 ) : 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
21,042
def get_requirements ( opts ) : 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 ( __file__ ) , name ) install_requires = [ line . strip ( ) . replace ( '==' , '>=' ) for line in open...
Get the proper requirements file based on the optional argument
21,043
def remove_args ( 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 . argv . remove ( arg )
Remove custom arguments from the parser
21,044
def _render_log ( ) : config = load_config ( ROOT ) definitions = config [ 'types' ] fragments , fragment_filenames = find_fragments ( pathlib . Path ( config [ 'directory' ] ) . absolute ( ) , config [ 'sections' ] , None , definitions , ) rendered = render_fragments ( pathlib . Path ( config [ 'template' ] ) . read_t...
Totally tap into Towncrier internals to get an in - memory result .
21,045
def adjust_name_for_printing ( name ) : if name is not None : name2 = name name = name . replace ( " " , "_" ) . replace ( "." , "_" ) . replace ( "-" , "_m_" ) name = name . replace ( "+" , "_p_" ) . replace ( "!" , "_I_" ) name = name . replace ( "**" , "_xx_" ) . replace ( "*" , "_x_" ) name = name . replace ( "/" ,...
Make sure a name can be printed alongside used as a variable name .
21,046
def name ( self , name ) : 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 .
21,047
def hierarchy_name ( self , adjust_for_printing = True ) : if adjust_for_printing : adjust = lambda x : adjust_name_for_printing ( x ) else : adjust = lambda x : x if self . has_parent ( ) : return self . _parent_ . hierarchy_name ( ) + "." + adjust ( self . name ) return adjust ( self . name )
return the name for this object with the parents names attached by dots .
21,048
def grep_param_names ( self , regexp ) : if not isinstance ( regexp , _pattern_type ) : regexp = compile ( regexp ) found_params = [ ] def visit ( innerself , regexp ) : if ( innerself is not self ) and regexp . match ( innerself . hierarchy_name ( ) . partition ( '.' ) [ 2 ] ) : found_params . append ( innerself ) sel...
create a list of parameters matching regular expression regexp
21,049
def _setup_observers ( self ) : if self . has_parent ( ) : self . add_observer ( self . _parent_ , self . _parent_ . _pass_through_notify_observers , - np . inf )
Setup the default observers
21,050
def _repr_html_ ( self , indices = None , iops = None , lx = None , li = None , lls = None ) : filter_ = self . _current_slice_ vals = self . flat if indices is None : indices = self . _indices ( filter_ ) if iops is None : ravi = self . _raveled_index ( filter_ ) iops = OrderedDict ( [ name , iop . properties_for ( ra...
Representation of the parameter in html for notebook display .
21,051
def add_observer ( self , observer , callble , priority = 0 ) : self . observers . add ( priority , observer , callble )
Add an observer observer with the callback callble and priority priority to this observers list .
21,052
def notify_observers ( self , which = None , min_priority = None ) : if self . _update_on : if which is None : which = self if min_priority is None : [ callble ( self , which = which ) for _ , _ , callble in self . observers ] else : for p , _ , callble in self . observers : if p <= min_priority : break callble ( self ...
Notifies all observers . Which is the element which kicked off this notification loop . The first argument will be self the second which .
21,053
def constrain_fixed ( self , value = None , warning = True , trigger_parent = True ) : if value is not None : self [ : ] = value index = self . _add_to_index_operations ( self . constraints , np . empty ( 0 ) , __fixed__ , warning ) self . _highest_parent_ . _set_fixed ( self , index ) self . notify_observers ( self , ...
Constrain this parameter to be fixed to the current value it carries .
21,054
def unconstrain_fixed ( self ) : unconstrained = self . unconstrain ( __fixed__ ) self . _highest_parent_ . _set_unfixed ( self , unconstrained ) return unconstrained
This parameter will no longer be fixed .
21,055
def checkgrad ( self , verbose = 0 , step = 1e-6 , tolerance = 1e-3 , df_tolerance = 1e-12 ) : if self . has_parent ( ) : return self . _highest_parent_ . _checkgrad ( self , verbose = verbose , step = step , tolerance = tolerance , df_tolerance = df_tolerance ) return self . _checkgrad ( self , verbose = verbose , ste...
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 gradient is smaller then tolerance .
21,056
def opt ( self , x_init , f_fp = None , f = None , fp = None ) : tnc_rcstrings = [ 'Local minimum' , 'Converged' , 'XConverged' , 'Maximum number of f evaluations reached' , 'Line search failed' , 'Function is constant' ] assert f_fp != None , "TNC requires f_fp" opt_dict = { } if self . xtol is not None : opt_dict [ '...
Run the TNC optimizer
21,057
def opt ( self , x_init , f_fp = None , f = None , fp = None ) : statuses = [ 'Converged' , 'Maximum number of function evaluations made' , 'Maximum number of iterations reached' ] opt_dict = { } if self . xtol is not None : opt_dict [ 'xtol' ] = self . xtol if self . ftol is not None : opt_dict [ 'ftol' ] = self . fto...
The simplex optimizer does not require gradients .
21,058
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 ] ) ) return [ a for i , a in enumerate ( inputs ) if i not in ignore_args...
Combines the args and kw in a unique way such that ordering of kwargs does not lead to recompute
21,059
def ensure_cache_length ( self ) : "Ensures the cache is within its limits and has one place free" if len ( self . order ) == self . limit : cache_id = self . order . popleft ( ) combined_args_kw = self . cached_inputs [ cache_id ] for ind in combined_args_kw : ind_id = self . id ( ind ) tmp = self . cached_input_ids ....
Ensures the cache is within its limits and has one place free
21,060
def add_to_cache ( self , cache_id , inputs , 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 : if a is not None and not isinstance ( a , Number ) and not isinstance ( a , str ...
This adds cache_id to the cache with inputs and output
21,061
def on_cache_changed ( self , direct , which = None ) : for what in [ direct , which ] : ind_id = self . id ( what ) _ , cache_ids = self . cached_input_ids . get ( ind_id , [ None , [ ] ] ) for cache_id in cache_ids : self . inputs_changed [ cache_id ] = True
A callback funtion which sets local flags when the elements of some cached inputs change
21,062
def reset ( self ) : [ 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 = { } self . cached_input_ids = { } self . cached_outputs = { } self . inputs_changed =...
Totally reset the cache
21,063
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
21,064
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 .
21,065
def remove ( self , priority , observer , 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 .
21,066
def add ( self , priority , observer , callble ) : ins = 0 for pr , _ , _ in self : if priority > pr : break ins += 1 self . _poc . insert ( ins , ( priority , weakref . ref ( observer ) , callble ) )
Add an observer with priority and callble
21,067
def properties_for ( self , index ) : return vectorize ( lambda i : [ prop for prop in self . properties ( ) if i in self [ prop ] ] , otypes = [ list ] ) ( index )
Returns a list of properties such that each entry in the list corresponds to the element of the index given .
21,068
def properties_dict_for ( self , index ) : props = self . properties_for ( index ) prop_index = extract_properties_to_index ( index , props ) return prop_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
21,069
def optimize ( self , optimizer = None , start = None , messages = False , max_iters = 1000 , ipython_notebook = True , clear_after_finish = False , ** kwargs ) : if self . is_fixed or self . size == 0 : print ( 'nothing to optimize' ) return if not self . update_model ( ) : print ( "updates were off, setting updates o...
Optimize the model using self . log_likelihood and self . log_likelihood_gradient as well as self . priors .
21,070
def optimize_restarts ( self , num_restarts = 10 , robust = False , verbose = True , parallel = False , num_processes = None , ** kwargs ) : initial_length = len ( self . optimization_runs ) initial_parameters = self . optimizer_array . copy ( ) if parallel : try : pool = mp . Pool ( processes = num_processes ) obs = [...
Perform random restarts of the model and set the model to the best seen solution .
21,071
def _grads ( self , x ) : try : self . optimizer_array = x self . obj_grads = self . _transform_gradients ( self . objective_function_gradients ( ) ) self . _fail_count = 0 except ( LinAlgError , ZeroDivisionError , ValueError ) : if self . _fail_count >= self . _allowed_failures : raise self . _fail_count += 1 self . ...
Gets the gradients from the likelihood and the priors .
21,072
def _objective ( self , x ) : try : self . optimizer_array = x obj = self . objective_function ( ) self . _fail_count = 0 except ( LinAlgError , ZeroDivisionError , ValueError ) : if self . _fail_count >= self . _allowed_failures : raise self . _fail_count += 1 return np . inf return obj
The objective function passed to the optimizer . It combines the likelihood and the priors .
21,073
def _repr_html_ ( self ) : model_details = [ [ '<b>Model</b>' , self . name + '<br>' ] , [ '<b>Objective</b>' , '{}<br>' . format ( float ( self . objective_function ( ) ) ) ] , [ "<b>Number of Parameters</b>" , '{}<br>' . format ( self . size ) ] , [ "<b>Number of Optimization Parameters</b>" , '{}<br>' . format ( sel...
Representation of the model in html for notebook display .
21,074
def add_index_operation ( self , name , operations ) : if name not in self . _index_operations : self . _add_io ( name , operations ) else : raise AttributeError ( "An index operation with the name {} was already taken" . format ( name ) )
Add index operation with name to the operations given .
21,075
def _offset_for ( self , param ) : if param . has_parent ( ) : p = param . _parent_ . _get_original ( param ) if p in self . parameters : return reduce ( lambda a , b : a + b . size , self . parameters [ : p . _parent_index_ ] , 0 ) return self . _offset_for ( param . _parent_ ) + param . _parent_ . _offset_for ( param...
Return the offset of the param inside this parameterized object . This does not need to account for shaped parameters as it basically just sums up the parameter sizes which come before param .
21,076
def _raveled_index_for ( self , param ) : from . . param import ParamConcatenation if isinstance ( param , ParamConcatenation ) : return np . hstack ( ( self . _raveled_index_for ( p ) for p in param . params ) ) return param . _raveled_index ( ) + self . _offset_for ( param )
get the raveled index for a param that is an int array containing the indexes for the flattened param inside this parameterized logic .
21,077
def copy ( self ) : from . lists_and_dicts import ObserverList memo = { } memo [ id ( self ) ] = self memo [ id ( self . observers ) ] = ObserverList ( ) return self . __deepcopy__ ( memo )
Make a copy . This means we delete all observers and return a copy of this array . It will still be an ObsAr!
21,078
def update_model ( self , updates = None ) : if updates is None : return self . _update_on assert isinstance ( updates , bool ) , "updates are either on (True) or off (False)" p = getattr ( self , '_highest_parent_' , None ) def turn_updates ( s ) : s . _update_on = updates p . traverse ( turn_updates ) self . trigger_...
Get or set whether automatic updates are performed . When updates are off the model might be in a non - working state . To make the model work turn updates on again .
21,079
def trigger_update ( self , trigger_parent = True ) : if not self . update_model ( ) or ( hasattr ( self , "_in_init_" ) and self . _in_init_ ) : return self . _trigger_params_changed ( trigger_parent )
Update the model from the current state . Make sure that updates are on otherwise this method will do nothing
21,080
def optimizer_array ( self ) : if self . __dict__ . get ( '_optimizer_copy_' , None ) is None or self . size != self . _optimizer_copy_ . size : self . _optimizer_copy_ = np . empty ( self . size ) if not self . _optimizer_copy_transformed : self . _optimizer_copy_ . flat = self . param_array . flat [ np . put ( self ....
Array for the optimizer to work on . This array always lives in the space for the optimizer . Thus it is untransformed going from Transformations .
21,081
def _trigger_params_changed ( self , trigger_parent = True ) : [ p . _trigger_params_changed ( trigger_parent = False ) for p in self . parameters if not p . is_fixed ] self . notify_observers ( None , None if trigger_parent else - np . inf )
First tell all children to update then update yourself .
21,082
def _transform_gradients ( self , g ) : [ np . put ( g , i , c . gradfactor ( self . param_array [ i ] , g [ i ] ) ) for c , i in self . constraints . items ( ) if c != __fixed__ ] if self . _has_fixes ( ) : return g [ self . _fixes_ ] return g
Transform the gradients by multiplying the gradient factor for each constraint to it .
21,083
def parameter_names ( self , add_self = False , adjust_for_printing = False , recursive = True , intermediate = False ) : if adjust_for_printing : adjust = adjust_name_for_printing else : adjust = lambda x : x names = [ ] if intermediate or ( not recursive ) : names . extend ( [ adjust ( x . name ) for x in self . para...
Get the names of all parameters of this model or parameter . It starts from the parameterized object you are calling this method on .
21,084
def parameter_names_flat ( self , include_fixed = False ) : name_list = [ ] for p in self . flattened_parameters : name = p . hierarchy_name ( ) if p . size > 1 : name_list . extend ( [ "{}[{!s}]" . format ( name , i ) for i in p . _indices ( ) ] ) else : name_list . append ( name ) name_list = np . array ( name_list )...
Return the flattened parameter names for all subsequent parameters of this parameter . We do not include the name for self here!
21,085
def _propagate_param_grad ( self , parray , garray ) : pi_old_size = 0 for pi in self . parameters : pislice = slice ( pi_old_size , pi_old_size + pi . size ) self . param_array [ pislice ] = pi . param_array . flat self . gradient_full [ pislice ] = pi . gradient_full . flat pi . param_array . data = parray [ pislice ...
For propagating the param_array and gradient_array . This ensures the in memory view of each subsequent array .
21,086
def initialize_parameter ( self ) : self . _highest_parent_ . _notify_parent_change ( ) self . _highest_parent_ . _connect_parameters ( ) self . _highest_parent_ . _connect_fixes ( ) self . trigger_update ( )
Call this function to initialize the model if you built it without initialization .
21,087
def traverse_parents ( self , visit , * args , ** kwargs ) : if self . has_parent ( ) : self . __visited = True self . _parent_ . traverse_parents ( visit , * args , ** kwargs ) self . _parent_ . traverse ( visit , * args , ** kwargs ) self . __visited = False
Traverse the hierarchy upwards visiting all parents and their children except self . See visitor pattern in literature . This is implemented in pre - order fashion .
21,088
def phi ( self , Xpred , degrees = None ) : assert Xpred . shape [ 1 ] == self . X . shape [ 1 ] , "Need to predict with same shape as training data." if degrees is None : degrees = range ( self . basis . degree + 1 ) tmp_phi = np . empty ( ( len ( degrees ) , Xpred . shape [ 0 ] , Xpred . shape [ 1 ] ) ) for i , w in ...
Compute the design matrix for this model using the degrees given by the index array in degrees
21,089
def consolidate_dependencies ( needs_ipython , child_program , requirement_files , manual_dependencies ) : logger = logging . getLogger ( 'fades' ) if needs_ipython : logger . debug ( "Adding ipython dependency because --ipython was detected" ) ipython_dep = parsing . parse_manual ( [ 'ipython' ] ) else : ipython_dep =...
Parse files get deps and merge them . Deps read later overwrite those read earlier .
21,090
def detect_inside_virtualenv ( prefix , real_prefix , base_prefix ) : if real_prefix is not None : return True if base_prefix is None : return False return prefix != base_prefix
Tell if fades is running inside a virtualenv .
21,091
def _get_normalized_args ( parser ) : env = os . environ if '_' in env and env [ '_' ] != sys . argv [ 0 ] and len ( sys . argv ) >= 1 and " " in sys . argv [ 1 ] : return parser . parse_args ( shlex . split ( sys . argv [ 1 ] ) + sys . argv [ 2 : ] ) else : return parser . parse_args ( )
Return the parsed command line arguments .
21,092
def parse_fade_requirement ( text ) : text = text . strip ( ) if "::" in text : repo_raw , requirement = text . split ( "::" , 1 ) try : repo = { 'pypi' : REPO_PYPI , 'vcs' : REPO_VCS } [ repo_raw ] except KeyError : logger . warning ( "Not understood fades repository: %r" , repo_raw ) return else : if ":" in text and ...
Return a requirement and repo from the given text already parsed and converted .
21,093
def _parse_content ( fh ) : content = iter ( fh ) deps = { } for line in content : if 'fades' not in line : continue if '#' not in line : continue line = line . strip ( ) index_of_last_fades = line . rfind ( 'fades' ) index_of_first_hash = line . index ( '#' ) if index_of_first_hash > index_of_last_fades : continue imp...
Parse the content of a script to find marked dependencies .
21,094
def _parse_docstring ( fh ) : find_fades = re . compile ( r'\b(fades)\b:' ) . search for line in fh : if line . startswith ( "'" ) : quote = "'" break if line . startswith ( '"' ) : quote = '"' break else : return { } if line [ 1 ] == quote : endquote = quote * 3 else : endquote = quote if endquote in line [ len ( endq...
Parse the docstrings of a script to find marked dependencies .
21,095
def _parse_requirement ( iterable ) : deps = { } for line in iterable : line = line . strip ( ) if not line or line [ 0 ] == '#' : continue parsed_req = parse_fade_requirement ( line ) if parsed_req is None : continue repo , dependency = parsed_req deps . setdefault ( repo , [ ] ) . append ( dependency ) return deps
Actually parse the requirements from file or manually specified .
21,096
def _read_lines ( filepath ) : with open ( filepath , 'rt' , encoding = 'utf8' ) as fh : for line in fh : line = line . strip ( ) if line . startswith ( "-r" ) : logger . debug ( "Reading deps from nested requirement file: %s" , line ) try : nested_filename = line . split ( ) [ 1 ] except IndexError : logger . warning ...
Read a req file to a list to support nested requirement files .
21,097
def create_venv ( requested_deps , interpreter , is_current , options , pip_options ) : env = _FadesEnvBuilder ( ) env_path , env_bin_path , pip_installed = env . create_env ( interpreter , is_current , options ) venv_data = { } venv_data [ 'env_path' ] = env_path venv_data [ 'env_bin_path' ] = env_bin_path venv_data [...
Create a new virtualvenv with the requirements of this script .
21,098
def destroy_venv ( env_path , venvscache = None ) : logger . debug ( "Destroying virtualenv at: %s" , env_path ) shutil . rmtree ( env_path , ignore_errors = True ) if venvscache is not None : venvscache . remove ( env_path )
Destroy a venv .
21,099
def create_with_virtualenv ( self , interpreter , virtualenv_options ) : args = [ 'virtualenv' , '--python' , interpreter , self . env_path ] args . extend ( virtualenv_options ) if not self . pip_installed : args . insert ( 3 , '--no-pip' ) try : helpers . logged_exec ( args ) self . env_bin_path = os . path . join ( ...
Create a virtualenv using the virtualenv lib .