Hi, I have couple of questions for you, which could be very silly.

I downloaded the movie.py from http://www.rubor.de/, which is rTools 0.7.2  and 
put it to the right directory. When I did run movie.py, nothing seemed wrong. 
And then I did mv_clear, and still good. But when I do like : mv_move 1-10, x, 
80, linear, it showed
             ^
 SyntaxError: invalid syntax

  File "/Applications/pymolx11hybrid.app/pymol/modules/pymol/parser.py", line 
464, in parse
  File "<string>", line 1, in <module>
NameError: name 'x' is not defined


And then I did the same thing to 11hybrid, instead of macpymol. Every commands 
I put in, it did not show any mistake, but the problem is the action is not 
performed. I do not really know how to look at the .py file. Attached is the 
movie.py I downloaded, could you please take a look, and tell me what is the 
right way for me to get the command I need. Thank you very much.

Jingzhen
"""
--- movie: easy movie scripting in PyMOL ---
Script  : movie
Author  : The PyMOL community 
Date    : Oct 2004
Version : 0.7
Contact : kristia...@gmx.de

Copyright (C) 2004 Kristian Rother, Laurence Pearl, Seth Harris,
Morri Feldmann, Tserk Wassenaar and Lieven Buts

Movie is an extension for the PyMOL Molecular Graphics System.

Movie for PyMOL facilitates creation of high-quality animations. Translation, rotation
and other commands can be assigned to frame ranges, resulting in a much shorter scripting
of animations. Additionaly, smooth movements are enabled.

It is assumed that you have already gathered experience with the standard PyMOL animation
commands, or are at least familiar with the 'frame' and 'state' concepts. Most movie
commands will require a frame/state range assigned to a specific action. Thus, you
dont have to worry about how to use the mset command correctly. Just say what you
want to see.

Frames can be specified to cover individual frames, states or ranges of both. The frame
ranges of several commands may very well overlap (but not the states).
The 'mode' parameter of several commands takes the values 'linear' and 'trigon'

Examples for frames/states:
    10         # frame 10 only
    20-199     # frame 20 to 199
    1-100:5    # state 5 only
    1-100:1-10 # multiple states are looped through

"""

from pymol import cmd
import string,os,re
from math import *
import math
from math import sqrt,acos,sin
from copy import deepcopy

class Movie:    
    def __init__(self):
        """Stores data of what should appear in the movie."""
        self.movie=[]
        self.maxframe = 1
        self.framestates = {}
        self.png_prefix=""
        self.views={}
        self.ray=0

    def add(self,framestate,command):
        self.movie.append((framestate[0],framestate[1],command))
            

    def add_frame_states(self, framestates):
        """Stores list of (frame,state) tuples in a dictionary."""
        for fs in framestates:
            self.framestates[str(fs[0])] = fs[1]

    def get_state(self,frame):
        key = str(frame)
        if self.framestates.has_key(key):
            return self.framestates[key]
        else:
            return 1 # state one, if none specified            

    def store_view(self,viewname):
        """
        Store the current view in a dictionary in the object under
        the given hashcode.
        """
        # adapted from MasterMovie.py
        view=cmd.get_view()
        self.views[viewname] = view
        
    def load_view(self,viewname):
        if self.views.has_key(viewname):
            cmd.set_view(self.views[viewname])
    

moviedata = Movie()
#
# all movie commands
#
# define a set of new PyMOL commands for creation of movies
# this part will be executed first upon the
# 'run movie.py' command from within PyMOL.
def __init__(self):
    cmd.extend('movie',movie)
    cmd.extend('mv_clear',mv_clear) # clear cached instructions
    cmd.extend('mv_rot',mv_rotate)     # rotate over frame range
    cmd.extend('mv_move',mv_move)   # move over frame range
    cmd.extend('mv_trans',mv_trans)   # translate over frame range
    cmd.extend('mv_turn',mv_turn)   # turn over frame range
    cmd.extend('mv_cmd',mv_cmd)     # do anything during a frame range
    cmd.extend('mv_set',mv_set)     # adjust parameter over frame range
    cmd.extend('mv_sinrot',mv_sinrotate)   # rotate smoothly
    cmd.extend('mv_sinmove',mv_sinmove) # move smoothly
    cmd.extend('mv_sintrans',mv_sintrans) # move smoothly
    cmd.extend('mv_sinturn',mv_sinturn) # turn smoothly 
    cmd.extend('mv_sinset',mv_sinset)   # set smoothly

    # Tserk's additions
    cmd.extend('mv_gradcol',mv_gradcol)
    cmd.extend('mv_bg',mv_bg)
    cmd.extend('mv_sinbg',mv_sinbg)
    cmd.extend('mv_del',mv_del)
    cmd.extend('mv_morph',mv_morph)
    
    # MasterMovie additions
    cmd.extend('store_view',store_view)
    cmd.extend('load_view',load_view)
    cmd.extend('mv_viewtravel',mv_viewtravel)
    cmd.extend('ribbon_ride',ribbon_ride)
    cmd.extend('peak_tour',tour)

    # downward compatibility section
    cmd.extend('mvClear',mv_clear) # clear cached instructions
    cmd.extend('mvRot',mv_rotate)     # rotate over frame range
    cmd.extend('mvMove',mv_move)   # move over frame range
    cmd.extend('mvTurn',mv_turn)   # turn over frame range
    cmd.extend('mvCmd',mv_cmd)     # do anything during a frame range
    cmd.extend('mvSet',mv_set)     # adjust parameter over frame range
    cmd.extend('mvSinrot',mv_sinrotate)   # rotate smoothly
    cmd.extend('mvSinmove',mv_sinmove) # move smoothly
    cmd.extend('mvSinturn',mv_sinturn) # turn smoothly 
    cmd.extend('mvSinset',mv_sinset)   # set smoothly
    cmd.extend('mvGradCol',mv_gradcol)
    cmd.extend('mvBG',mv_bg)
    cmd.extend('mvSinBG',mv_sinbg)
    cmd.extend('mvDel',mv_del)
    cmd.extend('mvMorph',mv_morph)
    cmd.extend('mvViewTravel',mv_viewtravel)
    cmd.extend('pngseq',pngseq)
    
