def get_gromos_define( _bondedfile_): ''' reading GROMOS define forcefield format gb_ : bond ga_ : angle gi_ : wop - improper gd_ : dihedral eg. #define gb_12 ''' _dedic_ = {'b':'bond', 'a':'angle', 'i':'improper', 'd':'dihedral'} _define_ = {} for k in _dedic_.keys(): _define_[ _dedic_[k]] = {} with open(_bondedfile_, 'r') as indata: for j_line in indata: _line_ = j_line.split(';')[0].split() if _line_ and _line_[0][0] == '#': if _line_[0] == '#define': if _line_[1][0] == 'g': if _line_[1][2] == '_' and _line_[1][3].isdigit(): aux_dic = { _line_[1] : _line_[2:]} _define_[ _dedic_[ _line_[1][1]]].update( aux_dic) else: print('Whojojoooh...') elif _line_[0] == '#include': print(wrg_3( _line_[1] + ' skipped!')) else: print(wrg_3( str(_line_) + ' ??')) return _define_
def fileseeker(path=getcwd(), word='data', notw=None): '''seek data & destroy, returns a list of posible files, filtered by "word" criterion ''' list_of_files = [] if path == getcwd(): DIR = '.' else: DIR = path for (root, folder, filenames) in walk(DIR, topdown=True): for name in filenames: list_of_files.append(join(root, name)) files = [] for fs in range(len(list_of_files)): # Could implement "while not" and use the same list_of_files # with remove(list_of_files[fs]) _file_ = list_of_files[fs] if '/' in _file_ and word in _file_.split('/')[-1]: if notw <> None and notw in _file_.split('/')[-1]: pass else: files.append(_file_) if files == []: print wrg_3(" No file(s) found with " + word + " criterion---") return files
def get_topitp_line( _filename_, _ss_): ''' reading gromacs content lines spliting by the space between info ''' _verbose_ = True content_line = [] _define_ = {} # \* TODO: apply a method just in case that # some _startstrings_ are not there ?? with open(_filename_, 'r') as indata: read_flag = False ok_flag = True tag_not_found = True if _verbose_: print _ss_ for j_line in indata: # I just whant to read once the flag is on j_line_s0 = j_line.split(';')[0].split() if read_flag and j_line_s0: #if _verbose_: ### is beter to store and print outside the # cycle with just one if #print j_line_s0 _line_ = j_line_s0 # getting out comments and empty lines if len( _line_) <0: pass elif _line_[0][0] == '#': if _line_[0] == '#include': print( wrg_3( _line_[1] + ' skipped this time')) elif _line_[0] == '#define': _define_[_line_[1]] = _line_[2:] else: print wrg_3( str(_line_) + ' ??') elif _line_[0][0] == '[': print( ' '.join(_line_) + 'Checked!') if ' '.join(_line_) <> _ss_ : read_flag = False #print 'exit here 424' elif len( _line_) > 0: content_line.append( _line_) else: print('Ups... please raise an issue at GitHub ;)') elif j_line.lstrip().startswith( _ss_): if _verbose_: print( _ss_+' found!') read_flag = True tag_not_found = False if content_line == [] or tag_not_found: if '/' in _filename_: _filename_ = _filename_.split('/')[-1] pop_err_1( 'The {} section is missing on {} file'.format( _ss_ , _filename_) ) ok_flag = False return content_line, ok_flag, _define_
def launch_gui(): ''' launcher ''' print wrg_3('Before you start, make sure there are no comments', '(;) in the middle of a line of the input GROMACS files.', 'Data after this symbol are not taken into account.') MasterWin = Tk() prompt = Gro2Lam_GUI(master=MasterWin) # xl_App help_icon = PhotoImage(file=lib_path + "/img/help.ppm") entry_list_of_dicts = [{ 'title': 'File', 'cascade': (('Quit', MasterWin.quit), ) }, { 'title': 'Data File Creation', 'title_com': (prompt.swapbody, 1) }, { 'title': 'Input File Creation', 'title_com': (prompt.swapbody, 2) }, { 'title': 'Run', 'title_com': (prompt.swapbody, 3) }, { 'titlei': help_icon, 'cascade': ( ('User manual', showuserman), ('About', launch_about, prompt), ) }] createmenubar(MasterWin, entry_list_of_dicts) w = 460 h = 570 # get screen width and height ws = MasterWin.winfo_screenwidth() # width of the screen hs = MasterWin.winfo_screenheight() # height of the screen # calculate x and y coordinates for the Tk root window x = (ws / 6) - (w / 2) if x < 100: x = 100 y = (hs / 3) - (h / 2) if y < 40: y = 40 prompt.MAINVERTEX = [ws, hs, w, h, x, y] #print MAINVERTEX # set the dimensions of the screen # and where it is placed MasterWin.geometry('{:d}x{:d}+{:d}+{:d}'.format(*prompt.MAINVERTEX[2:])) prompt.mainloop() try: MasterWin.destroy() except TclError: pass
def write_list2file(filename, listofstrings): '''datafile maker''' plaintext = "" if type(listofstrings) == type([]): for strings in listofstrings: plaintext += strings + "\n" write_file(filename, plaintext) else: print wrg_3(" Wrong format list --- "), listofstrings
def write_listoflist2file(filename, listoflistsofstrings): '''datafile maker''' listofstrings = [] if type(listoflistsofstrings) == type([]): for rw in range(len(listoflistsofstrings)): row_text = "" for st in range(len(listoflistsofstrings[rw])): row_text += listoflistsofstrings[rw][st] + ' ' row_text = row_text[:-1] listofstrings.append(row_text) write_list2file(filename, listofstrings) else: print wrg_3(" Wrong format list --- ")
def get_gro_line(_filename_, _startstrings_, _i_=0): ''' reading gromacs content lines''' content_line = [] _ss_ = _startstrings_ # \* TODO: aply a metod just in case that # some _startstrings_ are not there with open(_filename_, 'r') as indata: read_flag = False #print _i_, _ss_[_i_], _ss_[_i_+1] for j_line in indata: if j_line.startswith(';'): pass if j_line.startswith('#include'): print wrg_3( j_line.rstrip('\n') + ' not included in this line\n') elif read_flag: _line_ = j_line.split(';')[0].split() if _ss_[_i_ + 1] <> '' and j_line.startswith(_ss_[_i_ + 1]): #print _ss_[_i_+1] + ' -exit-' break elif len(_line_) >= 2: #if _i_==7: print _line_ content_line.append(_line_) elif j_line.startswith(_ss_[_i_]): #print _ss_[_i_] read_flag = True if content_line == [] or not read_flag: if '/' in _filename_: _filename_ = _filename_.split('/')[-1] pop_err_1('The {} section is missing on {} file'.format( _ss_[_i_], _filename_)) return 0, read_flag else: return content_line, read_flag
def check_file_list(files_list, extensions=['*']): '''Check for input files integrity and extension''' finam = '' try: for x in range(len(files_list)): finam = files_list[x].split('/')[-1] fi = open(files_list[x], 'r') fi.close() ext = finam.split('.')[-1] if extensions <> ['*'] and not ext in extensions: print extensions print wrg_3(' Invalid format: < ' + ext + ' >') return False return True except IOError: if finam == '': print wrg_3(" Select a file --- ") else: print wrg_3(' No such file or directory: ' + finam) return False
def extract_gromacs_data( _data_files_, _autoload_): ''' data files ---> ['gro file', 'top file', 'forcefield', 'non bonded file', 'bonded file']''' # _water_names_ filename_gro = _data_files_[0] filename_top = _data_files_[1] filename_ff = _data_files_[2] filename_nb = _data_files_[3] filename_bon = _data_files_[4] data_container = {} data_container['define'] = {} #_solvated_f_, _autoload_= _ck_buttons_ print 'Autoload: {}\n'.format( _autoload_) if not _autoload_: print filename_ff # or not _sidemol_f_ = False ########################################################################### ########################################################################### section = '''--------------- FILE GRO ----------------------''' #=========================================================================# ok_flag, gro_pack, b_xyz = get_gro_fixed_line( filename_gro) if not ok_flag: pop_err_1('Problem detected in :\n' + section) return {}, [ ok_flag, _sidemol_f_] _mol_, _mtype_, _type_, _xyz_, _mtypes_ = gro_pack ################# ------------ BOX DEF ------------- ################## data_container['box'] = [[],[]] b_xyz = [ x_y_z*10 for x_y_z in b_xyz ] angles = [] Ar = [[0,0,0],[0,0,0],[0,0,0]] for i in range(3): Ar[i][i] = b_xyz[i] if sum( b_xyz) < 2.8: exit('xx/0 Error in .gro file, box dimension 000') elif len( b_xyz) == 3: pass elif len( b_xyz) == 9: k = 0 for i in range(3): for j in range(3): if i <> j: Ar[i][j] = b_xyz[ k + 3] k += 1 cero = 1e-12 if Ar[1][0] < cero or Ar[2][0] < cero or Ar[2][1] < cero: print('Your triclinic cell will be rotated to make it!') # y rotation a_tor_y = -arcos( (Ar[0][0])/(raiz(Ar[0][0]*Ar[0][0]+Ar[2][0]*Ar[2][0])) ) Ar = rotate( Ar, a_tor_y, 'y') # z rotation a_tor_z = arcos( (Ar[0][0])/(raiz(Ar[0][0]*Ar[0][0]+Ar[1][0]*Ar[1][0])) ) Ar = rotate( Ar, a_tor_z, 'z') a_tor_x = arcos( Ar[1][1]/( raiz( Ar[1][1]*Ar[1][1] + Ar[2][1]*Ar[2][1])) ) Ar = rotate( Ar, a_tor_x) _xyz_ = rotate( rotate( rotate( _xyz_, a_tor_y, 'y'), a_tor_z, 'z'), a_tor_x) else: exit('xx/0 Error box dimension 001') _x_, _y_, _z_ = _xyz_ xlo = min( _x_)*10 xhi = xlo + Ar[0][0] ylo = min( _y_)*10 yhi = ylo + Ar[1][1] zlo = min( _z_)*10 zhi = zlo + Ar[2][2] data_container['box'][0] = [ xlo, xhi, ylo, yhi, zlo, zhi] data_container['box'][1] = [ Ar[0][1], Ar[0][2], Ar[1][2]] data_container['atomsdata'] = [ _mol_, _mtypes_, _type_, _xyz_, _mtype_] ########################################################################### ########################################################################### ########################################################################### section = '''---------------- .FILE TOP. ---------------''' #=========================================================================# ################# Defaults ################## data_container['defaults'], ok_flag, _a_fff_ = ck_forcefield( filename_ff, filename_top) filename_ff = _a_fff_ if not ok_flag: pop_err_1('Problem detected in :\n' + section.split('.')[1]) return {}, [ ok_flag, _sidemol_f_] buckorlj = int(data_container['defaults'][0]) ############ startstrings = ['[ moleculetype ]', '[ atoms ]', '[ bonds ]', '[ pairs ]', '[ angles ]', '[ dihedrals ]', '[ system ]', '[ molecules ]', ''] exclusions_ = ['[ bonds ]', '[ pairs ]', '[ angles ]', '[ dihedrals ]'] # Scheme type???? pure_side_mol_flag = ( ( seek_for_directive( [ filename_top], 'moleculetype') == '') or ( filename_nb == filename_ff and filename_nb == filename_bon)) if pure_side_mol_flag: startstrings = startstrings[-3:] print wrg_3( 'Using pure side molecule scheme') #n_atoms = 0 #n_bonds = 0 #n_angles = 0 data_container['atoms'] = [] data_container['bonds'] = [] data_container['angles'] = [] data_container['dihedrals'] = [] for ti in range(len(startstrings))[:-1]: s_str_ = startstrings[ ti][ 2:-2] ''' here is possible to insert a selector in case pairs and others can be obviated''' data_container[ s_str_], ok_flag, _ = get_topitp_line( filename_top, startstrings[ti] ) if not ok_flag: if startstrings[ti] not in exclusions_: print wrg_3( 'Not ok flag in <extract_gromacs_data> top file' + 'section, in ' + s_str_) return {}, [ ok_flag, _sidemol_f_] else: ok_flag = True #debugger_file( s_str_, data_container[s_str_]) n_atoms = len( data_container['atoms']) n_bonds = len( data_container['bonds']) n_angles = len( data_container['angles']) ########################################################################### section = '''---------- .SIDE MOLE FILES. -------------''' #=========================================================================# #### re-search in topology for new molecules / side molecules if _autoload_: data_container, ok_flag, _sidemol_f_ = sidemol_data( filename_top, data_container) if not ok_flag: pop_err_1( 'Problem detected in :\n' + section.split('.')[1]) return {}, [ ok_flag, _sidemol_f_] ########################################################################### section = '''----------------- .FILE NB. ---------------''' #=========================================================================# startstrings = ['[ atomtypes ]', '[ nonbond_params ]'] data_container['atomtypes'], ok_flag, _ = get_topitp_line( filename_nb, '[ atomtypes ]') if not ok_flag: pop_err_1('Problem detected in :\n' + section.split('.')[1]) return {}, [ ok_flag, _sidemol_f_] n_atomtypes = len( data_container['atomtypes']) #debugger_file( 'atomtypes',data_container['atomtypes']) ########################################################################### section = '''---------------- .FILE BON. ---------------''' #=========================================================================# startstrings = ['[ bondtypes ]', '[ angletypes ]', '[ dihedraltypes ]', ''] if filename_nb == filename_ff and filename_nb == filename_bon: for bi in range( len( startstrings))[:-1]: s_str_ = startstrings[ bi][ 2:-2] data_container[ s_str_] = [] data_container['define'][s_str_[:-5]] = {} #data_container['impropers'] = [] #data_container['impropertypes'] = [] startstrings = startstrings[-1] aux_strings = [ 'bonds', 'angles', 'dihedrals'] for bi in range( len( startstrings))[:-1]: s_str_ = startstrings[ bi][ 2:-2] _aux_here_ = get_topitp_line( filename_bon, startstrings[ bi]) data_container[ s_str_], ok_flag, _data_define_ = _aux_here_ data_container['define'][s_str_[:-5]] = _data_define_ #debugger_file(s_str_, data_container[s_str_]) if not ok_flag: if data_container[ aux_strings[ bi]] <> []: pop_err_1('Problem detected in :\n' + section.split('.')[1]) return {}, [ ok_flag, _sidemol_f_] else: ok_flag = True ########################################################################### section = '''------------ .#define & Impropers. ------------''' #=========================================================================# gromosff_flag = False data_container[ 'define'][ 'improper'] = {} aux_here = {} print( section.split('.')[1]) if filename_nb <> filename_ff and filename_nb <> filename_bon: print(" Is it GROMOS there ?? ") aux_here = get_gromos_define( filename_bon) else: print('no gromos check') for key_ in aux_here.keys(): if aux_here[ key_] <> {}: print ( 'GROMOS ' + key_ + ' kind detected!') data_container[ 'define'][ key_].update( aux_here[ key_]) gromosff_flag = True dihe_g_data = data_container[ 'dihedraltypes'] if 'dihedraltypes' == key_+'types' and dihe_g_data <> []: rewrite_flag = False for gd_ in range( len( dihe_g_data)): #print dihe_g_data[gd_][2] if dihe_g_data[gd_][2].isdigit(): if not rewrite_flag: print('Dihedral with 2 atoms re-formating to 4: ') rewrite_flag = True dihe_g_data[gd_] = ( [ 'X',] + dihe_g_data[ gd_][:2] + [ 'X',] + dihe_g_data[ gd_][2:]) print (dihe_g_data[ gd_]) if rewrite_flag: data_container[ 'dihedraltypes'] = dihe_g_data if gromosff_flag: for ss_ in startstrings[:-1]: s_str_ = ss_[ 2:-2] data_aux = data_container[ s_str_] cont_k = s_str_[ :-5] cddd = data_container[ 'define'][ cont_k] for i in range( len( data_aux)): if len( data_aux[i][-1].split('.')) < 2: if not data_aux[i][-1].isdigit(): aux = data_aux[i][:-1] + cddd[ data_aux[i][-1]] #print aux data_container[ s_str_][i] = aux #print data_container['define']['bond']['gb_33'] # Search for impropers in TOP and BON, using crossreference if needed data_container = split_define_dihe_impr( data_container) n_dihedrals = len( data_container['dihedrals']) n_impropers = len( data_container['impropers']) ########################################################################### '''-------------- "Side Mol" --------------''' #=========================================================================# n_atomsnew = len( _type_) if _sidemol_f_: ### A_02 maths # "previewing / preallocating" // computing side mol size sidemol = data_container['sidemol'] side_bonds_n = 0 side_angles_n = 0 side_dihed_n = 0 side_improp_n = 0 for sb in range( len( sidemol['tag'])): bonds_x_mol = len( sidemol['data'][sb]['bonds']) angles_x_mol = len( sidemol['data'][sb]['angles']) dihedr_x_mol = len( sidemol['data'][sb]['dihedrals']) improp_x_mol = len( sidemol['data'][sb]['impropers']) sm_quantity = sidemol['num'][sb] side_bonds_n += sm_quantity * bonds_x_mol side_angles_n += sm_quantity * angles_x_mol side_dihed_n += sm_quantity * dihedr_x_mol side_improp_n += sm_quantity * improp_x_mol n_bondsnew = n_bonds + side_bonds_n n_anglesnew = n_angles + side_angles_n n_dihednew = n_dihedrals + side_dihed_n n_impropnew = n_impropers + side_improp_n #print n_bonds, side_bonds_n, n_bonds + side_bonds_n #print n_angles, side_angles_n, n_angles + side_angles_n ### A_03 # tester in case is an asigment for define ore something like that contentkey = [ 'bond', 'angle', 'improper', 'dihedral'] for cont_k in contentkey: # memorandum: # 'define' stores in a contentkey dictionary each define key:value cddd = data_container[ 'define'][ cont_k] if cddd.keys() <> []: for sb in range( len( sidemol['tag'])): # in each side mol datacont = sidemol['data'][sb][cont_k+'s']# in its cont-key for dc in range( len( datacont)):# lets look their content if isnot_num( datacont[dc][-1]):# #print( '{} {} {}'.format( cont_k+'s', dc, # datacont[dc][-1])) aux = datacont[dc][:-1] + cddd[ datacont[dc][-1]] sidemol['data'][sb][cont_k+'s'][dc] = aux #else: #print datacont[dc] ####################################################################### ### A_04 # I think that this part is deprecated... however I am not sure # Regarding the itp format: # charges index 6 in data-atoms # opls names in index 1 # atom tags in index 4 _charge_ = {} _conv_dict_ = {} for sb in range( len( sidemol['tag'])): for at in range( len( sidemol['data'][sb]['atoms'])): a_opls_tag = sidemol['data'][sb]['atoms'][at][1] a_elem_tag = sidemol['data'][sb]['atoms'][at][4] a_charge = float( sidemol['data'][sb]['atoms'][at][6]) _charge_[a_opls_tag] = a_charge _conv_dict_[ a_elem_tag] = a_opls_tag print '='*45+'\n'+'='*5+' Charges found: ' print _charge_ print _conv_dict_ data_container['S_charge'] = _charge_ data_container['S_translation'] = _conv_dict_ ####################################################################### ### A_05 ############ Esoteric part ;) ############### #### ----------- DEFINING BONDED INTERACTIONS ---------- #### # load the side molecules data if exist #sidemol = _topodata_['sidemol'] smol_extra_bondtypes = [] smol_extra_angletypes = [] smol_extra_dihedraltypes = [] smol_extra_impropertypes = [] bn_namelist = [] an_namelist = [] di_namelist = [] im_namelist = [] for sb in range( len( sidemol['tag'])): _smd_ = sidemol['data'][sb] _at_dic_here = {} for _at in range( len( _smd_['atoms'])): _smat_ = _smd_['atoms'][_at] _at_dic_here[ _smat_[0]] = _smat_[1] for _bn in range( len( _smd_['bonds'])): _smbn_ = _smd_['bonds'][_bn] aux_here = [_at_dic_here[ _smbn_[0]], _at_dic_here[ _smbn_[1]]] name = '{}-{}'.format(*aux_here) if name not in bn_namelist and len( _smbn_[2:]) > 1: bn_namelist.append( name) smol_extra_bondtypes.append( aux_here + _smbn_[2:]) for _an in range( len( _smd_['angles'])): _sman_ = _smd_['angles'][_an] aux_here = [_at_dic_here[ _sman_[0]], _at_dic_here[ _sman_[1]], _at_dic_here[ _sman_[2]] ] name = '{}-{}-{}'.format(*aux_here) if name not in an_namelist and len( _sman_[3:]) > 1: an_namelist.append( name) smol_extra_angletypes.append( aux_here + _sman_[3:]) for _dh in range( len( _smd_['dihedrals'])): _smdh_ = _smd_['dihedrals'][_dh] aux_here = [_at_dic_here[ _smdh_[0]], _at_dic_here[ _smdh_[1]], _at_dic_here[ _smdh_[2]], _at_dic_here[ _smdh_[3]]] name = '{}-{}-{}-{}'.format(*aux_here) if name not in di_namelist and len( _smdh_[4:]) > 1: di_namelist.append( name) smol_extra_dihedraltypes.append( aux_here + _smdh_[4:]) for _im in range( len( _smd_['impropers'])): _smim_ = _smd_['impropers'][_im] aux_here = [_at_dic_here[ _smim_[0]], _at_dic_here[ _smim_[1]], _at_dic_here[ _smim_[2]], _at_dic_here[ _smim_[3]]] name = '{}-{}-{}-{}'.format(*aux_here) if name not in im_namelist and len( _smim_[4:]) > 1: im_namelist.append( name) smol_extra_impropertypes.append( aux_here + _smim_[4:]) if len( _smd_.keys()) > 5: print ('Uuupa!! This thing is not implemented yet' + ' as side mol part') a_key = [ 'atoms', 'bonds', 'angles', 'dihedrals', 'impropers'] for ky in _smd_.keys(): if ky not in a_key: print ('-- > this key : ' + ky) # --------- !!!! Update the info !!!! data_container['bondtypes'] = ( smol_extra_bondtypes + data_container['bondtypes'] ) data_container['angletypes'] = ( smol_extra_angletypes + data_container['angletypes']) data_container['dihedraltypes'] = ( smol_extra_dihedraltypes + data_container['dihedraltypes']) data_container['impropertypes'] = ( smol_extra_impropertypes + data_container['impropertypes']) #print(data_container['bondtypes']) else: n_bondsnew = n_bonds n_anglesnew = n_angles n_atomsnew = n_atoms n_dihednew = n_dihedrals n_impropnew = n_impropers ###################### trabajo # marker: 'bond_kinds'angl_kinds'dihe_kinds'impr_kinds' nice_list = [ 'bondtypes', 'angletypes', 'dihedraltypes','impropertypes'] for it in range( len( nice_list)): _aux_set_here = set() poss = it + 2 if poss > 4: poss = 4 for i in range( len ( data_container[ nice_list[it] ])): _aux_set_here.add( data_container[ nice_list[it] ][i][ poss ]) #print _aux_set_here data_container[ nice_list[it][:4]+'_kinds'] = _aux_set_here n_bondstypes = len( data_container['bondtypes']) n_anglestypes = len( data_container['angletypes']) n_dihedraltypes = len( data_container['dihedraltypes']) n_impropertypes = len( data_container['impropertypes']) data_container['numbers']={} data_container['numbers']['total'] = [n_atomsnew, n_bondsnew, n_anglesnew, n_dihednew, n_impropnew ] data_container['numbers']['type'] = [n_atomtypes, n_bondstypes, n_anglestypes, n_dihedraltypes, n_impropertypes] print 'Ending gromacs data parsing\n' return data_container, [ ok_flag, _sidemol_f_]