idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
15,200 | def add_inverse_distances ( self , indices , periodic = True , indices2 = None ) : from . distances import InverseDistanceFeature atom_pairs = _parse_pairwise_input ( indices , indices2 , self . logger , fname = 'add_inverse_distances()' ) atom_pairs = self . _check_indices ( atom_pairs ) f = InverseDistanceFeature ( self . topology , atom_pairs , periodic = periodic ) self . __add_feature ( f ) | Adds the inverse distances between atoms to the feature list . |
15,201 | def add_contacts ( self , indices , indices2 = None , threshold = 0.3 , periodic = True , count_contacts = False ) : r from . distances import ContactFeature atom_pairs = _parse_pairwise_input ( indices , indices2 , self . logger , fname = 'add_contacts()' ) atom_pairs = self . _check_indices ( atom_pairs ) f = ContactFeature ( self . topology , atom_pairs , threshold , periodic , count_contacts ) self . __add_feature ( f ) | r Adds the contacts to the feature list . |
15,202 | def add_angles ( self , indexes , deg = False , cossin = False , periodic = True ) : from . angles import AngleFeature indexes = self . _check_indices ( indexes , pair_n = 3 ) f = AngleFeature ( self . topology , indexes , deg = deg , cossin = cossin , periodic = periodic ) self . __add_feature ( f ) | Adds the list of angles to the feature list |
15,203 | def add_dihedrals ( self , indexes , deg = False , cossin = False , periodic = True ) : from . angles import DihedralFeature indexes = self . _check_indices ( indexes , pair_n = 4 ) f = DihedralFeature ( self . topology , indexes , deg = deg , cossin = cossin , periodic = periodic ) self . __add_feature ( f ) | Adds the list of dihedrals to the feature list |
15,204 | def add_custom_feature ( self , feature ) : if feature . dimension <= 0 : raise ValueError ( "Dimension has to be positive. " "Please override dimension attribute in feature!" ) if not hasattr ( feature , 'transform' ) : raise ValueError ( "no 'transform' method in given feature" ) elif not callable ( getattr ( feature , 'transform' ) ) : raise ValueError ( "'transform' attribute exists but is not a method" ) self . __add_feature ( feature ) | Adds a custom feature to the feature list . |
15,205 | def add_custom_func ( self , func , dim , * args , ** kwargs ) : description = kwargs . pop ( 'description' , None ) f = CustomFeature ( func , dim = dim , description = description , fun_args = args , fun_kwargs = kwargs ) self . add_custom_feature ( f ) | adds a user defined function to extract features |
15,206 | def remove_all_custom_funcs ( self ) : custom_feats = [ f for f in self . active_features if isinstance ( f , CustomFeature ) ] for f in custom_feats : self . active_features . remove ( f ) | Remove all instances of CustomFeature from the active feature list . |
15,207 | def dimension ( self ) : dim = sum ( f . dimension for f in self . active_features ) return dim | current dimension due to selected features |
15,208 | def transform ( self , traj ) : if not self . active_features : self . add_selection ( np . arange ( self . topology . n_atoms ) ) warnings . warn ( "You have not selected any features. Returning plain coordinates." ) feature_vec = [ ] for f in self . active_features : if isinstance ( f , CustomFeature ) : vec = f . transform ( traj ) . astype ( np . float32 , casting = 'safe' ) if vec . shape [ 0 ] == 0 : vec = np . empty ( ( 0 , f . dimension ) ) if not isinstance ( vec , np . ndarray ) : raise ValueError ( 'Your custom feature %s did not return' ' a numpy.ndarray!' % str ( f . describe ( ) ) ) if not vec . ndim == 2 : raise ValueError ( 'Your custom feature %s did not return' ' a 2d array. Shape was %s' % ( str ( f . describe ( ) ) , str ( vec . shape ) ) ) if not vec . shape [ 0 ] == traj . xyz . shape [ 0 ] : raise ValueError ( 'Your custom feature %s did not return' ' as many frames as it received!' 'Input was %i, output was %i' % ( str ( f . describe ( ) ) , traj . xyz . shape [ 0 ] , vec . shape [ 0 ] ) ) else : vec = f . transform ( traj ) . astype ( np . float32 ) feature_vec . append ( vec ) if len ( feature_vec ) > 1 : res = np . hstack ( feature_vec ) else : res = feature_vec [ 0 ] return res | Maps an mdtraj Trajectory object to the selected output features |
15,209 | def bootstrapping_dtrajs ( dtrajs , lag , N_full , nbs = 10000 , active_set = None ) : Q = len ( dtrajs ) if active_set is not None : N = active_set . size else : N = N_full traj_ind = [ ] state1 = [ ] state2 = [ ] q = 0 for traj in dtrajs : traj_ind . append ( q * np . ones ( traj [ : - lag ] . size ) ) state1 . append ( traj [ : - lag ] ) state2 . append ( traj [ lag : ] ) q += 1 traj_inds = np . concatenate ( traj_ind ) pairs = N_full * np . concatenate ( state1 ) + np . concatenate ( state2 ) data = np . ones ( pairs . size ) Ct_traj = scipy . sparse . coo_matrix ( ( data , ( traj_inds , pairs ) ) , shape = ( Q , N_full * N_full ) ) Ct_traj = Ct_traj . tocsr ( ) svals = np . zeros ( ( nbs , N ) ) for s in range ( nbs ) : sel = np . random . choice ( Q , Q , replace = True ) Ct_sel = Ct_traj [ sel , : ] . sum ( axis = 0 ) Ct_sel = np . asarray ( Ct_sel ) . reshape ( ( N_full , N_full ) ) if active_set is not None : from pyemma . util . linalg import submatrix Ct_sel = submatrix ( Ct_sel , active_set ) svals [ s , : ] = scl . svdvals ( Ct_sel ) smean = np . mean ( svals , axis = 0 ) sdev = np . std ( svals , axis = 0 ) return smean , sdev | Perform trajectory based re - sampling . |
15,210 | def bootstrapping_count_matrix ( Ct , nbs = 10000 ) : N = Ct . shape [ 0 ] T = Ct . sum ( ) p = Ct . toarray ( ) p = np . reshape ( p , ( N * N , ) ) . astype ( np . float ) p = p / T svals = np . zeros ( ( nbs , N ) ) for s in range ( nbs ) : sel = np . random . multinomial ( T , p ) sC = np . reshape ( sel , ( N , N ) ) svals [ s , : ] = scl . svdvals ( sC ) smean = np . mean ( svals , axis = 0 ) sdev = np . std ( svals , axis = 0 ) return smean , sdev | Perform bootstrapping on trajectories to estimate uncertainties for singular values of count matrices . |
15,211 | def twostep_count_matrix ( dtrajs , lag , N ) : rows = [ ] cols = [ ] states = [ ] for dtraj in dtrajs : if dtraj . size > 2 * lag : rows . append ( dtraj [ 0 : - 2 * lag ] ) states . append ( dtraj [ lag : - lag ] ) cols . append ( dtraj [ 2 * lag : ] ) row = np . concatenate ( rows ) col = np . concatenate ( cols ) state = np . concatenate ( states ) data = np . ones ( row . size ) pair = N * row + col C2t = scipy . sparse . coo_matrix ( ( data , ( pair , state ) ) , shape = ( N * N , N ) ) return C2t . tocsc ( ) | Compute all two - step count matrices from discrete trajectories . |
15,212 | def featurizer ( topfile ) : r from pyemma . coordinates . data . featurization . featurizer import MDFeaturizer return MDFeaturizer ( topfile ) | r Featurizer to select features from MD data . |
15,213 | def load ( trajfiles , features = None , top = None , stride = 1 , chunksize = None , ** kw ) : r from pyemma . coordinates . data . util . reader_utils import create_file_reader from pyemma . util . reflection import get_default_args cs = _check_old_chunksize_arg ( chunksize , get_default_args ( load ) [ 'chunksize' ] , ** kw ) if isinstance ( trajfiles , _string_types ) or ( isinstance ( trajfiles , ( list , tuple ) ) and ( any ( isinstance ( item , ( list , tuple , str ) ) for item in trajfiles ) or len ( trajfiles ) is 0 ) ) : reader = create_file_reader ( trajfiles , top , features , chunksize = cs , ** kw ) trajs = reader . get_output ( stride = stride ) if len ( trajs ) == 1 : return trajs [ 0 ] else : return trajs else : raise ValueError ( 'unsupported type (%s) of input' % type ( trajfiles ) ) | r Loads coordinate features into memory . |
15,214 | def source ( inp , features = None , top = None , chunksize = None , ** kw ) : r from pyemma . coordinates . data . _base . iterable import Iterable from pyemma . coordinates . data . util . reader_utils import create_file_reader from pyemma . util . reflection import get_default_args cs = _check_old_chunksize_arg ( chunksize , get_default_args ( source ) [ 'chunksize' ] , ** kw ) if isinstance ( inp , _string_types ) or ( isinstance ( inp , ( list , tuple ) ) and ( any ( isinstance ( item , ( list , tuple , _string_types ) ) for item in inp ) or len ( inp ) is 0 ) ) : reader = create_file_reader ( inp , top , features , chunksize = cs , ** kw ) elif isinstance ( inp , _np . ndarray ) or ( isinstance ( inp , ( list , tuple ) ) and ( any ( isinstance ( item , _np . ndarray ) for item in inp ) or len ( inp ) is 0 ) ) : from pyemma . coordinates . data . data_in_memory import DataInMemory as _DataInMemory reader = _DataInMemory ( inp , chunksize = cs , ** kw ) elif isinstance ( inp , Iterable ) : inp . chunksize = cs return inp else : raise ValueError ( 'unsupported type (%s) of input' % type ( inp ) ) return reader | r Defines trajectory data source |
15,215 | def combine_sources ( sources , chunksize = None ) : r from pyemma . coordinates . data . sources_merger import SourcesMerger return SourcesMerger ( sources , chunk = chunksize ) | r Combines multiple data sources to stream from . |
15,216 | def pipeline ( stages , run = True , stride = 1 , chunksize = None ) : r from pyemma . coordinates . pipelines import Pipeline if not isinstance ( stages , list ) : stages = [ stages ] p = Pipeline ( stages , param_stride = stride , chunksize = chunksize ) if run : p . parametrize ( ) return p | r Data analysis pipeline . |
15,217 | def save_traj ( traj_inp , indexes , outfile , top = None , stride = 1 , chunksize = None , image_molecules = False , verbose = True ) : r from mdtraj import Topology , Trajectory from pyemma . coordinates . data . feature_reader import FeatureReader from pyemma . coordinates . data . fragmented_trajectory_reader import FragmentedTrajectoryReader from pyemma . coordinates . data . util . frames_from_file import frames_from_files from pyemma . coordinates . data . util . reader_utils import enforce_top import itertools if isinstance ( traj_inp , ( FeatureReader , FragmentedTrajectoryReader ) ) : if isinstance ( traj_inp , FragmentedTrajectoryReader ) : if not all ( isinstance ( reader , FeatureReader ) for reader in itertools . chain . from_iterable ( traj_inp . _readers ) ) : raise ValueError ( "Only FeatureReaders (MD-data) are supported for fragmented trajectories." ) trajfiles = traj_inp . filenames_flat top = traj_inp . _readers [ 0 ] [ 0 ] . featurizer . topology else : top = traj_inp . featurizer . topology trajfiles = traj_inp . filenames chunksize = traj_inp . chunksize reader = traj_inp else : if not isinstance ( traj_inp , ( list , tuple ) ) : raise TypeError ( "traj_inp has to be of type list, not %s" % type ( traj_inp ) ) if not isinstance ( top , ( _string_types , Topology , Trajectory ) ) : raise TypeError ( "traj_inp cannot be a list of files without an input " "top of type str (eg filename.pdb), mdtraj.Trajectory or mdtraj.Topology. " "Got type %s instead" % type ( top ) ) trajfiles = traj_inp reader = None top = enforce_top ( top ) indexes = _np . vstack ( indexes ) if len ( trajfiles ) < indexes [ : , 0 ] . max ( ) : raise ValueError ( "traj_inp contains %u trajfiles, " "but indexes will ask for file nr. %u" % ( len ( trajfiles ) , indexes [ : , 0 ] . max ( ) ) ) traj = frames_from_files ( trajfiles , top , indexes , chunksize , stride , reader = reader ) if image_molecules : traj . image_molecules ( inplace = True ) if outfile is None : return traj else : traj . save ( outfile ) if verbose : _logger . info ( "Created file %s" % outfile ) | r Saves a sequence of frames as a single trajectory . |
15,218 | def save_trajs ( traj_inp , indexes , prefix = 'set_' , fmt = None , outfiles = None , inmemory = False , stride = 1 , verbose = False ) : r assert _types . is_iterable ( indexes ) , "Indexes must be an iterable of matrices." if isinstance ( indexes , _np . ndarray ) : if indexes . ndim == 2 : indexes = [ indexes ] for i_indexes in indexes : assert isinstance ( i_indexes , _np . ndarray ) , "The elements in the 'indexes' variable must be numpy.ndarrays" assert i_indexes . ndim == 2 , "The elements in the 'indexes' variable must have ndim = 2, and not %u" % i_indexes . ndim assert i_indexes . shape [ 1 ] == 2 , "The elements in the 'indexes' variable must be of shape (T_i,2), and not (%u,%u)" % i_indexes . shape if fmt is None : import os _ , fmt = os . path . splitext ( traj_inp . filenames [ 0 ] ) else : fmt = '.' + fmt if outfiles is None : outfiles = [ ] for ii in range ( len ( indexes ) ) : outfiles . append ( prefix + '%06u' % ii + fmt ) if len ( indexes ) != len ( outfiles ) : raise Exception ( 'len(indexes) (%s) does not match len(outfiles) (%s)' % ( len ( indexes ) , len ( outfiles ) ) ) if not inmemory : for i_indexes , outfile in zip ( indexes , outfiles ) : save_traj ( traj_inp , i_indexes , outfile , stride = stride , verbose = verbose ) else : traj = save_traj ( traj_inp , indexes , outfile = None , stride = stride , verbose = verbose ) i_idx = 0 for i_indexes , outfile in zip ( indexes , outfiles ) : f_idx = i_idx + len ( i_indexes ) traj [ i_idx : f_idx ] . save ( outfile ) _logger . info ( "Created file %s" % outfile ) i_idx = f_idx return outfiles | r Saves sequences of frames as multiple trajectories . |
15,219 | def cluster_mini_batch_kmeans ( data = None , k = 100 , max_iter = 10 , batch_size = 0.2 , metric = 'euclidean' , init_strategy = 'kmeans++' , n_jobs = None , chunksize = None , skip = 0 , clustercenters = None , ** kwargs ) : r from pyemma . coordinates . clustering . kmeans import MiniBatchKmeansClustering res = MiniBatchKmeansClustering ( n_clusters = k , max_iter = max_iter , metric = metric , init_strategy = init_strategy , batch_size = batch_size , n_jobs = n_jobs , skip = skip , clustercenters = clustercenters ) from pyemma . util . reflection import get_default_args cs = _check_old_chunksize_arg ( chunksize , get_default_args ( cluster_mini_batch_kmeans ) [ 'chunksize' ] , ** kwargs ) if data is not None : res . estimate ( data , chunksize = cs ) else : res . chunksize = chunksize return res | r k - means clustering with mini - batch strategy |
15,220 | def cluster_kmeans ( data = None , k = None , max_iter = 10 , tolerance = 1e-5 , stride = 1 , metric = 'euclidean' , init_strategy = 'kmeans++' , fixed_seed = False , n_jobs = None , chunksize = None , skip = 0 , keep_data = False , clustercenters = None , ** kwargs ) : r from pyemma . coordinates . clustering . kmeans import KmeansClustering res = KmeansClustering ( n_clusters = k , max_iter = max_iter , metric = metric , tolerance = tolerance , init_strategy = init_strategy , fixed_seed = fixed_seed , n_jobs = n_jobs , skip = skip , keep_data = keep_data , clustercenters = clustercenters , stride = stride ) from pyemma . util . reflection import get_default_args cs = _check_old_chunksize_arg ( chunksize , get_default_args ( cluster_kmeans ) [ 'chunksize' ] , ** kwargs ) if data is not None : res . estimate ( data , chunksize = cs ) else : res . chunksize = cs return res | r k - means clustering |
15,221 | def cluster_uniform_time ( data = None , k = None , stride = 1 , metric = 'euclidean' , n_jobs = None , chunksize = None , skip = 0 , ** kwargs ) : r from pyemma . coordinates . clustering . uniform_time import UniformTimeClustering res = UniformTimeClustering ( k , metric = metric , n_jobs = n_jobs , skip = skip , stride = stride ) from pyemma . util . reflection import get_default_args cs = _check_old_chunksize_arg ( chunksize , get_default_args ( cluster_uniform_time ) [ 'chunksize' ] , ** kwargs ) if data is not None : res . estimate ( data , chunksize = cs ) else : res . chunksize = cs return res | r Uniform time clustering |
15,222 | def cluster_regspace ( data = None , dmin = - 1 , max_centers = 1000 , stride = 1 , metric = 'euclidean' , n_jobs = None , chunksize = None , skip = 0 , ** kwargs ) : r if dmin == - 1 : raise ValueError ( "provide a minimum distance for clustering, e.g. 2.0" ) from pyemma . coordinates . clustering . regspace import RegularSpaceClustering as _RegularSpaceClustering res = _RegularSpaceClustering ( dmin , max_centers = max_centers , metric = metric , n_jobs = n_jobs , stride = stride , skip = skip ) from pyemma . util . reflection import get_default_args cs = _check_old_chunksize_arg ( chunksize , get_default_args ( cluster_regspace ) [ 'chunksize' ] , ** kwargs ) if data is not None : res . estimate ( data , chunksize = cs ) else : res . chunksize = cs return res | r Regular space clustering |
15,223 | def assign_to_centers ( data = None , centers = None , stride = 1 , return_dtrajs = True , metric = 'euclidean' , n_jobs = None , chunksize = None , skip = 0 , ** kwargs ) : r if centers is None : raise ValueError ( 'You have to provide centers in form of a filename' ' or NumPy array or a reader created by source function' ) from pyemma . coordinates . clustering . assign import AssignCenters res = AssignCenters ( centers , metric = metric , n_jobs = n_jobs , skip = skip , stride = stride ) from pyemma . util . reflection import get_default_args cs = _check_old_chunksize_arg ( chunksize , get_default_args ( assign_to_centers ) [ 'chunksize' ] , ** kwargs ) if data is not None : res . estimate ( data , chunksize = cs ) if return_dtrajs : return res . dtrajs else : res . chunksize = cs return res | r Assigns data to the nearest cluster centers |
15,224 | def dtraj_T100K_dt10_n ( self , divides ) : disc = np . zeros ( 100 , dtype = int ) divides = np . concatenate ( [ divides , [ 100 ] ] ) for i in range ( len ( divides ) - 1 ) : disc [ divides [ i ] : divides [ i + 1 ] ] = i + 1 return disc [ self . dtraj_T100K_dt10 ] | 100K frames trajectory at timestep 10 arbitrary n - state discretization . |
15,225 | def generate_traj ( self , N , start = None , stop = None , dt = 1 ) : from msmtools . generation import generate_traj return generate_traj ( self . _P , N , start = start , stop = stop , dt = dt ) | Generates a random trajectory of length N with time step dt |
15,226 | def generate_trajs ( self , M , N , start = None , stop = None , dt = 1 ) : from msmtools . generation import generate_trajs return generate_trajs ( self . _P , M , N , start = start , stop = stop , dt = dt ) | Generates M random trajectories of length N each with time step dt |
15,227 | def spd_eig ( W , epsilon = 1e-10 , method = 'QR' , canonical_signs = False ) : assert _np . allclose ( W . T , W ) , 'W is not a symmetric matrix' if method . lower ( ) == 'qr' : from . eig_qr . eig_qr import eig_qr s , V = eig_qr ( W ) elif method . lower ( ) == 'schur' : from scipy . linalg import schur S , V = schur ( W ) s = _np . diag ( S ) else : raise ValueError ( 'method not implemented: ' + method ) s , V = sort_by_norm ( s , V ) evmin = _np . min ( s ) if evmin < 0 : epsilon = max ( epsilon , - evmin + 1e-16 ) evnorms = _np . abs ( s ) n = _np . shape ( evnorms ) [ 0 ] m = n - _np . searchsorted ( evnorms [ : : - 1 ] , epsilon ) if m == 0 : raise _ZeroRankError ( 'All eigenvalues are smaller than %g, rank reduction would discard all dimensions.' % epsilon ) Vm = V [ : , 0 : m ] sm = s [ 0 : m ] if canonical_signs : for j in range ( m ) : jj = _np . argmax ( _np . abs ( Vm [ : , j ] ) ) Vm [ : , j ] *= _np . sign ( Vm [ jj , j ] ) return sm , Vm | Rank - reduced eigenvalue decomposition of symmetric positive definite matrix . |
15,228 | def eig_corr ( C0 , Ct , epsilon = 1e-10 , method = 'QR' , sign_maxelement = False ) : r L = spd_inv_split ( C0 , epsilon = epsilon , method = method , canonical_signs = True ) Ct_trans = _np . dot ( _np . dot ( L . T , Ct ) , L ) if _np . allclose ( Ct . T , Ct ) : from scipy . linalg import eigh l , R_trans = eigh ( Ct_trans ) else : from scipy . linalg import eig l , R_trans = eig ( Ct_trans ) l , R_trans = sort_by_norm ( l , R_trans ) R = _np . dot ( L , R_trans ) if sign_maxelement : for j in range ( R . shape [ 1 ] ) : imax = _np . argmax ( _np . abs ( R [ : , j ] ) ) R [ : , j ] *= _np . sign ( R [ imax , j ] ) return l , R | r Solve generalized eigenvalue problem with correlation matrices C0 and Ct |
15,229 | def mdot ( * args ) : if len ( args ) < 1 : raise ValueError ( 'need at least one argument' ) elif len ( args ) == 1 : return args [ 0 ] elif len ( args ) == 2 : return np . dot ( args [ 0 ] , args [ 1 ] ) else : return np . dot ( args [ 0 ] , mdot ( * args [ 1 : ] ) ) | Computes a matrix product of multiple ndarrays |
15,230 | def submatrix ( M , sel ) : assert len ( M . shape ) == 2 , 'M is not a matrix' assert M . shape [ 0 ] == M . shape [ 1 ] , 'M is not quadratic' if scipy . sparse . issparse ( M ) : C_cc = M . tocsr ( ) else : C_cc = M C_cc = C_cc [ sel , : ] if scipy . sparse . issparse ( M ) : C_cc = C_cc . tocsc ( ) C_cc = C_cc [ : , sel ] if scipy . sparse . issparse ( M ) : return C_cc . tocoo ( ) else : return C_cc | Returns a submatrix of the quadratic matrix M given by the selected columns and row |
15,231 | def meval ( self , f , * args , ** kw ) : return [ _call_member ( M , f , * args , ** kw ) for M in self . models ] | Evaluates the given function call for all models Returns the results of the calls in a list |
15,232 | def u ( self ) : 'weights in the input basis' self . _check_estimated ( ) u_mod = self . u_pc_1 N = self . _R . shape [ 0 ] u_input = np . zeros ( N + 1 ) u_input [ 0 : N ] = self . _R . dot ( u_mod [ 0 : - 1 ] ) u_input [ N ] = u_mod [ - 1 ] - self . mean . dot ( self . _R . dot ( u_mod [ 0 : - 1 ] ) ) return u_input | weights in the input basis |
15,233 | def _estimate_param_scan_worker ( estimator , params , X , evaluate , evaluate_args , failfast , return_exceptions ) : model = None try : estimator . estimate ( X , ** params ) model = estimator . model except KeyboardInterrupt : raise except : e = sys . exc_info ( ) [ 1 ] if isinstance ( estimator , Loggable ) : estimator . logger . warning ( "Ignored error during estimation: %s" % e ) if failfast : raise elif return_exceptions : model = e else : pass res = [ ] if evaluate is None : res . append ( model ) elif _types . is_iterable ( evaluate ) : values = [ ] for ieval , name in enumerate ( evaluate ) : args = ( ) if evaluate_args is not None : args = evaluate_args [ ieval ] if _types . is_string ( args ) : args = ( args , ) try : value = _call_member ( estimator . model , name , failfast , * args ) except AttributeError as e : if failfast : raise e else : value = None values . append ( value ) if len ( values ) == 1 : values = values [ 0 ] res . append ( values ) else : raise ValueError ( 'Invalid setting for evaluate: ' + str ( evaluate ) ) if len ( res ) == 1 : res = res [ 0 ] return res | Method that runs estimation for several parameter settings . |
15,234 | def estimate ( self , X , ** params ) : if params : self . set_params ( ** params ) self . _model = self . _estimate ( X ) assert self . _model is not None self . _estimated = True return self | Estimates the model given the data X |
15,235 | def unregister_signal_handlers ( ) : signal . signal ( SIGNAL_STACKTRACE , signal . SIG_IGN ) signal . signal ( SIGNAL_PDB , signal . SIG_IGN ) | set signal handlers to default |
15,236 | def selection_strategy ( oasis_obj , strategy = 'spectral-oasis' , nsel = 1 , neig = None ) : strategy = strategy . lower ( ) if strategy == 'random' : return SelectionStrategyRandom ( oasis_obj , strategy , nsel = nsel , neig = neig ) elif strategy == 'oasis' : return SelectionStrategyOasis ( oasis_obj , strategy , nsel = nsel , neig = neig ) elif strategy == 'spectral-oasis' : return SelectionStrategySpectralOasis ( oasis_obj , strategy , nsel = nsel , neig = neig ) else : raise ValueError ( 'Selected strategy is unknown: ' + str ( strategy ) ) | Factory for selection strategy object |
15,237 | def _compute_error ( self ) : self . _err = np . sum ( np . multiply ( self . _R_k , self . _C_k . T ) , axis = 0 ) - self . _d | Evaluate the absolute error of the Nystroem approximation for each column |
15,238 | def set_selection_strategy ( self , strategy = 'spectral-oasis' , nsel = 1 , neig = None ) : self . _selection_strategy = selection_strategy ( self , strategy , nsel , neig ) | Defines the column selection strategy |
15,239 | def update_inverse ( self ) : Wk = self . _C_k [ self . _columns , : ] self . _W_k_inv = np . linalg . pinv ( Wk ) self . _R_k = np . dot ( self . _W_k_inv , self . _C_k . T ) | Recomputes W_k_inv and R_k given the current column selection |
15,240 | def approximate_cholesky ( self , epsilon = 1e-6 ) : r Wk = self . _C_k [ self . _columns , : ] L0 = spd_inv_split ( Wk , epsilon = epsilon ) L = np . dot ( self . _C_k , L0 ) return L | r Compute low - rank approximation to the Cholesky decomposition of target matrix . |
15,241 | def approximate_eig ( self , epsilon = 1e-6 ) : L = self . approximate_cholesky ( epsilon = epsilon ) LL = np . dot ( L . T , L ) s , V = np . linalg . eigh ( LL ) s , V = sort_by_norm ( s , V ) Linv = np . linalg . pinv ( L . T ) V = np . dot ( Linv , V ) ncol = V . shape [ 1 ] for i in range ( ncol ) : if not np . allclose ( V [ : , i ] , 0 ) : V [ : , i ] /= np . sqrt ( np . dot ( V [ : , i ] , V [ : , i ] ) ) return s , V | Compute low - rank approximation of the eigenvalue decomposition of target matrix . |
15,242 | def select ( self ) : err = self . _oasis_obj . error if np . allclose ( err , 0 ) : return None nsel = self . _check_nsel ( ) if nsel is None : return None return self . _select ( nsel , err ) | Selects next column indexes according to defined strategy |
15,243 | def delete ( self , name ) : if name not in self . _parent : raise KeyError ( 'model "{}" not present' . format ( name ) ) del self . _parent [ name ] if self . _current_model_group == name : self . _current_model_group = None | deletes model with given name |
15,244 | def select_model ( self , name ) : if name not in self . _parent : raise KeyError ( 'model "{}" not present' . format ( name ) ) self . _current_model_group = name | choose an existing model |
15,245 | def models_descriptive ( self ) : f = self . _parent return { name : { a : f [ name ] . attrs [ a ] for a in H5File . stored_attributes } for name in f . keys ( ) } | list all stored models in given file . |
15,246 | def show_progress ( self ) : from pyemma import config if not hasattr ( self , "_show_progress" ) : val = config . show_progress_bars self . _show_progress = val elif not config . show_progress_bars : return False return self . _show_progress | whether to show the progress of heavy calculations on this object . |
15,247 | def _progress_set_description ( self , stage , description ) : self . __check_stage_registered ( stage ) self . _prog_rep_descriptions [ stage ] = description if self . _prog_rep_progressbars [ stage ] : self . _prog_rep_progressbars [ stage ] . set_description ( description , refresh = False ) | set description of an already existing progress |
15,248 | def _progress_update ( self , numerator_increment , stage = 0 , show_eta = True , ** kw ) : if not self . show_progress : return self . __check_stage_registered ( stage ) if not self . _prog_rep_progressbars [ stage ] : return pg = self . _prog_rep_progressbars [ stage ] pg . update ( int ( numerator_increment ) ) | Updates the progress . Will update progress bars or other progress output . |
15,249 | def _progress_force_finish ( self , stage = 0 , description = None ) : if not self . show_progress : return self . __check_stage_registered ( stage ) if not self . _prog_rep_progressbars [ stage ] : return pg = self . _prog_rep_progressbars [ stage ] pg . desc = description increment = int ( pg . total - pg . n ) if increment > 0 : pg . update ( increment ) pg . refresh ( nolock = True ) pg . close ( ) self . _prog_rep_progressbars . pop ( stage , None ) self . _prog_rep_descriptions . pop ( stage , None ) self . _prog_rep_callbacks . pop ( stage , None ) | forcefully finish the progress for given stage |
15,250 | def plot_feature_histograms ( xyzall , feature_labels = None , ax = None , ylog = False , outfile = None , n_bins = 50 , ignore_dim_warning = False , ** kwargs ) : r if not isinstance ( xyzall , _np . ndarray ) : raise ValueError ( 'Input data hast to be a numpy array. Did you concatenate your data?' ) if xyzall . shape [ 1 ] > 50 and not ignore_dim_warning : raise RuntimeError ( 'This function is only useful for less than 50 dimensions. Turn-off this warning ' 'at your own risk with ignore_dim_warning=True.' ) if feature_labels is not None : if not isinstance ( feature_labels , list ) : from pyemma . coordinates . data . featurization . featurizer import MDFeaturizer as _MDFeaturizer if isinstance ( feature_labels , _MDFeaturizer ) : feature_labels = feature_labels . describe ( ) else : raise ValueError ( 'feature_labels must be a list of feature labels, ' 'a pyemma featurizer object or None.' ) if not xyzall . shape [ 1 ] == len ( feature_labels ) : raise ValueError ( 'feature_labels must have the same dimension as the input data xyzall.' ) if 'color' not in kwargs . keys ( ) : kwargs [ 'color' ] = 'b' if 'alpha' not in kwargs . keys ( ) : kwargs [ 'alpha' ] = .25 import matplotlib . pyplot as _plt if ax is None : fig , ax = _plt . subplots ( ) else : fig = ax . get_figure ( ) hist_offset = - .2 for h , coordinate in enumerate ( reversed ( xyzall . T ) ) : hist , edges = _np . histogram ( coordinate , bins = n_bins ) if not ylog : y = hist / hist . max ( ) else : y = _np . zeros_like ( hist ) + _np . NaN pos_idx = hist > 0 y [ pos_idx ] = _np . log ( hist [ pos_idx ] ) / _np . log ( hist [ pos_idx ] ) . max ( ) ax . fill_between ( edges [ : - 1 ] , y + h + hist_offset , y2 = h + hist_offset , ** kwargs ) ax . axhline ( y = h + hist_offset , xmin = 0 , xmax = 1 , color = 'k' , linewidth = .2 ) ax . set_ylim ( hist_offset , h + hist_offset + 1 ) if feature_labels is None : feature_labels = [ str ( n ) for n in range ( xyzall . shape [ 1 ] ) ] ax . set_ylabel ( 'Feature histograms' ) ax . set_yticks ( _np . array ( range ( len ( feature_labels ) ) ) + .3 ) ax . set_yticklabels ( feature_labels [ : : - 1 ] ) ax . set_xlabel ( 'Feature values' ) if outfile is not None : fig . savefig ( outfile ) return fig , ax | r Feature histogram plot |
15,251 | def in_memory ( self , op_in_mem ) : r old_state = self . in_memory if not old_state and op_in_mem : self . _map_to_memory ( ) elif not op_in_mem and old_state : self . _clear_in_memory ( ) | r If set to True the output will be stored in memory . |
15,252 | def expectation ( self , observables , statistics , lag_multiple = 1 , observables_mean_free = False , statistics_mean_free = False ) : r dim = self . dimension ( ) S = np . diag ( np . concatenate ( ( [ 1.0 ] , self . singular_values [ 0 : dim ] ) ) ) V = self . V [ : , 0 : dim ] U = self . U [ : , 0 : dim ] m_0 = self . mean_0 m_t = self . mean_t assert lag_multiple >= 1 , 'lag_multiple = 0 not implemented' if lag_multiple == 1 : P = S else : p = np . zeros ( ( dim + 1 , dim + 1 ) ) p [ 0 , 0 ] = 1.0 p [ 1 : , 0 ] = U . T . dot ( m_t - m_0 ) p [ 1 : , 1 : ] = U . T . dot ( self . Ctt ) . dot ( V ) P = np . linalg . matrix_power ( S . dot ( p ) , lag_multiple - 1 ) . dot ( S ) Q = np . zeros ( ( observables . shape [ 1 ] , dim + 1 ) ) if not observables_mean_free : Q [ : , 0 ] = observables . T . dot ( m_t ) Q [ : , 1 : ] = observables . T . dot ( self . Ctt ) . dot ( V ) if statistics is not None : R = np . zeros ( ( statistics . shape [ 1 ] , dim + 1 ) ) if not statistics_mean_free : R [ : , 0 ] = statistics . T . dot ( m_0 ) R [ : , 1 : ] = statistics . T . dot ( self . C00 ) . dot ( U ) if statistics is not None : return Q . dot ( P ) . dot ( R . T ) else : return Q . dot ( P ) [ : , 0 ] | r Compute future expectation of observable or covariance using the approximated Koopman operator . |
15,253 | def _diagonalize ( self ) : L0 = spd_inv_split ( self . C00 , epsilon = self . epsilon ) self . _rank0 = L0 . shape [ 1 ] if L0 . ndim == 2 else 1 Lt = spd_inv_split ( self . Ctt , epsilon = self . epsilon ) self . _rankt = Lt . shape [ 1 ] if Lt . ndim == 2 else 1 W = np . dot ( L0 . T , self . C0t ) . dot ( Lt ) from scipy . linalg import svd A , s , BT = svd ( W , compute_uv = True , lapack_driver = 'gesvd' ) self . _singular_values = s m = VAMPModel . _dimension ( self . _rank0 , self . _rankt , self . dim , self . _singular_values ) U = np . dot ( L0 , A [ : , : m ] ) V = np . dot ( Lt , BT [ : m , : ] . T ) if self . scaling is not None : U *= s [ np . newaxis , 0 : m ] V *= s [ np . newaxis , 0 : m ] self . _U = U self . _V = V self . _svd_performed = True | Performs SVD on covariance matrices and save left right singular vectors and values in the model . |
15,254 | def score ( self , test_model = None , score_method = 'VAMP2' ) : if test_model is None : test_model = self Uk = self . U [ : , 0 : self . dimension ( ) ] Vk = self . V [ : , 0 : self . dimension ( ) ] res = None if score_method == 'VAMP1' or score_method == 'VAMP2' : A = spd_inv_sqrt ( Uk . T . dot ( test_model . C00 ) . dot ( Uk ) ) B = Uk . T . dot ( test_model . C0t ) . dot ( Vk ) C = spd_inv_sqrt ( Vk . T . dot ( test_model . Ctt ) . dot ( Vk ) ) ABC = mdot ( A , B , C ) if score_method == 'VAMP1' : res = np . linalg . norm ( ABC , ord = 'nuc' ) elif score_method == 'VAMP2' : res = np . linalg . norm ( ABC , ord = 'fro' ) ** 2 elif score_method == 'VAMPE' : Sk = np . diag ( self . singular_values [ 0 : self . dimension ( ) ] ) res = np . trace ( 2.0 * mdot ( Vk , Sk , Uk . T , test_model . C0t ) - mdot ( Vk , Sk , Uk . T , test_model . C00 , Uk , Sk , Vk . T , test_model . Ctt ) ) else : raise ValueError ( '"score" should be one of VAMP1, VAMP2 or VAMPE' ) assert res return res + 1 | Compute the VAMP score for this model or the cross - validation score between self and a second model . |
15,255 | def get_umbrella_sampling_data ( ntherm = 11 , us_fc = 20.0 , us_length = 500 , md_length = 1000 , nmd = 20 ) : dws = _DWS ( ) us_data = dws . us_sample ( ntherm = ntherm , us_fc = us_fc , us_length = us_length , md_length = md_length , nmd = nmd ) us_data . update ( centers = dws . centers ) return us_data | Continuous MCMC process in an asymmetric double well potential using umbrella sampling . |
15,256 | def get_multi_temperature_data ( kt0 = 1.0 , kt1 = 5.0 , length0 = 10000 , length1 = 10000 , n0 = 10 , n1 = 10 ) : dws = _DWS ( ) mt_data = dws . mt_sample ( kt0 = kt0 , kt1 = kt1 , length0 = length0 , length1 = length1 , n0 = n0 , n1 = n1 ) mt_data . update ( centers = dws . centers ) return mt_data | Continuous MCMC process in an asymmetric double well potential at multiple temperatures . |
15,257 | def get_scaled ( self , factor ) : res = TimeUnit ( self ) res . _factor = self . _factor * factor res . _unit = self . _unit return res | Get a new time unit scaled by the given factor |
15,258 | def rescale_around1 ( self , times ) : if self . _unit == self . _UNIT_STEP : return times , 'step' m = np . mean ( times ) mult = 1.0 cur_unit = self . _unit if ( m < 0.001 ) : while mult * m < 0.001 and cur_unit >= 0 : mult *= 1000 cur_unit -= 1 return mult * times , self . _unit_names [ cur_unit ] if ( m > 1000 ) : while mult * m > 1000 and cur_unit <= 5 : mult /= 1000 cur_unit += 1 return mult * times , self . _unit_names [ cur_unit ] return times , self . _unit | Suggests a rescaling factor and new physical time unit to balance the given time multiples around 1 . |
15,259 | def list_models ( filename ) : from . h5file import H5File with H5File ( filename , mode = 'r' ) as f : return f . models_descriptive | Lists all models in given filename . |
15,260 | def is_iterable_of_int ( l ) : r if not is_iterable ( l ) : return False return all ( is_int ( value ) for value in l ) | r Checks if l is iterable and contains only integral types |
15,261 | def is_iterable_of_float ( l ) : r if not is_iterable ( l ) : return False return all ( is_float ( value ) for value in l ) | r Checks if l is iterable and contains only floating point types |
15,262 | def is_int_vector ( l ) : r if isinstance ( l , np . ndarray ) : if l . ndim == 1 and ( l . dtype . kind == 'i' or l . dtype . kind == 'u' ) : return True return False | r Checks if l is a numpy array of integers |
15,263 | def is_bool_matrix ( l ) : r if isinstance ( l , np . ndarray ) : if l . ndim == 2 and ( l . dtype == bool ) : return True return False | r Checks if l is a 2D numpy array of bools |
15,264 | def is_float_array ( l ) : r if isinstance ( l , np . ndarray ) : if l . dtype . kind == 'f' : return True return False | r Checks if l is a numpy array of floats ( any dimension |
15,265 | def ensure_int_vector ( I , require_order = False ) : if is_int_vector ( I ) : return I elif is_int ( I ) : return np . array ( [ I ] ) elif is_list_of_int ( I ) : return np . array ( I ) elif is_tuple_of_int ( I ) : return np . array ( I ) elif isinstance ( I , set ) : if require_order : raise TypeError ( 'Argument is an unordered set, but I require an ordered array of integers' ) else : lI = list ( I ) if is_list_of_int ( lI ) : return np . array ( lI ) else : raise TypeError ( 'Argument is not of a type that is convertible to an array of integers.' ) | Checks if the argument can be converted to an array of ints and does that . |
15,266 | def ensure_float_vector ( F , require_order = False ) : if is_float_vector ( F ) : return F elif is_float ( F ) : return np . array ( [ F ] ) elif is_iterable_of_float ( F ) : return np . array ( F ) elif isinstance ( F , set ) : if require_order : raise TypeError ( 'Argument is an unordered set, but I require an ordered array of floats' ) else : lF = list ( F ) if is_list_of_float ( lF ) : return np . array ( lF ) else : raise TypeError ( 'Argument is not of a type that is convertible to an array of floats.' ) | Ensures that F is a numpy array of floats |
15,267 | def ensure_dtype_float ( x , default = np . float64 ) : r if isinstance ( x , np . ndarray ) : if x . dtype . kind == 'f' : return x elif x . dtype . kind == 'i' : return x . astype ( default ) else : raise TypeError ( 'x is of type ' + str ( x . dtype ) + ' that cannot be converted to float' ) else : raise TypeError ( 'x is not an array' ) | r Makes sure that x is type of float |
15,268 | def ensure_ndarray ( A , shape = None , uniform = None , ndim = None , size = None , dtype = None , kind = None ) : r if not isinstance ( A , np . ndarray ) : try : A = np . array ( A ) except : raise AssertionError ( 'Given argument cannot be converted to an ndarray:\n' + str ( A ) ) assert_array ( A , shape = shape , uniform = uniform , ndim = ndim , size = size , dtype = dtype , kind = kind ) return A | r Ensures A is an ndarray and does an assert_array with the given parameters |
15,269 | def ensure_ndarray_or_sparse ( A , shape = None , uniform = None , ndim = None , size = None , dtype = None , kind = None ) : r if not isinstance ( A , np . ndarray ) and not scisp . issparse ( A ) : try : A = np . array ( A ) except : raise AssertionError ( 'Given argument cannot be converted to an ndarray:\n' + str ( A ) ) assert_array ( A , shape = shape , uniform = uniform , ndim = ndim , size = size , dtype = dtype , kind = kind ) return A | r Ensures A is an ndarray or a scipy sparse matrix and does an assert_array with the given parameters |
15,270 | def ensure_ndarray_or_None ( A , shape = None , uniform = None , ndim = None , size = None , dtype = None , kind = None ) : r if A is not None : return ensure_ndarray ( A , shape = shape , uniform = uniform , ndim = ndim , size = size , dtype = dtype , kind = kind ) else : return None | r Ensures A is None or an ndarray and does an assert_array with the given parameters |
15,271 | def _describe_atom ( topology , index ) : at = topology . atom ( index ) if topology . n_chains > 1 : return "%s %i %s %i %i" % ( at . residue . name , at . residue . resSeq , at . name , at . index , at . residue . chain . index ) else : return "%s %i %s %i" % ( at . residue . name , at . residue . resSeq , at . name , at . index ) | Returns a string describing the given atom |
15,272 | def _first_and_last_element ( arr ) : if isinstance ( arr , np . ndarray ) or hasattr ( arr , 'data' ) : data = arr . data if sparse . issparse ( arr ) else arr return data . flat [ 0 ] , data . flat [ - 1 ] else : return arr [ 0 , 0 ] , arr [ - 1 , - 1 ] | Returns first and last element of numpy array or sparse matrix . |
15,273 | def running_covar ( xx = True , xy = False , yy = False , remove_mean = False , symmetrize = False , sparse_mode = 'auto' , modify_data = False , column_selection = None , diag_only = False , nsave = 5 ) : return RunningCovar ( compute_XX = xx , compute_XY = xy , compute_YY = yy , sparse_mode = sparse_mode , modify_data = modify_data , remove_mean = remove_mean , symmetrize = symmetrize , column_selection = column_selection , diag_only = diag_only , nsave = nsave ) | Returns a running covariance estimator |
15,274 | def _can_merge_tail ( self ) : if len ( self . storage ) < 2 : return False return self . storage [ - 2 ] . w <= self . storage [ - 1 ] . w * self . rtol | Checks if the two last list elements can be merged |
15,275 | def store ( self , moments ) : if len ( self . storage ) == self . nsave : self . storage [ - 1 ] . combine ( moments , mean_free = self . remove_mean ) else : self . storage . append ( moments ) while self . _can_merge_tail ( ) : M = self . storage . pop ( ) self . storage [ - 1 ] . combine ( M , mean_free = self . remove_mean ) | Store object X with weight w |
15,276 | def submodel ( self , states = None , obs = None ) : ref = super ( SampledHMSM , self ) . submodel ( states = states , obs = obs ) samples_sub = [ sample . submodel ( states = states , obs = obs ) for sample in self . samples ] return SampledHMSM ( samples_sub , ref = ref , conf = self . conf ) | Returns a HMM with restricted state space |
15,277 | def _generate_lags ( maxlag , multiplier ) : r lags = [ 1 ] lag = 1.0 import decimal while lag <= maxlag : lag = lag * multiplier lag = int ( decimal . Decimal ( lag ) . quantize ( decimal . Decimal ( '1' ) , rounding = decimal . ROUND_HALF_UP ) ) if lag <= maxlag : ilag = int ( lag ) lags . append ( ilag ) if maxlag not in lags : lags . append ( maxlag ) return np . array ( lags ) | r Generate a set of lag times starting from 1 to maxlag using the given multiplier between successive lags |
15,278 | def combinations ( seq , k ) : from itertools import combinations as _combinations , chain from scipy . special import comb count = comb ( len ( seq ) , k , exact = True ) res = np . fromiter ( chain . from_iterable ( _combinations ( seq , k ) ) , int , count = count * k ) return res . reshape ( - 1 , k ) | Return j length subsequences of elements from the input iterable . |
15,279 | def folding_model_energy ( rvec , rcut ) : r r = np . linalg . norm ( rvec ) - rcut rr = r ** 2 if r < 0.0 : return - 2.5 * rr return 0.5 * ( r - 2.0 ) * rr | r computes the potential energy at point rvec |
15,280 | def folding_model_gradient ( rvec , rcut ) : r rnorm = np . linalg . norm ( rvec ) if rnorm == 0.0 : return np . zeros ( rvec . shape ) r = rnorm - rcut if r < 0.0 : return - 5.0 * r * rvec / rnorm return ( 1.5 * r - 2.0 ) * rvec / rnorm | r computes the potential s gradient at point rvec |
15,281 | def get_asymmetric_double_well_data ( nstep , x0 = 0. , nskip = 1 , dt = 0.01 , kT = 10.0 , mass = 1.0 , damping = 1.0 ) : r adw = AsymmetricDoubleWell ( dt , kT , mass = mass , damping = damping ) return adw . sample ( x0 , nstep , nskip = nskip ) | r wrapper for the asymmetric double well generator |
15,282 | def get_folding_model_data ( nstep , rvec0 = np . zeros ( ( 5 ) ) , nskip = 1 , dt = 0.01 , kT = 10.0 , mass = 1.0 , damping = 1.0 , rcut = 3.0 ) : r fm = FoldingModel ( dt , kT , mass = mass , damping = damping , rcut = rcut ) return fm . sample ( rvec0 , nstep , nskip = nskip ) | r wrapper for the folding model generator |
15,283 | def get_prinz_pot ( nstep , x0 = 0. , nskip = 1 , dt = 0.01 , kT = 10.0 , mass = 1.0 , damping = 1.0 ) : r pw = PrinzModel ( dt , kT , mass = mass , damping = damping ) return pw . sample ( x0 , nstep , nskip = nskip ) | r wrapper for the Prinz model generator |
15,284 | def step ( self , x ) : r return x - self . coeff_A * self . gradient ( x ) + self . coeff_B * np . random . normal ( size = self . dim ) | r perform a single Brownian dynamics step |
15,285 | def plot_markov_model ( P , pos = None , state_sizes = None , state_scale = 1.0 , state_colors = '#ff5500' , state_labels = 'auto' , minflux = 1e-6 , arrow_scale = 1.0 , arrow_curvature = 1.0 , arrow_labels = 'weights' , arrow_label_format = '%2.e' , max_width = 12 , max_height = 12 , figpadding = 0.2 , show_frame = False , ax = None , ** textkwargs ) : r from msmtools import analysis as msmana if isinstance ( P , _np . ndarray ) : P = P . copy ( ) else : P = P . transition_matrix . copy ( ) if state_sizes is None : state_sizes = msmana . stationary_distribution ( P ) if minflux > 0 : F = _np . dot ( _np . diag ( msmana . stationary_distribution ( P ) ) , P ) I , J = _np . where ( F < minflux ) P [ I , J ] = 0.0 plot = NetworkPlot ( P , pos = pos , ax = ax ) fig = plot . plot_network ( state_sizes = state_sizes , state_scale = state_scale , state_colors = state_colors , state_labels = state_labels , arrow_scale = arrow_scale , arrow_curvature = arrow_curvature , arrow_labels = arrow_labels , arrow_label_format = arrow_label_format , max_width = max_width , max_height = max_height , figpadding = figpadding , xticks = False , yticks = False , show_frame = show_frame , ** textkwargs ) return fig , plot . pos | r Network representation of MSM transition matrix |
15,286 | def plot_flux ( flux , pos = None , state_sizes = None , flux_scale = 1.0 , state_scale = 1.0 , state_colors = '#ff5500' , state_labels = 'auto' , minflux = 1e-9 , arrow_scale = 1.0 , arrow_curvature = 1.0 , arrow_labels = 'weights' , arrow_label_format = '%2.e' , max_width = 12 , max_height = 12 , figpadding = 0.2 , attribute_to_plot = 'net_flux' , show_frame = False , show_committor = True , ax = None , ** textkwargs ) : r from matplotlib import pylab as plt F = flux_scale * getattr ( flux , attribute_to_plot ) c = flux . committor if state_sizes is None : state_sizes = flux . stationary_distribution plot = NetworkPlot ( F , pos = pos , xpos = c , ax = ax ) if minflux > 0 : I , J = _np . where ( F < minflux ) F [ I , J ] = 0.0 if isinstance ( state_labels , str ) and state_labels == 'auto' : state_labels = _np . array ( [ str ( i ) for i in range ( flux . nstates ) ] ) state_labels [ _np . array ( flux . A ) ] = "A" state_labels [ _np . array ( flux . B ) ] = "B" elif isinstance ( state_labels , ( _np . ndarray , list , tuple ) ) : if len ( state_labels ) != flux . nstates : raise ValueError ( "length of state_labels({}) has to match length of states({})." . format ( len ( state_labels ) , flux . nstates ) ) fig = plot . plot_network ( state_sizes = state_sizes , state_scale = state_scale , state_colors = state_colors , state_labels = state_labels , arrow_scale = arrow_scale , arrow_curvature = arrow_curvature , arrow_labels = arrow_labels , arrow_label_format = arrow_label_format , max_width = max_width , max_height = max_height , figpadding = figpadding , xticks = show_committor , yticks = False , show_frame = show_frame , ** textkwargs ) if show_committor : plt . xlabel ( 'Committor probability' ) return fig , plot . pos | r Network representation of reactive flux |
15,287 | def plot_network ( weights , pos = None , xpos = None , ypos = None , state_sizes = None , state_scale = 1.0 , state_colors = '#ff5500' , state_labels = 'auto' , arrow_scale = 1.0 , arrow_curvature = 1.0 , arrow_labels = 'weights' , arrow_label_format = '%2.e' , max_width = 12 , max_height = 12 , figpadding = 0.2 , attribute_to_plot = 'net_flux' , show_frame = False , xticks = False , yticks = False , ax = None , ** textkwargs ) : r plot = NetworkPlot ( weights , pos = pos , xpos = xpos , ypos = ypos , ax = ax ) fig = plot . plot_network ( state_sizes = state_sizes , state_scale = state_scale , state_colors = state_colors , state_labels = state_labels , arrow_scale = arrow_scale , arrow_curvature = arrow_curvature , arrow_labels = arrow_labels , arrow_label_format = arrow_label_format , max_width = max_width , max_height = max_height , figpadding = figpadding , xticks = xticks , yticks = yticks , show_frame = show_frame , ** textkwargs ) return fig , plot . pos | r Network representation of given matrix |
15,288 | def compute_csets_TRAM ( connectivity , state_counts , count_matrices , equilibrium_state_counts = None , ttrajs = None , dtrajs = None , bias_trajs = None , nn = None , factor = 1.0 , callback = None ) : r return _compute_csets ( connectivity , state_counts , count_matrices , ttrajs , dtrajs , bias_trajs , nn = nn , equilibrium_state_counts = equilibrium_state_counts , factor = factor , callback = callback ) | r Computes the largest connected sets in the produce space of Markov state and thermodynamic states for TRAM data . |
15,289 | def compute_csets_dTRAM ( connectivity , count_matrices , nn = None , callback = None ) : r if connectivity == 'post_hoc_RE' or connectivity == 'BAR_variance' : raise Exception ( 'Connectivity type %s not supported for dTRAM data.' % connectivity ) state_counts = _np . maximum ( count_matrices . sum ( axis = 1 ) , count_matrices . sum ( axis = 2 ) ) return _compute_csets ( connectivity , state_counts , count_matrices , None , None , None , nn = nn , callback = callback ) | r Computes the largest connected sets for dTRAM data . |
15,290 | def _indexes ( arr ) : myarr = np . array ( arr ) if myarr . ndim == 1 : return list ( range ( len ( myarr ) ) ) elif myarr . ndim == 2 : return tuple ( itertools . product ( list ( range ( arr . shape [ 0 ] ) ) , list ( range ( arr . shape [ 1 ] ) ) ) ) else : raise NotImplementedError ( 'Only supporting arrays of dimension 1 and 2 as yet.' ) | Returns the list of all indexes of the given array . |
15,291 | def _column ( arr , indexes ) : if arr . ndim == 2 and types . is_int ( indexes ) : return arr [ : , indexes ] elif arr . ndim == 3 and len ( indexes ) == 2 : return arr [ : , indexes [ 0 ] , indexes [ 1 ] ] else : raise NotImplementedError ( 'Only supporting arrays of dimension 2 and 3 as yet.' ) | Returns a column with given indexes from a deep array |
15,292 | def statistical_inefficiency ( X , truncate_acf = True ) : assert np . ndim ( X [ 0 ] ) == 1 , 'Data must be 1-dimensional' N = _maxlength ( X ) xflat = np . concatenate ( X ) Xmean = np . mean ( xflat ) X0 = [ x - Xmean for x in X ] x2m = np . mean ( xflat ** 2 ) corrsum = 0.0 for lag in range ( N ) : acf = 0.0 n = 0.0 for x in X0 : Nx = len ( x ) if ( Nx > lag ) : acf += np . sum ( x [ 0 : Nx - lag ] * x [ lag : Nx ] ) n += float ( Nx - lag ) acf /= n if acf <= 0 and truncate_acf : break elif lag > 0 : corrsum += acf * ( 1.0 - ( float ( lag ) / float ( N ) ) ) corrtime = 0.5 + corrsum / x2m return 1.0 / ( 2 * corrtime ) | Estimates the statistical inefficiency from univariate time series X |
15,293 | def _database_from_key ( self , key ) : if not self . filename : return None from pyemma . util . files import mkdir_p hash_value_long = int ( key , 16 ) db_name = str ( hash_value_long ) [ - 1 ] + '.db' directory = os . path . dirname ( self . filename ) + os . path . sep + 'traj_info_usage' mkdir_p ( directory ) return os . path . join ( directory , db_name ) | gets the database name for the given key . Should ensure a uniform spread of keys over the databases in order to minimize waiting times . Since the database has to be locked for updates and multiple processes want to write each process has to wait until the lock has been released . |
15,294 | def _clean ( self , n ) : import sqlite3 num_delete = int ( self . num_entries / 100.0 * n ) logger . debug ( "removing %i entries from db" % num_delete ) lru_dbs = self . _database . execute ( "select hash, lru_db from traj_info" ) . fetchall ( ) lru_dbs . sort ( key = itemgetter ( 1 ) ) hashs_by_db = { } age_by_hash = [ ] for k , v in itertools . groupby ( lru_dbs , key = itemgetter ( 1 ) ) : hashs_by_db [ k ] = list ( x [ 0 ] for x in v ) len_by_db = { os . path . basename ( db ) : len ( hashs_by_db [ db ] ) for db in hashs_by_db . keys ( ) } logger . debug ( "distribution of lru: %s" , str ( len_by_db ) ) for db in hashs_by_db . keys ( ) : with sqlite3 . connect ( db , timeout = self . lru_timeout ) as conn : rows = conn . execute ( "select hash, last_read from usage" ) . fetchall ( ) for r in rows : age_by_hash . append ( ( r [ 0 ] , float ( r [ 1 ] ) , db ) ) age_by_hash . sort ( key = itemgetter ( 1 ) ) if len ( age_by_hash ) >= 2 : assert [ age_by_hash [ - 1 ] > age_by_hash [ - 2 ] ] ids = map ( itemgetter ( 0 ) , age_by_hash [ : num_delete ] ) ids = tuple ( map ( str , ids ) ) sql_compatible_ids = SqliteDB . _format_tuple_for_sql ( ids ) with self . _database as c : c . execute ( "DELETE FROM traj_info WHERE hash in (%s)" % sql_compatible_ids ) age_by_hash . sort ( key = itemgetter ( 2 ) ) for db , values in itertools . groupby ( age_by_hash , key = itemgetter ( 2 ) ) : values = tuple ( v [ 0 ] for v in values ) with sqlite3 . connect ( db , timeout = self . lru_timeout ) as conn : stmnt = "DELETE FROM usage WHERE hash IN (%s)" % SqliteDB . _format_tuple_for_sql ( values ) curr = conn . execute ( stmnt ) assert curr . rowcount == len ( values ) , curr . rowcount | obtain n% oldest entries by looking into the usage databases . Then these entries are deleted first from the traj_info db and afterwards from the associated LRU dbs . |
15,295 | def log_likelihood ( self ) : r return _tram . log_likelihood_lower_bound ( self . log_lagrangian_mult , self . biased_conf_energies , self . count_matrices , self . btrajs , self . dtrajs , self . state_counts , None , None , None , None , None ) | r Returns the value of the log - likelihood of the converged TRAM estimate . |
15,296 | def histogram ( transform , dimensions , nbins ) : maximum = np . ones ( len ( dimensions ) ) * ( - np . inf ) minimum = np . ones ( len ( dimensions ) ) * np . inf for _ , chunk in transform : maximum = np . max ( np . vstack ( ( maximum , np . max ( chunk [ : , dimensions ] , axis = 0 ) ) ) , axis = 0 ) minimum = np . min ( np . vstack ( ( minimum , np . min ( chunk [ : , dimensions ] , axis = 0 ) ) ) , axis = 0 ) bins = [ np . linspace ( m , M , num = n ) for m , M , n in zip ( minimum , maximum , nbins ) ] res = np . zeros ( np . array ( nbins ) - 1 ) for _ , chunk in transform : part , _ = np . histogramdd ( chunk [ : , dimensions ] , bins = bins ) res += part return res , bins | Computes the N - dimensional histogram of the transformed data . |
15,297 | def load ( self , filename = None ) : if not filename : filename = self . default_config_file files = self . _cfgs_to_read ( ) files . insert ( - 1 , filename ) try : config = self . __read_cfg ( files ) except ReadConfigException as e : print ( Config . _format_msg ( 'config.load("{file}") failed with {error}' . format ( file = filename , error = e ) ) ) else : self . _conf_values = config if self . show_config_notification and not self . cfg_dir : print ( Config . _format_msg ( "no configuration directory set or usable." " Falling back to defaults." ) ) | load runtime configuration from given filename . If filename is None try to read from default file from default location . |
15,298 | def save ( self , filename = None ) : if not filename : filename = self . DEFAULT_CONFIG_FILE_NAME else : filename = str ( filename ) head , tail = os . path . split ( filename ) if head : self . _cfg_dir = head base , ext = os . path . splitext ( tail ) if ext != ".cfg" : filename += ".cfg" if not self . cfg_dir or not os . path . isdir ( self . cfg_dir ) or not os . stat ( self . cfg_dir ) != os . W_OK : try : self . cfg_dir = self . DEFAULT_CONFIG_DIR except ConfigDirectoryException as cde : print ( Config . _format_msg ( 'Could not create configuration directory "{dir}"! config.save() failed.' ' Please set a writeable location with config.cfg_dir = val. Error was {exc}' . format ( dir = self . cfg_dir , exc = cde ) ) ) return filename = os . path . join ( self . cfg_dir , filename ) try : with open ( filename , 'w' ) as fh : self . _conf_values . write ( fh ) except IOError as ioe : print ( Config . _format_msg ( "Save failed with error %s" % ioe ) ) | Saves the runtime configuration to disk . |
15,299 | def default_config_file ( self ) : import os . path as p import pyemma return p . join ( pyemma . __path__ [ 0 ] , Config . DEFAULT_CONFIG_FILE_NAME ) | default config file living in PyEMMA package |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.