Exemple #1
0
    def get_pdbstr(selection="all", state=-1, ref='', ref_state=-1, quiet=1, _self=cmd):
        '''
DESCRIPTION

    "get_pdbstr" in an API-only function which returns a pdb
    corresponding to the atoms in the selection provided and that are
    present in the indicated state

PYMOL API

    cmd.get_pdbstr(string selection, int state)

NOTES

    "state" is a 1-based state index for the object.

    if state is -1, then current state is used.

    if state is 0, then all states are saved.
    
    '''
        r = DEFAULT_ERROR
        try:
            _self.lock(_self)   
            r = _cmd.get_pdb(_self._COb,str(selection),int(state)-1,0,
                             str(ref),int(ref_state),int(quiet))
        finally:
            _self.unlock(r,_self)
        if _self._raising(r,_self): raise QuietException         
        return r
Exemple #2
0
    def get_pdbstr(selection="all", state=-1, ref='', ref_state=-1, quiet=1, _self=cmd):
        '''
DESCRIPTION

    "get_pdbstr" in an API-only function which returns a pdb
    corresponding to the atoms in the selection provided and that are
    present in the indicated state

PYMOL API

    cmd.get_pdbstr(string selection, int state)

NOTES

    "state" is a 1-based state index for the object.

    if state is -1, then current state is used.

    if state is 0, then all states are saved.
    
    '''
        r = DEFAULT_ERROR
        try:
            _self.lock(_self)   
            r = _cmd.get_pdb(_self._COb,str(selection),int(state)-1,0,
                             str(ref),int(ref_state),int(quiet))
        finally:
            _self.unlock(r,_self)
        if _self._raising(r,_self): raise QuietException         
        return r
