当前位置: 首页>>代码示例>>Python>>正文


Python MSMLib.invert_assignments方法代码示例

本文整理汇总了Python中msmbuilder.MSMLib.invert_assignments方法的典型用法代码示例。如果您正苦于以下问题:Python MSMLib.invert_assignments方法的具体用法?Python MSMLib.invert_assignments怎么用?Python MSMLib.invert_assignments使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在msmbuilder.MSMLib的用法示例。


在下文中一共展示了MSMLib.invert_assignments方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: run

# 需要导入模块: from msmbuilder import MSMLib [as 别名]
# 或者: from msmbuilder.MSMLib import invert_assignments [as 别名]
def run(project, assignments, num_confs_per_state, random_source=None):
    """
    Pull random confs from each state in an MSM
    
    Parameters
    ----------
    project : msmbuilder.Project
        Used to load up the trajectories, get topology
    assignments : np.ndarray, dtype=int
        State membership for each frame
    num_confs_per_state : int
        number of conformations to pull from each state
    random_source : numpy.random.RandomState, optional
        If supplied, random numbers will be pulled from this random source,
        instead of the default, which is np.random. This argument is used
        for testing, to ensure that the random number generator always
        gives the same stream.
        
    Notes
    -----
    A new random_source can be initialized by calling numpy.random.RandomState(seed)
    with whatever seed you like. See http://stackoverflow.com/questions/5836335/consistenly-create-same-random-numpy-array
    for some discussion.
                
    """
    
    if random_source is None:
        random_source = np.random
    
    n_states = max(assignments.flatten()) + 1
    logger.info("Pulling %s confs for each of %s confs", num_confs_per_state, n_states)
    
    inv = MSMLib.invert_assignments(assignments)
    xyzlist = []
    for s in xrange(n_states):
        trj, frame = inv[s]
        # trj and frame are a list of indices, such that
        # project.load_traj(trj[i])[frame[i]] is a frame assigned to state s
        for j in xrange(num_confs_per_state):
            r = random_source.randint(len(trj))
            xyz = Trajectory.read_frame(project.traj_filename(trj[r]), frame[r])
            xyzlist.append(xyz)
            
    # xyzlist is now a list of (n_atoms, 3) arrays, and we're going
    # to stack it along the third dimension 
    xyzlist = np.dstack(xyzlist)
    # load up the conf to get the topology, put then pop in the new coordinates
    output = project.load_conf()
    output['XYZList'] = xyzlist
    
    return output
开发者ID:jimsnyderjr,项目名称:msmbuilder,代码行数:53,代码来源:GetRandomConfs.py

示例2: run

# 需要导入模块: from msmbuilder import MSMLib [as 别名]
# 或者: from msmbuilder.MSMLib import invert_assignments [as 别名]
def run(project, assignments, states, n_per_state, random=None, replacement=True):
    """Extract random conformations from states

    Parameters
    ----------
    project : msmbuilder.project
    assignments : np.ndarray, shape=[n_trajs, n_confs], dtype=int
    states : array_like
        The indices of the states to pull from
    n_per_state : int
        Number of conformations to extract per state
    random : np.random.RandomState, optional
        Source of randomness

    Returns
    -------
    confs : [msmbuilder.Trajectory]
        List of trajectories, each of length n_per_state. confs[i][j] is
        the `j`th conformation sampled from state `states[i]`.
    """

    if random is None:
        random = np.random

    results = []
    # get a mapping from microstate -> trj/frame
    inv = MSMLib.invert_assignments(assignments)
    for s in states:
        trajs, frames = inv[s]
        if len(trajs) != len(frames):
            raise RuntimeError('inverse assignments corrupted?')

        if replacement:
            if len(trajs) < n_per_state:
                logger.error("Asked for %d confs per state, but state %d only has %d" % (n_per_state, s, len(trajs)))
            # indices of the confs to select
            r = random.randint(len(trajs), size=n_per_state)
        else:
            if len(trajs) < n_per_state:
                raise ValueError("Asked for %d confs per state, but state %d only has %d" % (n_per_state, s, len(trajs)))
            # draw n_per_state random numbers between `0` and `len(trajs)` without replacement
            r = random.permutation(len(trajs))[:n_per_state]


        results.append(project.load_frame(trajs[r], frames[r]))

    return results
开发者ID:chrismichel,项目名称:msmbuilder,代码行数:49,代码来源:SaveStructures.py

示例3: run_round