# ---------------------------------------------------------
# internal stuff

def get_linear_values(number,start=0.0,end=1.0):
    """
    Returns a list of 'number' float values, where the first
    value is 'start', the last one is 'end' and the others
    are linearly in between them.
    """
    if number==1: return [end]
    values = []
    i = 0.0
    while i<=number:
        values.append( start + (end-start)*i/(number) )
        i+=1
    return values
        
def get_trigon_values(number,start=0.0,end=1.0):
    """
    Returns a list of 'number' float values, where the first
    value is 'start', the last one is 'end' and the others
    are calculated using a trigonometric function.
    """
    if number==1: return [end]
    values = []
    arcIncrement=pi/(number-1)
    
    prev=1.0
    sum=0.0
    i = 0.0
    while i < number:
        arc=cos(i*arcIncrement)
        sum += (end-start)*abs(arc-prev)*0.5
        values.append(start+sum)
        prev=arc
        i += 1
        
    return values

def get_values(number,start,end,mode):
    if mode == 'linear': values = get_linear_values(number,start,end)
    elif mode == 'trigon': values = get_trigon_values(number,start,end)
    else:
        print 'movie.py: INVALID MODE %s'%mode
        return []
    
    return values
    
def get_increment_values(number,start=0.0,end=1.0,mode='linear'):
    """
    Returns a list of float numbers that are either linear or
    trigonometric increments that sum up to the difference between
    start and end.
    """
    if mode =='linear':
        incr = []
        increment = (end-start)/number
        incr = [increment] * number
        return incr
    else: 
        values = get_values(number+1,start,end,mode)    
        incr = []
        act = values[0]
        for v in values[1:]:
            incr.append(v - act)
            act = v
        return incr

def get_frame_states(fstring):
    """Returns a list of (frame,state) tuples parsed from a string like
    1-10       # frame 1 to 10, state 1
    10         # frame 10 only
    1-100:1-10 # multiple states are looped through
    1-100:5    # one state only
    1-50:10-5  # reverse order is ok, too
    1:8        # state no.8 in frame no.1
    1:1-10     # this is crap, don't know what happens
    """

    t=string.split(fstring,":")
    frames=t[0] # the first token is frame range
    if len(t)==2: states = t[1] # the second token is state range
    else: states='1' # only state number 1 is used

    # parse frame substring
    t=string.split(frames,"-")
    firstFrame=int(t[0]) # first token is starting frame
    if len(t)==2: lastFrame=int(t[1]) # second token is end frame
    else: lastFrame = firstFrame # only one frame is used
    
    # parse state substring
    t=string.split(states,"-")
    firstState=int(t[0]) # first token is starting state
    if len(t)==2: lastState=int(t[1]) # second token is end state
    else: lastState = firstState # only one state is used

    # compile list of frames/states
    framestates = []
    if lastFrame == firstFrame or lastFrame < firstFrame:
        framestates.append((firstFrame,firstState))
        lastFrame = firstFrame
    else:
        nframes = lastFrame - firstFrame +1 
        stateinc = (lastState - firstState +1) * 1.0 / nframes
        for i in range(nframes):
            frame = firstFrame + i 
            state = firstState + int(stateinc * i)
            framestates.append((frame,state))

    # put values into mv for compiling the movie later
    if moviedata.maxframe < lastFrame: moviedata.maxframe = lastFrame
    moviedata.add_frame_states(framestates)

    return framestates