Exemple #3
0
    def save(filename,
             selection='(all)',
             state=-1,
             format='',
             ref='',
             ref_state=-1,
             quiet=1,
             partial=0,
             _self=cmd):
        '''
DESCRIPTION

    "save" writes content to a file.
    
USAGE

    save filename [, selection [, state [, format ]]]

ARGUMENTS

    filename = string: file path to be written

    selection = string: atoms to save {default: (all)}

    state = integer: state to save {default: -1 (current state)}
    
PYMOL API

    cmd.save(string file, string selection, int state, string format)

NOTES

    The file format is automatically chosen if the extesion is one of
    the supported output formats: pdb, pqr, mol, pkl, mmd, mmod, pov,
    png, pse, aln, obj, mtl, or wrl.

    If the file format is not recognized, then a PDB file is written
    by default.

    For molecular files and where applicable and supported:
    
    * if state = -1 (default), then only the current state is written.

    * if state = 0, then a multi-state output file is written.
    
SEE ALSO

    load, get_model
        '''
        # preprocess selection
        input_selection = selection
        selection = selector.process(input_selection)
        #
        r = DEFAULT_ERROR
        lc_filename = string.lower(filename)
        if format == '':
            format = 'unknown'
            # refactor following if/elif cascade
            # with a dictionary lookup
            if re.search("\.pdb$|\.ent$", lc_filename):
                format = 'pdb'
            elif re.search("\.pqr$", lc_filename):
                format = 'pqr'
            elif re.search("\.mol$", lc_filename):
                format = 'mol'
            elif re.search("\.sdf$", lc_filename):
                format = 'sdf'
            elif re.search("\.pkl$", lc_filename):
                format = 'pkl'
            elif re.search("\.pkl$", lc_filename):
                format = 'pkla'
            elif re.search("\.mmd$", lc_filename):
                format = 'mmod'
            elif re.search("\.out$", lc_filename):
                format = 'mmod'
            elif re.search("\.dat$", lc_filename):
                format = 'mmod'
            elif re.search("\.mmod$", lc_filename):
                format = 'mmod'
            elif re.search("\.pmo$", lc_filename):
                format = 'pmo'
            elif re.search("\.pov$", lc_filename):
                format = 'pov'
            elif re.search("\.png$", lc_filename):
                format = 'png'
            elif re.search("\.pse$|\.psw$", lc_filename):
                format = 'pse'
            elif re.search("\.aln$", lc_filename):
                format = 'aln'
            elif re.search("\.fasta$", lc_filename):
                format = 'fasta'
            elif re.search("\.obj$", lc_filename):
                format = 'obj'
            elif re.search("\.mtl$", lc_filename):
                format = 'mtl'
            elif re.search("\.wrl$", lc_filename):
                format = 'wrl'
            elif re.search("\.idtf$", lc_filename):
                format = 'idtf'
            elif re.search("\.mol2$", lc_filename):
                format = 'mol2'
            else:
                format = str(format)
        if format == 'unknown':
            if not quiet:
                print " Save-Warning: Unrecognized file type -- defaulting to PDB format."
            format = 'pdb'
        filename = _self.exp_path(filename)
        if format == 'pdb':  # standard PDB file
            f = open(filename, "w")
            if f:
                st = ''
                try:
                    _self.lock(_self)
                    st = _cmd.get_pdb(_self._COb, "(" + str(selection) + ")",
                                      int(state) - 1, 0, str(ref),
                                      int(ref_state) - 1, int(quiet))
                    if st != None:
                        r = DEFAULT_SUCCESS
                finally:
                    _self.unlock(r, _self=_self)
                f.write(st)
                f.close()
                if not quiet:
                    print " Save: wrote \"" + filename + "\"."
        elif format == 'aln':
            st = ''
            try:
                _self.lock(_self)
                st = _cmd.get_seq_align_str(_self._COb, str(selection),
                                            int(state) - 1, 0, int(quiet))
                if st != None:
                    r = DEFAULT_SUCCESS
            finally:
                _self.unlock(r, _self)
            if st != None:
                f = open(filename, "w")
                f.write(st)
                f.close()
                if not quiet:
                    print " Save: wrote \"" + filename + "\"."
            else:
                r = DEFAULT_ERROR
        elif format == 'fasta':
            st = _self.get_fastastr(selection)
            if st != None:
                r = DEFAULT_SUCCESS
                f = open(filename, "w")
                f.write(st)
                f.close()
                if not quiet:
                    print " Save: wrote \"" + filename + "\"."
            else:
                r = DEFAULT_ERROR
        elif format == 'pqr':  # PQR (modified PDB file)
            f = open(filename, "w")
            if f:
                st = ''
                try:
                    _self.lock(_self)
                    st = _cmd.get_pdb(_self._COb, "(" + str(selection) + ")",
                                      int(state) - 1, 1, str(ref),
                                      int(ref_state) - 1, int(quiet))
                    if st != None:
                        r = DEFAULT_SUCCESS
                finally:
                    _self.unlock(r, _self)
                f.write(st)
                f.close()
                if not quiet:
                    print " Save: wrote \"" + filename + "\"."
        elif format == 'pkl':  # python binary
            io.pkl.toFile(_self.get_model(selection, state, ref, ref_state),
                          filename)
            r = DEFAULT_SUCCESS
            if not quiet:
                print " Save: wrote \"" + filename + "\"."
        elif format == 'pkla':  # ascii override
            io.pkl.toFile(_self.get_model(selection, state, ref, ref_state),
                          filename,
                          bin=0)
            r = DEFAULT_SUCCESS
            if not quiet:
                print " Save: wrote \"" + filename + "\"."
        elif format == 'pse':  # PyMOL session
            filename = filename.replace(
                "\\", "/")  # always use unix-like path separators
            _self.set("session_file", filename, quiet=1)
            if '(' in input_selection:  # ignore selections
                input_selection = ''
            if not quiet:
                print " Save: Please wait -- writing session file..."
            io.pkl.toFile(
                _self.get_session(str(input_selection), int(partial),
                                  int(quiet)), filename)
            r = DEFAULT_SUCCESS
            if not quiet:
                print " Save: wrote \"" + filename + "\"."
        elif format == 'mmod':  # macromodel
            io.mmd.toFile(_self.get_model(selection, state, ref, ref_state),
                          filename)
            r = DEFAULT_SUCCESS
            if not quiet:
                print " Save: wrote \"" + filename + "\"."
        elif format == 'sdf':
            state = int(state)
            if state == 0:
                first_state = 1
                last_state = cmd.count_states(selection)
            else:
                first_state = state
                last_state = state
            sdf = SDF(filename, 'w')
            for state in range(first_state, last_state + 1):
                rec = SDFRec(
                    io.mol.toList(
                        _self.get_model(selection, state, ref, ref_state)) +
                    ["$$$$\n"])
                sdf.write(rec)
            r = DEFAULT_SUCCESS
            if not quiet:
                print " Save: wrote %d states to \"%s\"." % (
                    1 + last_state - first_state, filename)
        elif format == 'mol':
            io.mol.toFile(_self.get_model(selection, state, ref, ref_state),
                          filename)
            r = DEFAULT_SUCCESS
            if not quiet:
                print " Save: wrote \"" + filename + "\"."
        elif format == "mol2":
            state = int(state)
            if state == 0:
                first_state = 1
                last_state = cmd.count_states(selection)
            else:
                first_state = state
                last_state = state
            recList = []
            for state in range(first_state, last_state + 1):
                # assign_atom_types selection, format [ mol2, macromodel ], state, quiet
                assign_atom_types(selection, "mol2", state, 1, _self)
                recList.extend(
                    io.mol2.toList(_self.get_model(selection, state, ref,
                                                   ref_state),
                                   selection=selection,
                                   state=state))
            m = MOL2(cmd=cmd)
            m.strToFile(recList, filename)
            r = DEFAULT_SUCCESS
            if not quiet:
                print " Save: wrote %d states to \"%s\"." % (
                    1 + last_state - first_state, filename)
        elif format == 'png':
            r = _self.png(filename, quiet=quiet)
        # refactor below to lift repeated code
        elif format == 'pov':
            tup = _self.get_povray()
            f = open(filename, "w")
            f.write(tup[0])
            f.write(tup[1])
            f.flush()
            f.close()
            if not quiet:
                print " Save: wrote \"" + filename + "\"."
            r = DEFAULT_SUCCESS
        elif format == 'obj':
            tup = _self.get_mtl_obj()
            f = open(filename, "w")
            f.write(tup[1])
            f.flush()
            f.close()
            r = DEFAULT_SUCCESS
        elif format == 'mtl':
            tup = _self.get_mtl_obj()
            f = open(filename, "w")
            f.write(tup[0])
            f.flush()
            f.close()
            r = DEFAULT_SUCCESS
        elif format == 'wrl':
            txt = _self.get_vrml()
            f = open(filename, "w")
            f.write(txt)
            f.flush()
            f.close()
            if not quiet:
                print " Save: wrote \"" + filename + "\"."
            r = DEFAULT_SUCCESS
        elif format == 'idtf':
            tup = _self.get_idtf()
            f = open(filename, "w")
            f.write(tup[0])
            f.write(tup[1])
            f.flush()
            f.close()
            if not quiet:
                fov = float(cmd.get("field_of_view"))
                dist = cmd.get_view()[11]
                print " 3Daac=%3.1f, 3Droll=0, 3Dc2c=0 0 1, 3Droo=%1.2f, 3Dcoo=0 0 %1.2f" % (
                    fov, -dist, dist)
                print " Save: wrote \"" + filename + "\"."
            r = DEFAULT_SUCCESS

        if _self._raising(r, _self): raise QuietException
        return r