# 需要导入模块: from msmbuilder import MSMLib [as 别名]
# 或者: from msmbuilder.MSMLib import invert_assignments [as 别名]
def run_round(checkdata=True):
    """Activate the builder and build new MSMs (if necessary)
    
    First, check to see if there is enough data are to warrant building a
    new set of MSMs. Assuming yes, do a joint clustering over all of the
    data, and then build MSMs for each forcefield on that state space.
    
    Parameters
    ----------
    checkdata : boolean, optional
         If False, skip the checking process
    
    Returns
    -------
    happened : boolean
        True if we actually did a round of MSM building, False otherwise
    """
        
    if checkdata:
        logger.info("Checking if sufficient data has been acquired.")
        if not is_sufficient_new_data():
            return False
    else:
        logger.info("Skipping check for adequate data.")
        
    # use all the data together to get the cluster centers
    generators, db_trajs = joint_clustering()
        
    msmgroup = MSMGroup(trajectories=db_trajs)
    for ff in Session.query(Forcefield).all():
        trajs = filter(lambda t: t.forcefield == ff, db_trajs)
        msm = build_msm(ff, generators=generators, trajs=trajs)
        msmgroup.markov_models.append(msm)
        
    # add generators to msmgroup
    Session.add(msmgroup)
    Session.flush()
    msmgroup.populate_default_filenames()
        
    msmgroup.trajectories = db_trajs
    msmgroup.n_states = len(generators)
    save_file(msmgroup.generators_fn, generators)

        
    for msm in msmgroup.markov_models:
        msm.populate_default_filenames()
        if hasattr(msm, 'counts'):
            save_file(msm.counts_fn, msm.counts)
        if hasattr(msm, 'assignments'):
            save_file(msm.assignments_fn, msm.assignments)
        if hasattr(msm, 'distances'):
            save_file(msm.distances_fn, msm.distances)
            save_file(msm.inverse_assignments_fn, dict(MSMLib.invert_assignments(msm.assignments)))
        

    # ======================================================================#
    # HERE IS WHERE THE ADAPTIVE SAMPLING ALGORITHMS GET CALLED
    # The obligation of the adaptive_sampling routine is to set the
    # model_selection_weight on each MSM/forcefield and the microstate
    # selection weights
    # check to make sure that the right fields were populated
    try:
        Project().adaptive_sampling(Session, msmgroup)
        
        for msm in msmgroup.markov_models:
            if not isinstance(msm.model_selection_weight, numbers.Number):
                raise ValueError('model selection weight on %s not set correctly' % msm)
            if not isinstance(msm.microstate_selection_weights, np.ndarray):
                raise ValueError('microstate_selection_weights on %s not set correctly' % msm)
    except Exception as e:
        logging.error('ADAPTIVE SAMPLING ERROR')
        logging.error(e)
        sampling.default(Session, msmgroup)
        
    #=======================================================================#

        
    Session.flush()       
    logger.info("Round completed sucessfully")
    return True
开发者ID:rmcgibbo,项目名称:msmaccelerator,代码行数:82,代码来源:Builder.py

示例4: get_random_confs_from_states

# 需要导入模块: from msmbuilder import MSMLib [as 别名]
# 或者: from msmbuilder.MSMLib import invert_assignments [as 别名]
    def get_random_confs_from_states(self, assignments, states, num_confs, 
        replacement=True, random=np.random):
        """
        Get random conformations from a particular state (or states) in assignments.

        Parameters
        ----------
        assignments : np.ndarray
            2D array storing the assignments for a particular MSM
        states : int or 1d array_like
            state index (or indices) to load random conformations from
        num_confs : int or 1d array_like
            number of conformations to get from state. The shape should 
            be the same as the states argument
        replacement : bool, optional
            whether to sample with replacement or not (default: True)
        random : np.random.RandomState, optional
            use a particular RandomState for generating the random samples.
            this is only useful if you want to get the same samples, i.e.
            when debugging something.

        Returns
        -------
        random_confs : msmbuilder.Trajectory or list of
                       msmbuilder.Trajectory objects
            If states is a list, then the output is a list, otherwise a 
            single trajectory is returned
            Trajectory object containing random conformations from the 
            specified state
        """

        def randomize(state_counts, size=1, replacement=True, random=np.random):
            """
            This is a helper function for selecting random conformations. It will
            select many samples from a discrete, uniform distribution over:
            
            .. math::  \{i\}_{i=1}^{\textnormal{state_counts}}

            If replacement==True, then random.randint will be used, otherwise
            random.permutation will be used.

            Parameters
            ----------
            state_counts : int
                number of conformations in the state
            size : int, optional
                number of samples to draw (size kwarg in np.random.randint)
                default: 1
            replacement : bool, optional
                if True, then we sample with replacement, otherwise we use a 
                permutation
            random : np.random.RandomState, optional
                if you want this to behave deterministically then pass a particular
                random state, otherwise we will use np.random.

            Returns
            -------
            result : np.ndarray
                1d array with samples from the given distribution

            Raises
            ------
            ValueError: if size > state_counts and replacement is False, then
                it is not possible to sample that many conformations without 
                replacement
            """
            if replacement:
                result = random.randint(0, state_counts, size=size)
            else:
                if size > state_counts:
                    raise ValueError("Asked for %d conformations from a state "
                                     "with only %d conformations." % (size, state_counts))
                else:
                    result = random.permutation(np.arange(state_counts))[:size]

            return result
            

        if isinstance(states, int):
            states = np.array([states])
        states = np.array(states).flatten()

        # if num_confs is just a number, map it to
        # each state given in states
        if isinstance(num_confs, int):
            num_confs = np.array([num_confs] * len(states)) 
        num_confs = np.array(num_confs).flatten()

        # if num_confs is length-1, then map that value to each
        # state in states
        if len(num_confs) == 1:
            num_confs = np.array(list(num_confs) * len(states))

        if len(num_confs) != len(states):
            raise Exception("num_confs must be the same size as num_states")

        inv_assignments = MSMLib.invert_assignments(assignments)
        state_counts = np.bincount(assignments[np.where(assignments!=-1)])

        random_confs = []
#.........这里部分代码省略.........
开发者ID:raviramanathan,项目名称:msmbuilder,代码行数:103,代码来源:project.py


注:本文中的msmbuilder.MSMLib.invert_assignments方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。