#
#
# Commands revised 
#
#
def mv_clear():
    """Deletes the movie."""
    moviedata.movie=[]
    cmd.mset("1")
    cmd.mclear()
    cmd.frame(1)
    moviedata.ray=0
    moviedata.png_prefix=""
    moviedata.maxframe = 1

def pngseq(prefix,ray="0"):
    """Sets a path for creating a PNG sequence while playing the movie.
    Ray lets raytrace each frame.
    """    
    moviedata.png_prefix=prefix
    moviedata.ray=int(ray)

def mv_cmd(frames="1",command=""):
    """
    mv_cmd(frames,command) - executes a command in all frames specified.
       """    
    framestates = get_frame_states(frames)
    for fs in framestates:
        moviedata.add(fs,command)


def mv_turn(frames="1",axis="z",angle='360',mode='linear'):
    """
    mv_turn(frames,axis,angle,selection,mode) - turns the camera over the given
       frame range, the rotation angle summing up to the angle given.
       """    
    framestates = get_frame_states(frames)
    nFrames = len(framestates)
    angleIncrement = get_increment_values(nFrames,0.0,float(angle),mode)

    for i in range(nFrames): 
        moviedata.add(framestates[i],"turn %s,%f"%(axis,angleIncrement[i]))


def mv_rotate(frames="1",axis="z",angle='360',selection='all',mode='linear'):
    """
    mv_rotate(frames,axis,angle,selection,mode) - rotates the object over the given
       frame range, the rotation angle summing up to the angle given.
       """    
    framestates = get_frame_states(frames)
    nFrames = len(framestates)
    angleIncrement = get_increment_values(nFrames,0.0,float(angle),mode)

    for i in range(nFrames): 
        moviedata.add(framestates[i],"rotate %s,%f,%s"%(axis,angleIncrement[i],selection))


def mv_move(frames="1",axis="x",distance="0",mode='linear'):
    """
    mv_move(frames,axis,distance,selection,mode) - moves the environment over the given
       frame range, the moved distance summing up to the distance given.
       """    
    framestates = get_frame_states(frames)
    nFrames = len(framestates)
    distanceIncrement = get_increment_values(nFrames,0.0,float(distance),mode)

    for i in range(nFrames):
        moviedata.add(framestates[i],"move %s,%f"%(axis,distanceIncrement[i]))
        
def mv_trans(frames="1",axis="x",distance="0",selection='all',mode='linear'):
    """
    mv_move(frames,axis,distance,selection,mode) - moves the selection object over the given
       frame range, the moved distance summing up to the distance given.
       """    
    framestates = get_frame_states(frames)
    nFrames = len(framestates)
    distanceIncrement = get_increment_values(nFrames,0.0,float(distance),mode)
    
    for i in range(nFrames):
        if axis== 'x': vector = "[%f,0,0]"%(distanceIncrement[i])
        elif axis== 'y': vector = "[0,%f,0]"%(distanceIncrement[i])
        elif axis== 'z': vector = "[0,0,%f]"%(distanceIncrement[i])
        moviedata.add(framestates[i],"translate %s,%s"%(vector,selection))

def mv_set(frames="1",variable="",start="0.0",end="1.0",selection='all',mode='linear'):
    """
    mv_set(frames,variable,start,end,selection,mode) - lets a PyMOL variable go through a gradient
    in the specified frame range. Great for fading effects!
    """    
    framestates = get_frame_states(frames)
    nFrames = len(framestates)
    values = get_values(nFrames,float(start),float(end),mode)

    for i in range(nFrames):
        moviedata.add(framestates[i],"set %s,%f,%s"%(variable,values[i],selection))


def mv_gradcol(frames="1",selection="all",R1="1.0",G1="1.0",B1="1.0",R2="0.0",G2="0.0",B2="0.0",mode='linear'):
    """
    mv_gradcol(frames,selection,R1,G1,B1,R2,G2,B2) - changes colour gradually from (R1,G1,B1) to (R2,G2,B2)
    through the specified frame range and on the specified selection.
    """
    # provided by Tserk Wassenaar 2003
    tmpc="_temp_color"
    framestates = get_frame_states(frames)
    nFrames = len(framestates)

    red   = get_values(nFrames,float(R1),float(R2),mode)
    green = get_values(nFrames,float(G1),float(G2),mode)
    blue  = get_values(nFrames,float(B1),float(B2),mode)
    
    for i in range(nFrames):
        moviedata.add(framestates[i],"set_color %s,[ %f,%f,%f ]"%(tmpc,red[i],green[i],blue[i]))
        moviedata.add(framestates[i],"color %s, %s"%(tmpc,selection))