Exemple #4
0
    def save(filename, selection='(all)', state=-1, format='', ref='',
             ref_state=-1, quiet=1, partial=0,_self=cmd):
        '''
DESCRIPTION

    "save" writes content to a file.
    
USAGE

    save filename [, selection [, state [, format ]]]

ARGUMENTS

    filename = string: file path to be written

    selection = string: atoms to save {default: (all)}

    state = integer: state to save {default: -1 (current state)}
    
PYMOL API

    cmd.save(string file, string selection, int state, string format)

NOTES

    The file format is automatically chosen if the extesion is one of
    the supported output formats: pdb, pqr, mol, pkl, mmd, mmod, pov,
    png, pse, aln, obj, mtl, or wrl.

    If the file format is not recognized, then a PDB file is written
    by default.

    For molecular files and where applicable and supported:
    
    * if state = -1 (default), then only the current state is written.

    * if state = 0, then a multi-state output file is written.
    
SEE ALSO

    load, get_model
        '''
        # preprocess selection
        input_selection = selection
        selection = selector.process(input_selection)
        #   
        r = DEFAULT_ERROR
        lc_filename=string.lower(filename)
        if format=='':
            format = 'unknown'
            # refactor following if/elif cascade 
            # with a dictionary lookup
            if re.search("\.pdb$|\.ent$",lc_filename):
                format = 'pdb'
            elif re.search("\.pqr$",lc_filename):
                format = 'pqr'
            elif re.search("\.mol$",lc_filename):
                format = 'mol'
            elif re.search("\.sdf$",lc_filename):
                format = 'sdf'
            elif re.search("\.pkl$",lc_filename):
                format = 'pkl'
            elif re.search("\.pkl$",lc_filename):
                format = 'pkla'
            elif re.search("\.mmd$",lc_filename):
                format = 'mmod'
            elif re.search("\.out$",lc_filename):
                format = 'mmod'
            elif re.search("\.dat$",lc_filename):
                format = 'mmod'
            elif re.search("\.mmod$",lc_filename):
                format = 'mmod'
            elif re.search("\.pmo$",lc_filename):
                format = 'pmo'
            elif re.search("\.pov$",lc_filename):
                format = 'pov'
            elif re.search("\.png$",lc_filename):
                format = 'png'
            elif re.search("\.pse$|\.psw$",lc_filename):
                format = 'pse'
            elif re.search("\.aln$",lc_filename):
                format = 'aln'
            elif re.search("\.fasta$",lc_filename):
                format = 'fasta'
            elif re.search("\.obj$",lc_filename):
                format = 'obj'
            elif re.search("\.mtl$",lc_filename):
                format = 'mtl'
            elif re.search("\.wrl$",lc_filename):
                format = 'wrl'
            elif re.search("\.idtf$",lc_filename):
                format = 'idtf'
            elif re.search("\.mol2$",lc_filename):
                format = 'mol2'
            else:
                format = str(format)
        if format=='unknown':
            if not quiet:
                print " Save-Warning: Unrecognized file type -- defaulting to PDB format."
            format='pdb'
        filename = _self.exp_path(filename)
        if format=='pdb': # standard PDB file 
            f=open(filename,"w")
            if f:
                st = ''
                try:
                    _self.lock(_self)
                    st = _cmd.get_pdb(_self._COb,"("+str(selection)+")",int(state)-1,0,
                                      str(ref),int(ref_state)-1,int(quiet))
                    if st != None:
                        r = DEFAULT_SUCCESS                    
                finally:
                    _self.unlock(r,_self=_self)
                f.write(st)
                f.close()
                if not quiet:
                    print " Save: wrote \""+filename+"\"."
        elif format=='aln':
            st = ''
            try:
                _self.lock(_self)
                st = _cmd.get_seq_align_str(_self._COb,str(selection),int(state)-1,0,int(quiet))
                if st != None:
                    r = DEFAULT_SUCCESS
            finally:
                _self.unlock(r,_self)
            if st!=None:
                f=open(filename,"w")
                f.write(st)
                f.close()
                if not quiet:
                    print " Save: wrote \""+filename+"\"."
            else:
                r = DEFAULT_ERROR
        elif format=='fasta':
            st = _self.get_fastastr(selection)
            if st != None:
                r = DEFAULT_SUCCESS
                f=open(filename,"w")
                f.write(st)
                f.close()
                if not quiet:
                    print " Save: wrote \""+filename+"\"."
            else:
                r = DEFAULT_ERROR
        elif format=='pqr': # PQR (modified PDB file)
            f=open(filename,"w")
            if f:
                st = ''
                try:
                    _self.lock(_self)
                    st = _cmd.get_pdb(_self._COb,"("+str(selection)+")",int(state)-1,1,
                                      str(ref),int(ref_state)-1,int(quiet))
                    if st != None:
                        r = DEFAULT_SUCCESS
                finally:
                    _self.unlock(r,_self)
                f.write(st)
                f.close()
                if not quiet:
                    print " Save: wrote \""+filename+"\"."
        elif format=='pkl': # python binary
            io.pkl.toFile(_self.get_model(selection,state,ref,ref_state),filename)
            r = DEFAULT_SUCCESS
            if not quiet:
                print " Save: wrote \""+filename+"\"."
        elif format=='pkla': # ascii override
            io.pkl.toFile(_self.get_model(selection,state,ref,ref_state),filename,bin=0)
            r = DEFAULT_SUCCESS
            if not quiet:
                print " Save: wrote \""+filename+"\"."
        elif format=='pse': # PyMOL session
            filename = filename.replace("\\","/") # always use unix-like path separators	
            _self.set("session_file",filename,quiet=1)
            if '(' in input_selection: # ignore selections 
                input_selection=''
            if not quiet:
                print " Save: Please wait -- writing session file..."
            io.pkl.toFile(_self.get_session(str(input_selection),int(partial),int(quiet)),filename)
            r = DEFAULT_SUCCESS
            if not quiet:
                print " Save: wrote \""+filename+"\"."
        elif format=='mmod': # macromodel
            io.mmd.toFile(_self.get_model(selection,state,ref,ref_state),filename)
            r = DEFAULT_SUCCESS
            if not quiet:
                print " Save: wrote \""+filename+"\"."
        elif format=='sdf':
            state = int(state)
            if state==0:
                first_state = 1
                last_state = cmd.count_states(selection)
            else:
                first_state = state
                last_state = state
            sdf = SDF(filename,'w')
            for state in range(first_state, last_state+1):
                rec = SDFRec(io.mol.toList(_self.get_model(selection,state,ref,ref_state))
                             + ["$$$$\n"])
                sdf.write(rec)
            r = DEFAULT_SUCCESS
            if not quiet:
                print " Save: wrote %d states to \"%s\"."%(1+last_state-first_state,filename)
        elif format=='mol':
            io.mol.toFile(_self.get_model(selection,state,ref,ref_state),filename)
            r = DEFAULT_SUCCESS
            if not quiet:
                print " Save: wrote \""+filename+"\"."
        elif format=="mol2":
            state = int(state)
            if state==0:
                first_state = 1
                last_state = cmd.count_states(selection)
            else:
                first_state = state
                last_state = state
            recList=[]
            for state in range(first_state, last_state+1):
                # assign_atom_types selection, format [ mol2, macromodel ], state, quiet
                assign_atom_types(selection, "mol2", state, 1, _self)
                recList.extend(io.mol2.toList(_self.get_model(selection,state,ref,ref_state),selection=selection,state=state))
            m = MOL2(cmd=cmd)
            m.strToFile(recList,filename)
            r = DEFAULT_SUCCESS
            if not quiet:
                print " Save: wrote %d states to \"%s\"."%(1+last_state-first_state,filename)
        elif format=='png':
            r = _self.png(filename,quiet=quiet)
        # refactor below to lift repeated code
        elif format=='pov':
            tup = _self.get_povray()
            f=open(filename,"w")
            f.write(tup[0])
            f.write(tup[1])
            f.flush()
            f.close()
            if not quiet:
                print " Save: wrote \""+filename+"\"."
            r = DEFAULT_SUCCESS
        elif format=='obj':
            tup = _self.get_mtl_obj()
            f=open(filename,"w")
            f.write(tup[1])
            f.flush()
            f.close()
            r = DEFAULT_SUCCESS
        elif format=='mtl':
            tup = _self.get_mtl_obj()
            f=open(filename,"w")
            f.write(tup[0])
            f.flush()
            f.close()
            r = DEFAULT_SUCCESS
        elif format=='wrl':
            txt = _self.get_vrml()
            f=open(filename,"w")
            f.write(txt)
            f.flush()
            f.close()
            if not quiet:
                print " Save: wrote \""+filename+"\"."
            r = DEFAULT_SUCCESS
        elif format=='idtf':
            tup = _self.get_idtf()
            f=open(filename,"w")
            f.write(tup[0]);
            f.write(tup[1]);
            f.flush()
            f.close()
            if not quiet:
                fov = float(cmd.get("field_of_view"))
                dist = cmd.get_view()[11]
                print " 3Daac=%3.1f, 3Droll=0, 3Dc2c=0 0 1, 3Droo=%1.2f, 3Dcoo=0 0 %1.2f"%(fov,-dist,dist)
                print " Save: wrote \""+filename+"\"."
            r = DEFAULT_SUCCESS
            
        if _self._raising(r,_self): raise QuietException
        return r
