Exemple #1
0
def data_from_sdf(sdf_file_path):

    mol_dict = {}

    row_id_list = []
    row_id_dict = {}
    
    col_id_list = []
    col_id_dict = {}

    # first pass, load the identifiers, MOL files, and tag names

    col = 0
    sdf = SDF(sdf_file_path)
    while 1:
        rec = sdf.read()
        if not rec:
            break
        mol = rec.get('MOL')

        # get the unique identifier
        mol_id = mol[0].strip()

        # store the MOL record
        mol_dict[mol_id] = ''.join(mol)
        
        # add row (assuming mol_id is unique)
        row_id_list.append(mol_id)
        row_id_dict[mol_id] = None
        
        # add column (if new)
        for key in rec.kees:
            if key != 'MOL':
                if key not in col_id_dict:
                    col_id_list.append(key)
                    col_id_dict[key] = None
        
    # second pass, read the actual data into the table structure

    content = {}
    
    sdf = SDF(sdf_file_path)
    while 1:
        rec = sdf.read()
        if not rec:
            break
        mol_id = rec.get('MOL')[0].strip()

        for key in rec.kees:
            if key != 'MOL':
                content[ (mol_id,key) ] = rec.get(key)[0].strip()

    return {
        'content' : content,
        'row_id_list' : row_id_list,
        'col_id_list' : col_id_list,
        'mol_dict' : mol_dict
        }
def data_from_sdf(sdf_file_path):

    mol_dict = {}

    row_id_list = []
    row_id_dict = {}

    col_id_list = []
    col_id_dict = {}

    # first pass, load the identifiers, MOL files, and tag names

    col = 0
    sdf = SDF(sdf_file_path)
    while 1:
        rec = sdf.read()
        if not rec:
            break
        mol = rec.get('MOL')

        # get the unique identifier
        mol_id = mol[0].strip()

        # store the MOL record
        mol_dict[mol_id] = ''.join(mol)

        # add row (assuming mol_id is unique)
        row_id_list.append(mol_id)
        row_id_dict[mol_id] = None

        # add column (if new)
        for key in rec.kees:
            if key != 'MOL':
                if key not in col_id_dict:
                    col_id_list.append(key)
                    col_id_dict[key] = None

    # second pass, read the actual data into the table structure

    content = {}

    sdf = SDF(sdf_file_path)
    while 1:
        rec = sdf.read()
        if not rec:
            break
        mol_id = rec.get('MOL')[0].strip()

        for key in rec.kees:
            if key != 'MOL':
                content[(mol_id, key)] = rec.get(key)[0].strip()

    return {
        'content': content,
        'row_id_list': row_id_list,
        'col_id_list': col_id_list,
        'mol_dict': mol_dict
    }
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 load_annotated_sdf(filename, object=None, state=1, discrete=1, _self=cmd):
    pymol = _self._pymol
    cmd = _self

    # get object name from file prefix

    if object == None:
        object = re.sub(r"\.[sS][dD][fF]$", "", filename)

    # open the SD file

    inp_sdf = SDF(filename)

    # create a persistent place to store the annotations

    if not hasattr(pymol.session, 'annotation'):
        pymol.session.annotation = {}

    # create a state-indexed dictionary for this object

    state_dict = {}
    pymol.session.annotation[object] = state_dict

    while 1:

        # get next record

        sdf_rec = inp_sdf.read()

        # if at end of list, break out of loop
        if not sdf_rec: break

        # get the MOL portion of the record

        mol_list = sdf_rec.get('MOL')

        # load it into PyMOL

        cmd.read_molstr(string.join(mol_list, ''),
                        object,
                        state,
                        finish=0,
                        discrete=discrete)

        # populate with tuple containing ordered list of keys
        # and associated data dictionary

        anno_list = ["\\955" + object]
        for key in sdf_rec.kees:
            if (key != 'MOL'):
                data = sdf_rec.data[key]
                print key, data
                anno_list.append(
                    "  \\595%s: \\559%s" %
                    (key, string.join(map(string.strip, sdf_rec.data[key]))))
        state_dict[state] = anno_list

        # increment the state index

        state = state + 1

    if state > 1:
        cmd.zoom(object)
        cmd.finish_object(object)
def load_annotated_sdf(filename, object=None, state=1, discrete=1, _self=cmd):
    pymol=_self._pymol
    cmd=_self
    
    # get object name from file prefix

    if object==None:
        object = re.sub(r"\.[sS][dD][fF]$","",filename)

    # open the SD file

    inp_sdf = SDF(filename)

    # create a persistent place to store the annotations

    if not hasattr(pymol.session,'annotation'):
        pymol.session.annotation = {}

    # create a state-indexed dictionary for this object

    state_dict = {}
    pymol.session.annotation[object] = state_dict

    while 1:

        # get next record 

        sdf_rec = inp_sdf.read()

        # if at end of list, break out of loop
        if not sdf_rec: break

        # get the MOL portion of the record

        mol_list = sdf_rec.get('MOL')

        # load it into PyMOL

        cmd.read_molstr(''.join(mol_list),object,
                             state,finish=0,discrete=discrete)

        # populate with tuple containing ordered list of keys
        # and associated data dictionary

        anno_list = [ "\\955"+object ]
        for key in sdf_rec.kees:
            if (key!='MOL'):
                data = sdf_rec.data[key]
                print(key,data)
                anno_list.append("  \\595%s: \\559%s"%(
                    key,
                    ' '.join(map(str.strip, sdf_rec.data[key]))))
        state_dict[state] = anno_list

        # increment the state index 

        state = state + 1

    if state > 1:
        cmd.zoom(object)
        cmd.finish_object(object)
Exemple #7
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