def mv_bg(frames='1',R1=0.0,G1=0.0,B1=0.0,R2=0.0,G2=0.0,B2=0.0,mode='linear'):
    """
    mv_bg lets the background colour fade from RGB1 to RGB2. Isn't that a nice feature ;)
    """
    # provided by Tserk Wassenaar 2003
    framestates = get_frame_states(frames)
    nFrames = len(framestates)

    red   = get_values(nFrames,float(R1),float(R2),mode)
    green = get_values(nFrames,float(G1),float(G2),mode)
    blue  = get_values(nFrames,float(B1),float(B2),mode)
    
    for i in range(nFrames):
        moviedata.add(framestates[i],"cmd.set('bg_rgb',[%f,%f,%f])" %(red[i],green[i],blue[i]))


def mv_del(frames="1",S1="all",S2="all",start=50,mode='linear'):
    """
    Stepwise deletes the molecule S1 by a sphere growing from S2.
    """
    # provided by Tserk Wassenaar 2003
    framestates = get_frame_states(frames)
    nFrames = len(framestates)
 
    values= get_values(nFrames,float(start),0.0,mode)
    for i in range(nFrames):
        moviedata.add(framestates[i],"remove %s and not (%s within %f of %s)"%(S1,S1,values[i],S2))

def mv_morph(frames='1',source='',target='',filename='morph_script.pml'):
    """
    Atoms from source selection one will be _alter_ed to be on positions from
    target atoms at end time. This is very time consuming! It writes and uses
    an external script which is read every frame, since the list of commands
    will be very long usually.
    """
    # provided by Tserk Wassenaar 2003
    framestates = get_frame_states(frames)
    nFrames = len(framestates)

    sourceobj = cmd.get_model(source)
    targetobj = cmd.get_model(target)
    natoms = len(sourceobj.atom)
    if not len(targetobj.atom) == natoms:
        print "Something wrong, target selection is of different size as source!"
        return

    fout = open(filename, 'w')

    for i in range(natoms):
        r1 = sourceobj.atom[i].coord
        r2 = targetobj.atom[i].coord
        if r1 != r2:
            shift = [ (r2[0]-r1[0])/(nFrames - 1),
                      (r2[1]-r1[1])/(nFrames - 1),
                      (r2[2]-r1[2])/(nFrames - 1) ]
            atomid = 'id %d' % sourceobj.atom[i].id
            if shift[0]:
                fout.write('alter_state 1,%s,x=x+ %f\n' % (source + ' and ' + atomid, shift[0]))
            if shift[1]:
                fout.write('alter_state 1,%s,y=y+ %f\n' % (source + ' and ' + atomid, shift[1]))
            if shift[2]:
                fout.write('alter_state 1,%s,z=z+ %f\n' % (source + ' and ' + atomid, shift[2]))

    for fs in framestates:
        moviedata.add(fs,"cmd.do('@%s')"%filename)


#
# Commands with trigonometric smoothing
#
def mv_sinturn(frames="1",axis="z",angle='360'):
    mv_turn(frames,axis,angle,mode='trigon')

def mv_sinrotate(frames="1",axis="z",angle='360',selection='all'):
    mv_rotate(frames,axis,angle,selection,mode='trigon')

def mv_sinmove(frames="1",axis="x",distance="0"):
    mv_move(frames,axis,distance,mode='trigon')

def mv_sintrans(frames="1",axis="x",distance="0",selection='all'):
    mv_trans(frames,axis,distance,selection,mode='trigon')

def mv_sinset(frames="1",variable="",start="0.0",end="1.0",selection='all'):
    mv_set(frames,variable,start,end,selection,mode='trigon')

def mv_sinbg(frames='1',R1=0.0,B1=0.0,G1=0.0,R2=0.0,G2=0.0,B2=0.0,):
    mv_bg(frames,R1,G1,B1,R2,G2,B2,mode='trigon')
    # provided by Tserk


def movie(png_prefix="",ray="0"):
    """
    Creates the movie and plays it.
    """
    if png_prefix: moviedata.png_prefix=png_prefix
    if ray!="0":moviedata.ray=1
    if moviedata.png_prefix!="":
        # stop movie after first loop
        mv_cmd(str(moviedata.maxframe+1),"mstop")
        mv_cmd(str(moviedata.maxframe+2),"dummy")
        print "don"
    
    cmd.frame(1) # reset frame counter
    nFrames=moviedata.maxframe

    # compile list of molecule states
    states=[]
    for n in range(nFrames):
        states.append(moviedata.get_state(n+1))

    # compile mset command string "1 2 3 4 x3 5" from state list [1,2,3,4,4,4,5]
    statelist=""
    count=0     
    for i in range(nFrames):
        actual=states[n]
        next=0
        if n<nFrames-1: next=states[n+1]
        if next==actual: count+=1
        else:
            if count>0: statelist+="%s x%i "%(actual,count+1)
            else: statelist+="%s "%(actual)
            count=0
            
    cmd.mset(statelist)

    do=["zero unused"] # create empty frame-2do-list
    for i in range(nFrames): do.append("")

    for m in moviedata.movie: do[m[0]]+=m[2]+";" # push all movie commands to the 2do-list
    
    # check for png output and raytracing:
    #if moviedata.png_prefix!="":
    #    cmd.set('ray_trace_frames',moviedata.ray)
    #    cmd.set('cache_frames',0)
    #    cmd.mpng(moviedata.png_prefix)
    if moviedata.png_prefix!="":
        for i in range(nFrames):
            if moviedata.ray: do[i]+="ray;"
            num = "0000"+str(i)
            num = num[-4:]
            do[i]+="png %s.%s;"%(moviedata.png_prefix,num)
            
    # now let action happen in the frames
    for i in range(nFrames):
        cmd.mdo(i+1,do[i+1])


    cmd.mplay() # start the movie