Exemple #5
0
    def save(filename, selection='(all)', state=-1, format='', ref='',
             ref_state=-1, quiet=1, partial=0,_self=cmd):
        '''
DESCRIPTION

    "save" writes content to a file.
    
USAGE

    save filename [, selection [, state [, format ]]]

ARGUMENTS

    filename = string: file path to be written

    selection = string: atoms to save {default: (all)}

    state = integer: state to save {default: -1 (current state)}
    
PYMOL API

    cmd.save(string file, string selection, int state, string format)

NOTES

    The file format is automatically chosen if the extesion is one of
    the supported output formats: pdb, pqr, mol, sdf, pkl, pkla, mmd, out,
    dat, mmod, pmo, pov, png, pse, psw, aln, fasta, obj, mtl, wrl, dae, idtf,
    or mol2.

    If the file format is not recognized, then a PDB file is written
    by default.

    For molecular files and where applicable and supported:
    
    * if state = -1 (default), then only the current state is written.

    * if state = 0, then a multi-state output file is written.
    
SEE ALSO

    load, get_model
        '''
        import cPickle
        import gzip

        do_gzip = False

        # preprocess selection
        input_selection = selection
        selection = selector.process(input_selection)
        #   
        r = DEFAULT_ERROR
        lc_filename=string.lower(filename)

        if format=='':
            format = 'unknown'
            # refactor following if/elif cascade 
            # with a dictionary lookup
            if re.search("\.pdb$|\.ent$",lc_filename):
                format = 'pdb'
            elif re.search("\.cif$",lc_filename):
                format = 'cif'
            elif re.search("\.pqr$",lc_filename):
                format = 'pqr'
            elif re.search("\.mol$",lc_filename):
                format = 'mol'
            elif re.search("\.sdf$",lc_filename):
                format = 'sdf'
            elif re.search("\.pkl$",lc_filename):
                format = 'pkl'
            elif re.search("\.xyz$",lc_filename):
                format = 'xyz'
            elif re.search("\.mmd$",lc_filename):
                format = 'mmod'
            elif re.search("\.out$",lc_filename):
                format = 'mmod'
            elif re.search("\.dat$",lc_filename):
                format = 'mmod'
            elif re.search("\.mmod$",lc_filename):
                format = 'mmod'
            elif re.search("\.pmo$",lc_filename):
                format = 'pmo'
            elif re.search("\.pov$",lc_filename):
                format = 'pov'
            elif re.search("\.png$",lc_filename):
                format = 'png'
            elif re.search("\.pse$|\.psw$",lc_filename):
                format = 'pse'
            elif re.search("\.pze$|\.pzw$",lc_filename):
                do_gzip = True
                format = 'pse'
            elif re.search("\.aln$",lc_filename):
                format = 'aln'
            elif re.search("\.fasta$",lc_filename):
                format = 'fasta'
            elif re.search("\.obj$",lc_filename):
                format = 'obj'
            elif re.search("\.mtl$",lc_filename):
                format = 'mtl'
            elif re.search("\.wrl$",lc_filename):
                format = 'wrl'
            elif re.search("\.dae$",lc_filename):
                format = 'dae'
            elif re.search("\.idtf$",lc_filename):
                format = 'idtf'
            elif re.search("\.mol2$",lc_filename):
                format = 'mol2'
            else:
                format = str(format)
        if format=='unknown':
            if not quiet:
                print " Save-Warning: Unrecognized file type -- defaulting to PDB format."
            format='pdb'
        filename = _self.exp_path(filename)
        if format=='pdb': # standard PDB file 
            f=open(filename,"w")
            if f:
                st = ''
                try:
                    _self.lock(_self)
                    st = _cmd.get_pdb(_self._COb,"("+str(selection)+")",int(state)-1,0,
                                      str(ref),int(ref_state)-1,int(quiet))
                    if st != None:
                        r = DEFAULT_SUCCESS                    
                finally:
                    _self.unlock(r,_self=_self)
                f.write(st)
                f.close()
                if not quiet:
                    print " Save: wrote \""+filename+"\"."
        if format=='cif': # mmCIF
            with open(filename, "w") as f:
                st = get_cifstr(selection, state, int(quiet), _self=_self)
                f.write(st)
                r = DEFAULT_SUCCESS
                if not quiet:
                    print " Save: wrote \""+filename+"\"."
        elif format=='aln':
            st = ''
            try:
                _self.lock(_self)
                st = _cmd.get_seq_align_str(_self._COb,str(selection),int(state)-1,0,int(quiet))
                if st != None:
                    r = DEFAULT_SUCCESS
            finally:
                _self.unlock(r,_self)
            if st!=None:
                f=open(filename,"w")
                f.write(st)
                f.close()
                if not quiet:
                    print " Save: wrote \""+filename+"\"."
            else:
                r = DEFAULT_ERROR
        elif format=='fasta':
            st = _self.get_fastastr(selection)
            if st != None:
                r = DEFAULT_SUCCESS
                f=open(filename,"w")
                f.write(st)
                f.close()
                if not quiet:
                    print " Save: wrote \""+filename+"\"."
            else:
                r = DEFAULT_ERROR
        elif format=='pqr': # PQR (modified PDB file)
            f=open(filename,"w")
            if f:
                st = ''
                try:
                    _self.lock(_self)
                    st = _cmd.get_pdb(_self._COb,"("+str(selection)+")",int(state)-1,1,
                                      str(ref),int(ref_state)-1,int(quiet))
                    if st != None:
                        r = DEFAULT_SUCCESS
                finally:
                    _self.unlock(r,_self)
                f.write(st)
                f.close()
                if not quiet:
                    print " Save: wrote \""+filename+"\"."
        elif format=='pkl': # python binary
            io.pkl.toFile(_self.get_model(selection,state,ref,ref_state),filename)
            r = DEFAULT_SUCCESS
            if not quiet:
                print " Save: wrote \""+filename+"\"."
        elif format=='pkla': # ascii override
            io.pkl.toFile(_self.get_model(selection,state,ref,ref_state),filename,bin=0)
            r = DEFAULT_SUCCESS
            if not quiet:
                print " Save: wrote \""+filename+"\"."
        elif format=='pse': # PyMOL session
            filename = filename.replace("\\","/") # always use unix-like path separators	
            _self.set("session_file",filename,quiet=1)
            if '(' in input_selection: # ignore selections 
                input_selection=''
            if not quiet:
                print " Save: Please wait -- writing session file..."
            session = _self.get_session(input_selection, partial, quiet)
            contents = cPickle.dumps(session, 1)
            with (gzip.open if do_gzip else open)(filename, 'wb') as handle:
                handle.write(contents)
            r = DEFAULT_SUCCESS
            if not quiet:
                print " Save: wrote \""+filename+"\"."
        elif format=='mmod': # macromodel
            io.mmd.toFile(_self.get_model(selection,state,ref,ref_state),filename)
            r = DEFAULT_SUCCESS
            if not quiet:
                print " Save: wrote \""+filename+"\"."
        elif format == 'xyz':
            state = int(state)
            buf = []
            for i, (selection, state) in enumerate(
                    pymol.selecting.objsele_state_iter(selection, state)):
                n_atoms_i = len(buf)
                buf.append('') # natoms (deferred)
                buf.append('') # comment
                n = _self.iterate_state(state, selection,
                        '_buf.append("%s %f %f %f" % (elem, x, y, z))',
                        space={'_buf': buf})
                buf[n_atoms_i] = str(n)
            with open(filename, 'w') as handle:
                print >> handle, '\n'.join(buf)
            if not quiet:
                print " Save: wrote %d states to \"%s\"." % (i + 1, filename)
        elif format=='sdf':
            state = int(state)
            sdf = SDF(filename,'w')
            for i, (selection, state) in enumerate(
                    pymol.selecting.objsele_state_iter(selection, state)):
                rec = SDFRec(io.mol.toList(_self.get_model(selection,state,ref,ref_state))
                             + ["$$$$\n"])
                sdf.write(rec)
            r = DEFAULT_SUCCESS
            if not quiet:
                print " Save: wrote %d states to \"%s\"." % (i + 1, filename)
        elif format=='mol':
            io.mol.toFile(_self.get_model(selection,state,ref,ref_state),filename)
            r = DEFAULT_SUCCESS
            if not quiet:
                print " Save: wrote \""+filename+"\"."
        elif format=="mol2":
            state = int(state)
            recList = []
            entrycount = 0
            for osele, ostate in pymol.selecting.objsele_state_iter(selection, state):
                    assign_atom_types(osele, "mol2", ostate, 1, _self)
                    recList.extend(io.mol2.toList(_self.get_model(osele,
                        ostate, ref, ref_state), selection=osele, state=ostate))
                    entrycount += 1
            m = MOL2(cmd=cmd)
            m.strToFile(recList,filename)
            r = DEFAULT_SUCCESS
            if not quiet:
                print ' Save: wrote %d entries to "%s".' % (entrycount, filename)
        elif format=='png':
            r = _self.png(filename,quiet=quiet)
        # refactor below to lift repeated code
        elif format=='pov':
            tup = _self.get_povray()
            f=open(filename,"w")
            f.write(tup[0])
            f.write(tup[1])
            f.flush()
            f.close()
            if not quiet:
                print " Save: wrote \""+filename+"\"."
            r = DEFAULT_SUCCESS
        elif format=='obj':
            tup = _self.get_mtl_obj()
            f=open(filename,"w")
            f.write(tup[1])
            f.flush()
            f.close()
            r = DEFAULT_SUCCESS
        elif format=='mtl':
            tup = _self.get_mtl_obj()
            f=open(filename,"w")
            f.write(tup[0])
            f.flush()
            f.close()
            r = DEFAULT_SUCCESS
        elif format=='wrl':
            txt = _self.get_vrml()
            f=open(filename,"w")
            f.write(txt)
            f.flush()
            f.close()
            if not quiet:
                print " Save: wrote \""+filename+"\"."
            r = DEFAULT_SUCCESS
        elif format=='dae':
            txt = _self.get_collada()
            if txt:
                with open(filename, "w") as f:
                    f.write(txt)
                if not quiet:
                    print " Save: wrote \""+filename+"\"."
                r = DEFAULT_SUCCESS
            elif not quiet:
                print " COLLADA export failed, no file written"
        elif format=='idtf':
            tup = _self.get_idtf()
            f=open(filename,"w")
            f.write(tup[0]);
            f.write(tup[1]);
            f.flush()
            f.close()
            if not quiet:
                fov = float(cmd.get("field_of_view"))
                dist = cmd.get_view()[11]
                print " 3Daac=%3.1f, 3Droll=0, 3Dc2c=0 0 1, 3Droo=%1.2f, 3Dcoo=0 0 %1.2f"%(fov,-dist,dist)
                print " Save: wrote \""+filename+"\"."
            r = DEFAULT_SUCCESS
            
        if _self._raising(r,_self): raise QuietException
        return r