#
#
# Code from MasterMovie.py
#
#
def store_view(name):
    """
    Stores the actual view under a name.
    """
    moviedata.store_view(name)

def load_view(name):
    """
    Restores a view stored previously.
    """
    moviedata.load_view(name)

# ----------------------------------------------
# camera_travel - Laurence Pearl, November 2003
#     Pythonized by Lieven Buts, November 2003
#     Adapted to the movie.py framework by Morri Feldman and Seth Harris, December, 2003

#
# some helpful procedure.
# i did not go through them in detail, i just left them as they were, assuming
# they work. KR.
#
# But in fact they didn't. I guess i messed something up here. I re-inserted the
# original code from camera_view_travel.py and commented this here out.
#
def quaternion(view):
        """
        Returns a quaternion representation of a view matrix.
        """

        nxt = [1,2,0]
        q = [0.0,0.0,0.0,1.0]

        tr = view[0]+view[4]+view[8]

        if tr > 0.0 :
                s = sqrt(tr + 1.0)
                qw1 = s / 2.0
                s = 0.5 / s
                return ( (view[5] - view[7]) * s,
                         (view[6] - view[2]) * s,
                         (view[1] - view[3]) * s,
                         qw1                      )
        else :
                i = 0
                if (view[4] > view[0]):     i = 1
                if (view[8] > view[i+3*i]): i = 2
                j = nxt[i]
                k = nxt[j]
                s = sqrt ((view[i+i*3] - (view[j+j*3] + view[k+k*3])) +  1.0)
                q[i] = s * 0.5
                if (s != 0.0): s = 0.5 / s
                q[3] = (view[k+3*j] - view[j+3*k]) * s
                q[j] = (view[j+3*i] + view[i+3*j]) * s
                q[k] = (view[k+3*i] + view[i+3*k]) * s
                return q

def mv_viewtravel(frames="1",old_view=(1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0),new_view=(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),mode='linear'):
    """
    Generate progressive view matrices to move the camera smoothly
    from the current view to a new view provided as an argument.

     first   - start frame
     old_view  - view matrix at start of the sequence.
     new_view  - PyMol view matrix that defines the view at the end 
    of the sequence
    
    """
    framestates= get_frame_states(frames)
    nframes=len(framestates)
    ff=float(1.0/nframes)

    #       print ( "view : (" + "%8.3f, "*17 + "%8.3f)" ) % (old_view)
    #       print "oldtran : %8.3f %8.3f %8.3f" % (old_view[12], old_view[13], old_view[14])

    #		save for later since in sin smoothing need to do zoom/clip parameters 
    #		step by step also instead of a constant step size
    nv11 = new_view[11]
    nv15 = new_view[15]
    nv16 = new_view[16]
    
    #       capture new zoom/clip parameters
    ozc = (new_view[11],new_view[15],new_view[16])

    #       calculate shift in zoom/clip parameters
    dzc1 = (ozc[0] - old_view[11]) * ff
    dzc2 = (ozc[1] - old_view[15]) * ff
    dzc3 = (ozc[2] - old_view[16]) * ff

    ozc = [old_view[11],old_view[15],old_view[16]]

    #       capture new translation vector component
    o = [new_view[12],new_view[13],new_view[14]]

    #       calculate shift vector
    dx = o[0] - old_view[12]
    dy = o[1] - old_view[13]
    dz = o[2] - old_view[14]

    dx = dx*ff
    dy = dy*ff
    dz = dz*ff

    o = [old_view[12],old_view[13],old_view[14]]

    #       capture old and new rotation matrix components in quaternion form
    #       m[0][0] = v[0]  m[0][1] = v[1]  m[0][2] = v[2]
    #       m[1][0] = v[3]  m[1][1] = v[4]  m[1][2] = v[5]
    #       m[2][0] = v[6]  m[2][1] = v[7]  m[2][2] = v[8]
    qx1,qy1,qz1,qw1 = quaternion(old_view)
    qx2,qy2,qz2,qw2 = quaternion(new_view)

    #   calc cosine
    cosom = qx1 * qx2 + qy1 * qy2 + qz1 * qz2 + qw1 * qw2

    limit = 0.001
    if cosom>1.0+limit:
        raise ValueError,"Cosine of omega way out of range (positive)"
    elif cosom>1.0:
        print "Warning: cosom corrected from ",cosom,"to",
        cosom = 1.0
        print cosom

    if cosom<-1.0-limit:
        raise ValueError,"Cosine of omega way out of range (negative)"
    elif cosom<-1.0:
        print "Warning: cosom corrected from ",cosom,"to",
        cosom = 1.0
        print cosom

    #   adjust signs
    if (cosom < 0.0):
        cosom = -cosom
        to0 = -qx2
        to1 = -qy2
        to2 = -qz2
        to3 = -qw2
    else:
        to0 = qx2
        to1 = qy2
        to2 = qz2
        to3 = qw2

    #   calc coefficients
    omega = acos(cosom)
    sinom = sin(omega)
    if sinom==0.0:
        sinom=limit
        print "Warning: sinom corrected!"

    #   restore old view
    #cmd.set_view( ("%8.3f, " * 17 + "%8.3f") % tuple(old_view) )

    #   loop interpolating over nframes generating interpolated quaternion
    a=0
    for fs in framestates:
        scale0 = sin((1.0 - float(a*ff)) * omega) / sinom
        scale1 = sin(float(a*ff) * omega) / sinom
        #	print a, omega
        #	print a,scale0,scale1
        rx = scale0 * qx1 + scale1 * to0;
        ry = scale0 * qy1 + scale1 * to1;
        rz = scale0 * qz1 + scale1 * to2;
        rw = scale0 * qw1 + scale1 * to3;

        # convert back to matrix
        x2 = rx + rx
        y2 = ry + ry
        z2 = rz + rz
        xx = rx * x2
        xy = rx * y2
        xz = rx * z2
        yy = ry * y2
        yz = ry * z2
        zz = rz * z2
        wx = rw * x2
        wy = rw * y2
        wz = rw * z2

        nv0 = 1.0 - (yy + zz)
        nv3 = xy - wz
        nv6 = xz + wy

        nv1 = xy + wz
        nv4 = 1.0 - (xx + zz)
        nv7 = yz - wx

        nv2 = xz - wy
        nv5 = yz + wx
        nv8 = 1.0 - (xx + yy)

        # update translation vector
        o[0] = o[0] + dx
        o[1] = o[1] + dy
        o[2] = o[2] + dz

        if mode=='trigon':
            # for sin smoothing need difference between this step and next step:
            diff = (sin(math.pi/2*((a+1)*2*ff-1))-sin(math.pi/2*(a*2*ff-1)))/2
            if diff < 0:
                print ("diff adjusted from negative")
                diff = 0
            #   calculate shift in zoom/clip parameters
            dzc1 = (nv11 - old_view[11]) * diff
            dzc2 = (nv15 - old_view[15]) * diff
            dzc3 = (nv16 - old_view[16]) * diff

        # update zoom/clip parameters
        ozc[0] = ozc[0] + dzc1
        ozc[1] = ozc[1] + dzc2
        ozc[2] = ozc[2] + dzc3

        #   cmd.mdo("%d" % (first), ("set_view (" + "%8.3f, "*17 + "%8.3f)") %(nv0,nv1,nv2,nv3,nv4,nv5,nv6,nv7,nv8,old_view[9],old_view[10],ozc1,ox,oy,oz,ozc2,ozc3,old_view[17]))
        #   first += 1
        #   cmd.set_view( ("%8.3f, "*17 + "%8.3f") %(nv0,nv1,nv2,nv3,nv4,nv5,nv6,nv7,nv8,old_view[9],old_view[10],ozc1,ox,oy,oz,ozc2,ozc3,old_view[17]))

        svcmd = "set_view (%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f)" %(nv0,nv1,nv2,nv3,nv4,nv5,nv6,nv7,nv8,old_view[9],old_view[10],ozc[0],o[0],o[1],o[2],ozc[1],ozc[2],old_view[17])
	moviedata.add(fs,svcmd)
	a += 1

#def mv_sinviewtravel(frames=1,old_view=(1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0),new_view=(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)):
#    mv_viewtravel(frames,old_view,new_view,mode='trigon')


######### What follows are several (probably redundant but I'm only just learning Python!)
######### subroutines used by the ribbon rider module
# this is just plodding through it.  There's probably a better way in NumPy
# as it is already packaged, but I don't know it.
def cross_product(a,b):
    vx = a[1]*b[2]-a[2]*b[1]
    vy = a[2]*b[0]-a[0]*b[2]
    vz = a[0]*b[1]-a[1]*b[0]
    return (vx,vy,vz)

# normalize the vector    
def normvec(v,mag):
    vx=v[0]/mag
    vy=v[1]/mag
    vz=v[2]/mag
    return (vx,vy,vz)
    
#Convert rotation vector and angle to quaternion
def vecang2quat (rotvec,ang):
    qx = rotvec[0] * math.sin(ang/2)
    qy = rotvec[1] * math.sin(ang/2)
    qz = rotvec[2] * math.sin(ang/2)
    qw = math.cos(ang/2)
    return (qx,qy,qz,qw)

# Convert quaternion form to matrix
# note that I'm setting up the matrix working across each row first:
# m[0]  m[1]  m[2]
# m[3]  m[4]  m[5]
# m[6]  m[7]  m[8]
def quat2mat (q):
    m = [0]*9
    m[0] = q[3]*q[3] + q[0]*q[0] - q[1]*q[1] - q[2]*q[2]
    m[1] = 2*q[0]*q[1] - 2*q[3]*q[2]
    m[2] = 2*q[0]*q[2] + 2*q[3]*q[1]
    m[3] = 2*q[0]*q[1] + 2*q[3]*q[2]
    m[4] = q[3]*q[3] - q[0]*q[0] + q[1]*q[1] - q[2]*q[2]
    m[5] = 2*q[1]*q[2] - 2*q[3]*q[0]
    m[6] = 2*q[0]*q[2] - 2*q[3]*q[1]
    m[7] = 2*q[1]*q[2] + 2*q[3]*q[0]
    m[8] = q[3]*q[3] - q[0]*q[0] - q[1]*q[1] + q[2]*q[2]
    return (m)
	
# normalize the quaternion to a unit value
def normquat (q):
    magquat = math.sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2] + q[3]*q[3])
    n=[0]*4
    n[0]=q[0]/magquat
    n[1]=q[1]/magquat
    n[2]=q[2]/magquat
    n[3]=q[3]/magquat
    return (n[0],n[1],n[2],n[3])

##### The Ribbon Rider module
### create by Seth Harris, January, 2004
### based on Seth's VRML pepcam fly through
def ribbon_ride(selection="mol",fperm="40",zbuff="30",halfslab="6",frequency="1"):
    # get current view, just to inherit some flags like orthoscopic and ?
    # from how the user was looking at the world
    # that being said, most of the 18 view matrix arguments will be set de novo
    # by this routine
    
    old_view = cmd.get_view()
    
    frequency=int(frequency)
    fperm = int(fperm)
    zbuff = int(zbuff)
    halfslab = int(halfslab)
    
    #frame of reference vector...rotations are relative to this
    start=(0,0,-1)
    
    # parse mol selection to get array of Calpha coordinates
    cmd.create ("calpha","/" + selection + "////CA")
    calpha = cmd.get_model("calpha")
    # break calpha up so it only includes every xth atom, where x is frequency
    # passed in by user
    
    totalcount=len(calpha.atom)
    
    #define working list size
    listsizecorrect=0
    if (totalcount%frequency):
        listsizecorrect=1
    workinglist=[0]*(totalcount/frequency+listsizecorrect)
    lpcount=0
    indexcount=0
    for a in calpha.atom:
        # now only add this atom to the working array if our counter%frequency is 0
        # i.e. is evenly divisible by the frequency
        if (lpcount%frequency==0):
            workinglist[indexcount]=(a.coord[0],a.coord[1],a.coord[2])
            indexcount=indexcount+1
        lpcount=lpcount+1
    
    lpcount=0
    lastx=0
    target=(0,0,0)
    for b in workinglist:
        cx=b[0]
        cy=b[1]
        cz=b[2]

        # calculate vector to next Calpha
        if (lastx):
            vx=cx-lastx
            vy=cy-lasty
            vz=cz-lastz
            target=(vx,vy,vz)
        #print "cx - lastx is: " + `cx` + " - " + `lastx`
        lastx=cx
        lasty=cy
        lastz=cz
        #print "target vector is: " + `target`
        #debugging control point
        #	if (lpcount==1000):
        #		print "breaking!"
        #		break
        if (lpcount>0):
            maga=math.sqrt(start[0]*start[0] + start[1]*start[1] + start[2]*start[2])
            magb=math.sqrt(target[0]*target[0] + target[1]*target[1] + target[2]*target[2])

            # normalize the target view vector b
            target=normvec(target,magb)
            #print "normalized target view vector is: " + `target`
    
            magb=math.sqrt(target[0]*target[0] + target[1]*target[1] + target[2]*target[2])
            #print "magnitude should now be one: " + `magb`
            magb=1

            #calculate cross product
            cprod=cross_product(start,target)    
            magcross=math.sqrt(cprod[0]*cprod[0] + cprod[1]*cprod[1] + cprod[2]*cprod[2])
            dprod = (start[0]*target[0] + start[1]*target[1] + start[2]*target[2])
    
            # get angle between vectors
            sintheta = magcross/(maga*magb)
            theta1=asin(sintheta)
            theta2 = math.pi - theta1
    
            costheta = dprod/(maga*magb)
            theta3=acos(costheta)
            theta4=-theta3

            # have to check which solution of asin is correct by comparing with acos results
            diff1 = theta1 - theta3
            diff2 = theta2 - theta3
            diff3 = theta1 - theta4
            diff4 = theta2 - theta4
            diff1 = abs (diff1)
            diff2 = abs (diff2)
            diff3 = abs (diff3)
            diff4 = abs (diff4)
            if   (diff1 < 0.01) : theta = theta1
            elif (diff2 < 0.01) : theta = theta2
            elif (diff3 < 0.01) : theta = theta1;
            elif (diff4 < 0.01) : theta = theta2
            else                : theta = 0

            # convert this rotation vector (cprod) and angle (theta) to quaternion form
            quat1 = vecang2quat(cprod,theta)

            #normalize the quat
            quat1 = normquat(quat1)

            # now convert the quaternion to a matrix
            mat = quat2mat(quat1)

            #print "new view matrix is " + `mat`
            cmd.set_view( ("%8.3f, "*17 + "%8.3f") %(mat[0],mat[1],mat[2],mat[3],mat[4],mat[5],mat[6],mat[7],mat[8],0,0,-zbuff,cx,cy,cz,zbuff-halfslab,zbuff+halfslab-2,old_view[17]))
            new=cmd.get_view()
            if (lpcount==0):
                original=new
            start_frame=(lpcount-1)*fperm
            end_frame=start_frame+fperm
            mv_viewtravel("%s-%s"%(start_frame,end_frame),old_view,new)
            old_view=new
        lpcount=lpcount+1
    movie()

#################  PEAK TOUR #############################
## created by Seth Harris, shar...@msg.ucsf.edu         ##
## visit various entities sequentially such as peaks in ##
## your map file.                                       ##
## usage: peak_tour selection, zoom buffer              ##
## e.g.: peak_tour mypeaks, 6, 40, 10                   ##

def tour(selection="mol",zbuff="6",framespermove="40",stallframes="10",rotation="90"):
    """
    Creates a movie that jumps through atoms of a selection,
    doing a short dance at each.
   
    Usage:   peak_tour selection, zbuff, framespermove, stallframes, rotation
    e.g.     peak_tour my_map_peaks, 6, 40, 10, 90
    (those numbers are also the default values, by the way)
    or e.g.  peak_tour waters, rotation=90 
   
    where
    "zbuff" 
        is how far back from each waypoint the view is positioned
    "framespermove" 
        is how many frames spent at each waypoint 
    "stallframes"
        is how many frames to wait at each waypoint
        after the rotations before moving on 
    "rotation" 
        is how many degrees to rotate at each stopover 
    Note that the selections are atom based, while the viewpoint is by residue
    So if you want to run this on a protein it is recommended to 
    make a subselection of just the alpha carbons, for instance
    Otherwise you will "sit and spin" doing a cycle for each _atom_ in the
    residue before it advances to the next _residue_. 
    """
    framespermove=int(framespermove)
    stallframes=int(stallframes)
    rotation=int(rotation)
    mv_clear() # clear movie caches
    # cmd.do("mset")
    # parse mol selection to get array of peaks and find out how many waypoints we will have
    #cmd.create ("tour","/" + selection)
    peaks = cmd.get_model(selection).atom

    stopovers=len(peaks)

    for waypoints in range(1,stopovers+1):
        startframe=(waypoints-1)*framespermove+1+(waypoints-1)*stallframes
        #end1=int(startframe+framespermove/8)
        #end2=int(startframe+framespermove*3/8)
        end3=int(startframe+framespermove/2)
        #end4=int(startframe+framespermove*5/8)
        #end5=int(startframe+framespermove*7/8)
        endframe=startframe+framespermove

        # do a full 360 turn on y and x at each frame
        mv_sinturn("%i-%i"%(startframe,end3),'y',"%i"%rotation)
        mv_sinturn("%i-%i"%(end3,endframe),'x',"%i"%rotation)
        mv_cmd(str(startframe+1), "zoom /"+selection+"///"+peaks[waypoints-1].resi+"/, "+zbuff)

    movie()
    # converted the code to use the other movie commands. Save space. KR


------------------------------------------------------------------------------
Free Software Download: Index, Search & Analyze Logs and other IT data in 
Real-Time with Splunk. Collect, index and harness all the fast moving IT data 
generated by your applications, servers and devices whether physical, virtual
or in the cloud. Deliver compliance at lower cost and gain new business 
insights. http://p.sf.net/sfu/splunk-dev2dev 
_______________________________________________
PyMOL-users mailing list (PyMOL-users@lists.sourceforge.net)
Info Page: https://lists.sourceforge.net/lists/listinfo/pymol-users
Archives: http://www.mail-archive.com/pymol-users@lists.sourceforge.net

Reply via email to