Deploy_0.9.0/isRNAcirc/src/IsRNAcirc.cpp

isRNAcirc / src / IsRNAcirc.cpp

isRNAcirc/src/IsRNAcirc.cpp · 75.7 KB

#include <iostream>
using namespace std;
#include <fstream> //printf()
#include <cstdlib> //atoi(), atof(), exit()
#include <iomanip> //setprecision()
#define _USE_MATH_DEFINES
#include <cmath>   //exp()
#include <sstream> //string
#include <vector>
#include <map>
#include <algorithm>
#include <thread>

#include "./header/int_to_string.h"
#include "./header/double_to_string.h"
#include "./header/char_to_string.h"
#include "./header/string_to_vector_string.h"
#include "./header/pdb_details.h"
#include "./header/measure_distance.h"
#include "./header/get_nucleic.h"
#include "./header/get_residue_info.h"
#include "./header/allatom_to_CG.h"
#include "./header/build_CG_topology.h"
#include "./header/FIT_RMSD.h"
#include "./header/CG_to_allatom.h"
#include "./header/format_PDB.h"
#include "./header/recover_missed_atom.h"

const int NP=1;
const double RMSDCUT=7.5;
string excluded_pdblist_file;

double randf(){ //get a random number of 0-1
   return (double)(rand()/(double)RAND_MAX);
}

int read_2D(string in2D, vector<string> &Vseq) {
   Vseq.clear();
   string sline;
   vector<string> stoken;
   ifstream inD (in2D.c_str());
   getline(inD,sline);
   stoken=string_to_vector_string(sline,0);
   sline="";
   for(int ii=0;ii<stoken.size();ii++)
     sline+=stoken[ii];
   string seq="";
   for(int ii=0;ii<sline.size();ii++) {
     char nt=sline[ii];
     if(nt=='A'||nt=='a') seq+="A";
     else if(nt=='C'||nt=='c') seq+="C";
     else if(nt=='G'||nt=='g') seq+="G";
     else if(nt=='U'||nt=='u') seq+="U";
     else if(nt=='T'||nt=='t') seq+="U";
     else if(nt=='-') seq+="-";
     else {cout<<"ERROR: Not RNA sequence: "<<sline<<endl; return 1;}
   }
   getline(inD,sline);
   stoken=string_to_vector_string(sline,0);
   sline="";
   for(int ii=0;ii<stoken.size();ii++)
     sline+=stoken[ii];
   string sym="";
   for(int ii=0;ii<sline.size();ii++) {
     char ch=sline[ii];
     if(ch=='.'||ch=='('||ch==')'||ch=='['||ch==']'||ch=='{'||ch=='}'||ch=='<'||ch=='>')
       sym+=char_to_string(ch);
     else if(ch=='-')
       sym+="-";
     else {cout<<"ERROR: Not RNA 2D structure: "<<sline<<endl; return 1;}
   }
   inD.close(); inD.clear();
   int L0=0, R0=0;
   int L1=0, R1=0;
   int L2=0, R2=0;
   int L3=0, R3=0;
   for(int jj=0;jj<sym.size();jj++) {
     char ch=sym[jj];
     if(ch=='(') L0++;
     else if(ch==')') R0++;
     else if(ch=='[') L1++;
     else if(ch==']') R1++;
     else if(ch=='{') L2++;
     else if(ch=='}') R2++;
     else if(ch=='<') L3++;
     else if(ch=='>') R3++;
   }
   if(L0!=R0 || L1!=R1 || L2!=R2 || L3!=R3)
     {cout<<"ERROR: Wrong 2D structure: "<<sline<<endl; return 1;}

   if(seq.size()!=sym.size())
     {cout<<"ERROR: Sequence and 2D sructure is not matched: "<<endl<<seq<<endl<<sym<<endl; return 1;}
   Vseq.push_back(seq);
   Vseq.push_back(sym);

   int checkCH=-1;
   string tsym=sym;
   while(tsym.find("-")!=string::npos) {
     int found=tsym.find_first_of("-");
     tsym.replace(found,1," ");
   }
   stoken=string_to_vector_string(tsym,0);
   int nc=stoken.size();
   if(tsym.size()>1) checkCH=0;
   for(int jj=0;jj<stoken.size();jj++){
     int n1=count(stoken[jj].begin(),stoken[jj].end(),'(');
     int n2=count(stoken[jj].begin(),stoken[jj].end(),')');
     if(n1==n2) checkCH++;
   }
   if((sym.find("[[")!=string::npos&&sym.find("]]")!=string::npos) ||
      (sym.find("{{")!=string::npos&&sym.find("}}")!=string::npos) ||
      (sym.find("<<")!=string::npos&&sym.find(">>")!=string::npos)) {
     string sym1="";
     string sym2="";
     for(int jj=0;jj<sym.size();jj++) {
       char ch=sym[jj];
       if(ch=='.') {sym1+="."; sym2+=".";}
       else if(ch=='-') {sym1+="-"; sym2+="-";}
       else if(ch=='('||ch==')') {sym1+=char_to_string(ch); sym2+=".";}
       else {sym1+="."; sym2+=char_to_string(ch);}
     }
     Vseq.push_back(sym1);
     Vseq.push_back(sym2);
   }

   return 0;
}

int read_PDBs(string inPDB, string Rseq, vector<vector<string> > &VVatoms, int type) {
   string seq="";
   for(int jj=0;jj<Rseq.size();jj++) {
     if(Rseq[jj]=='-') continue;
     else seq+=char_to_string(Rseq[jj]);
   }
   VVatoms.clear();

   vector<string> Vseq;
   vector<vector<string> > VVpdbs;
   
   if(get_nucleic(inPDB,VVpdbs,Vseq)) return 1;
   
   int nn = inPDB.find_last_of("/");
   string pdbname = inPDB.substr(nn+1);
   for(int jj=0;jj<Vseq.size();jj++) {
     if(Vseq[jj].size()!=seq.size()) {
       cout<<"ERROR: sequence size of model #"<<jj+1<<" in file "<<pdbname<<" is not equal to that of the given sequence"<<endl;
       cout<<seq<<endl<<Vseq[jj]<<endl;
       return 1;
     }
     if(Vseq[jj]!=seq&&type==1) {
       cout<<"Warning: sequence of model #"<<jj+1<<" in file "<<pdbname<<" is not the same as the given sequence"<<endl;
       cout<<seq<<endl<<Vseq[jj]<<endl;
     }
   }
   
   for(int jj=0;jj<VVpdbs.size();jj++) {
     vector<string> Vpdb=VVpdbs[jj];
     if(recover_missed_atom(Vpdb,Rseq,0)) return 1;
     if(type) {
       vector<string> Vcg;
       map<string,string> mapNTID;
       allatom_to_cg(Vpdb,Vcg,mapNTID,0);
       VVatoms.push_back(Vcg);
     }
     else
       VVatoms.push_back(Vpdb);
   }

   if(VVatoms.size()==0 || VVatoms[0].size()==0)
     {cout<<"ERROR: Read initial structure failed: "<<inPDB<<endl; return 1;}

   return 0;
}

int get_initial_structures_vfold3D(string INPUT, string outDIR, string Name, vector<string> Vseq, vector<vector<string> > &VVatoms) {
   int Nmax=3;
   string seq=Vseq[0];
   VVatoms.clear();
   if(outDIR.back()=='/') outDIR.pop_back();

   time_t start0, end0;
   time (&start0);

   string f2d=outDIR+"/"+Name+"_vfold.2d";
   string fmtf=outDIR+"/"+Name+"_vfold3D.mtf";
   string fpdb=outDIR+"/"+Name+"_vfold3D-INI.pdb";
   string ferr=outDIR+"/"+Name+"_vfold3D.err";
   string fstr=outDIR+"/"+Name+"_vfold3D.log";
   ofstream outL (fstr.c_str(),ios::app);

   ofstream outS (f2d.c_str());
   outS<<seq<<endl;
   outS<<Vseq[1]<<endl;
   outS.close(); outS.clear();

   fstr=outDIR+"/log.vfold3D";
   string cmd=INPUT+"/vfold3D/vfold3D_motif.o "+f2d+" "+fmtf+" "+ferr+" 0";
   outL<<cmd<<endl;
   cmd+=" > "+fstr;
   system(cmd.c_str());
   string sline;
   int check=0;
   ifstream inL (fstr.c_str());
   while(getline(inL,sline)) {
     outL<<"  "<<sline<<endl;
     if(sline.find("ERROR:")!=string::npos) check=1;
   }
   inL.close(); inL.clear();
   if(check) return 1;
   outL<<endl;

   cmd=INPUT+"/vfold3D/vfold3D_pdb.o "+INPUT+" "+f2d+" "+fmtf+" "+fpdb+" "+ferr+" 0 "+" "+excluded_pdblist_file;
   outL<<cmd<<endl;
   cmd+=" > "+fstr;
   system(cmd.c_str());
   check=0;
   inL.open(fstr.c_str());
   while(getline(inL,sline)) {
     outL<<"  "<<sline<<endl;
     if(sline.find("ERROR:")!=string::npos) check=1;
   }
   inL.close(); inL.clear();
   if(check) return 1;
   outL<<endl;

   time (&end0);
   outL<<"It took "<<double(difftime(end0,start0))<<" seconds to get initial structures by Vfold3D."<<endl;
   outL.close(); outL.clear();

   vector<vector<string> > VVpdbs;
   if(read_PDBs(fpdb,seq,VVpdbs,0)) return 1;

   fpdb=outDIR+"/"+Name+"_vfold3D.pdb";
   ofstream outP (fpdb.c_str());

   for(int ii=0;ii<VVpdbs.size();ii++) {
     vector<string> Vcg;
     map<string,string> mapNTID;
     allatom_to_cg(VVpdbs[ii],Vcg,mapNTID,0);
     if(ii==0) {
       VVatoms.push_back(Vcg);
       outP<<"MODEL     "<<VVatoms.size()<<endl;
       for(auto str : VVpdbs[ii])
         outP<<str<<endl;
       outP<<"ENDMDL"<<endl;
       continue;
     }
     vector<double> Vxyz_tar;
     for(int jj=0;jj<Vcg.size();jj++) {
       vector<string> stoken=string_to_vector_string(Vcg[jj],0);
       for(int kk=5;kk<8;kk++)
         Vxyz_tar.push_back(stod(stoken[kk]));
     }
     check=0;
     for(int ll=0;ll<VVatoms.size();ll++) {
       vector<double> Vxyz_ref;
       for(int jj=0;jj<VVatoms[ll].size();jj++) {
         vector<string> stoken=string_to_vector_string(VVatoms[ll][jj],0);
         for(int kk=5;kk<8;kk++)
           Vxyz_ref.push_back(stod(stoken[kk]));
       }
       double rmsd=RMSD_vectors_rmsd(Vxyz_tar,Vxyz_ref);
       if(rmsd<=RMSDCUT)
         {check=1; break;}
     }
     if(check) continue;
     VVatoms.push_back(Vcg);
     outP<<"MODEL     "<<VVatoms.size()<<endl;
     for(auto str : VVpdbs[ii])
       outP<<str<<endl;
     outP<<"ENDMDL"<<endl;
     if(VVatoms.size()==Nmax) break;
   }
   outP.close(); outP.clear();

   return 0;
}

int get_initial_structures_vfoldLA(string INPUT, string outDIR, string Name, string seq, vector<vector<string> > &VVatoms) {
   int Nmax=3;
   VVatoms.clear();
   if(outDIR.back()=='/') outDIR.pop_back();

   time_t start0, end0;
   time (&start0);

   string f2d=outDIR+"/"+Name+"_vfold.2d";
   string fpdb=outDIR+"/"+Name+"_vfoldLA.pdb";
   string fstr=outDIR+"/"+Name+"_vfoldLA.log";
   ofstream outL (fstr.c_str(),ios::app);

   string f2dLA=outDIR+"/"+Name+"_vfoldLA-2Ds.2d";
   string cmd=INPUT+"/vfoldLA/vfold3D2_BPs.o "+f2d+" "+f2dLA+" 0";
   outL<<cmd<<endl;
   fstr=outDIR+"/log.vfoldLA";
   cmd+=" > "+fstr;
   system(cmd.c_str());
   string sline;
   int check=0;
   ifstream inL (fstr.c_str());
   while(getline(inL,sline)) {
     outL<<"  "<<sline<<endl;
     if(sline.find("ERROR:")!=string::npos) check=1;
   }
   inL.close(); inL.clear();
   outL<<endl;
   if(check) {
     return 1;
   }

   string fpdb0=outDIR+"/"+Name+"_vfoldLA-INI.pdb";
   cmd=INPUT+"/vfoldLA/vfold3D2_LA.o "+INPUT+" "+excluded_pdblist_file+" "+f2dLA+" "+fpdb0+" 0";
   outL<<cmd<<endl;
   cmd+=" > "+fstr;
   system(cmd.c_str());
   check=0;
   inL.open(fstr.c_str());
   while(getline(inL,sline)) {
     outL<<"  "<<sline<<endl;
     if(sline.find("ERROR:")!=string::npos) check=1;
   }
   inL.close(); inL.clear();
   outL<<endl;
   if(check) {
     return 1;
   }

   string fpdb1=outDIR+"/"+Name+"_vfoldLA-CLU.pdb";
   cmd=INPUT+"/vfoldLA/vfold3D2_cluster.o "+fpdb0+" "+fpdb1+" "+double_to_string(RMSDCUT)+" 0";
   outL<<cmd<<endl;
   cmd+=" > "+fstr;
   system(cmd.c_str());
   check=0;
   inL.open(fstr.c_str());
   while(getline(inL,sline)) {
     outL<<"  "<<sline<<endl;
     if(sline.find("ERROR:")!=string::npos) check=1;
   }
   inL.close(); inL.clear();
   outL<<endl;
   if(check) {
     return 1;
   }

   fpdb0=outDIR+"/"+Name+"_vfoldLA-MIN.pdb";
   cmd=INPUT+"/vfoldLA/vfold3D2_lammps1.o "+INPUT+" "+fpdb1+" "+int_to_string(Nmax)+" "+fpdb0+" "+outDIR+" 0";
   outL<<cmd<<endl;
   cmd+=" > "+fstr;
   system(cmd.c_str());
   check=0;
   inL.open(fstr.c_str());
   while(getline(inL,sline)) {
     outL<<"  "<<sline<<endl;
     if(sline.find("ERROR:")!=string::npos) check=1;
   }
   inL.close(); inL.clear();
   outL<<endl;
   if(check) {
     return 1;
   }

   cmd=INPUT+"/vfoldLA/vfold3D2_lammps.o "+INPUT+" "+fpdb0+" "+int_to_string(Nmax)+" "+fpdb+" "+outDIR+" 0";
   outL<<cmd<<endl;
   cmd+=" > "+fstr;
   system(cmd.c_str());
   check=0;
   inL.open(fstr.c_str());
   while(getline(inL,sline)) {
     outL<<"  "<<sline<<endl;
     if(sline.find("ERROR:")!=string::npos) check=1;
   }
   inL.close(); inL.clear();
   outL<<endl;
   if(check) {
     return 1;
   }

   time (&end0);
   outL<<"It took "<<double(difftime(end0,start0)/60.0)<<" mins to get initial structures by VfoldLA."<<endl;
   outL.close(); outL.clear();

   if(read_PDBs(fpdb,seq,VVatoms,1)) return 1;

   return 0;
}

double rcut0;
vector<string> cg_beads;
int write_CG_model(string outDIR, vector<vector<string> > Vallatoms, string coeffDIR, vector<string> Vseq, int type, double &dmax, string &restr)  {
   map<string,int> bondtype;
   map<int,string> bondcoeff;
   map<string,int> angletype;
   map<int,string> anglecoeff;
   map<string,int> dihedraltype;
   map<int,string> dihedralcoeff;
   map<int,string> mass;
   map<string,string> paircoeff;

   string sline;
   string filename=coeffDIR+"bond_coeff.dat";
   ifstream inB (filename.c_str());
   getline(inB,sline);
   int btype=1;
   while(getline(inB,sline)) {
     if(sline.find("#")!=string::npos) continue;
     vector<string> stoken=string_to_vector_string(sline,0);
     if(stoken.size()!=6) continue;
     string bname=stoken[0];
     string bcoeff="";
     for(int ii=1;ii<6;ii++)
       bcoeff+=stoken[ii]+" ";
     bondtype.insert(pair<string,int>(bname,btype));
     bondcoeff.insert(pair<int,string>(btype,bcoeff));
     btype++;
   }
   inB.close(); inB.clear();

   filename=coeffDIR+"mass.dat";
   ifstream inM (filename.c_str());
   getline(inM,sline);
   while(getline(inM,sline)) {
     vector<string> stoken=string_to_vector_string(sline,0);
     if(stoken.size()<3) continue;
     int mtype=stoi(stoken[0]);
     string mvalue=stoken[1];
     mass.insert(pair<int,string>(mtype,mvalue));
   }
   inM.close(); inM.clear();

   filename=coeffDIR+"angle_coeff.dat";
   ifstream inA (filename.c_str());
   if(inA.is_open()) {
     getline(inA,sline);
     int atype=1;
     while(getline(inA,sline)) {
       if(sline.find("#")!=string::npos) continue;
       vector<string> stoken=string_to_vector_string(sline,0);
       if(stoken.size()!=6) continue;
       string aname=stoken[0];
       string acoeff="";
       for(int ii=1;ii<6;ii++)
         acoeff+=stoken[ii]+" ";
       angletype.insert(pair<string,int>(aname,atype));
       anglecoeff.insert(pair<int,string>(atype,acoeff));
       atype++;
     }
     inA.close(); inA.clear();
   }

   filename=coeffDIR+"dihedral_coeff.dat";
   ifstream inD (filename.c_str());
   if(inD.is_open()) {
     getline(inD,sline);
     int dtype=1;
     while(getline(inD,sline)) {
       if(sline.find("#")!=string::npos) continue;
       vector<string> stoken=string_to_vector_string(sline,0);
       if(stoken.size()!=14)
         {cout<<"stoken.size()!=14 --> "<<stoken.size()<<" : "<<sline<<endl; continue;}
       string dname=stoken[0];
       string dcoeff="";
       for(int ii=1;ii<14;ii++)
         dcoeff+=stoken[ii]+" ";
       dihedraltype.insert(pair<string,int>(dname,dtype));
       dihedralcoeff.insert(pair<int,string>(dtype,dcoeff));
       dtype++;
     }
     inD.close(); inD.clear();
   }

   filename=coeffDIR+"pair_coeff.dat";
   ifstream inP (filename.c_str());
   if(inP.is_open()) {
     getline(inP,sline);
     rcut0=0.0;
     while(getline(inP,sline)) {
       if(sline.find("#")!=string::npos) continue;
       if(sline.size()<4) continue;
       vector<string> stoken=string_to_vector_string(sline,0);
       if(stoken.size()!=14)
         {cout<<"stoken.size()!=14 --> "<<stoken.size()<<" : "<<sline<<endl; continue;}
       string ptype=stoken[0]+" "+stoken[1];
       string pcoeff="";
       for(int ii=2;ii<14;ii++)
         pcoeff+=" "+stoken[ii];
       double rcut=stod(stoken[13]);
       if(rcut>rcut0) rcut0=rcut;
        if(paircoeff.count(ptype)==1) {
         cout<<"Repeated pair coeff --> "<<sline<<endl;
         paircoeff[ptype]=pcoeff;
         continue;
       }
       paircoeff.insert(pair<string,string>(ptype,pcoeff));
     }
     inP.close(); inP.clear();
   }
   
   if(bondcoeff.size()!=21) {cout<<"ERROR: Read parameters error --> bond_coeff "<<bondcoeff.size()<<" !=21"<<endl; return 1;}
   if(anglecoeff.size()!=16) {cout<<"ERROR: Read parameters error --> angle_coeff "<<anglecoeff.size()<<" !=16"<<endl; return 1;}
   if(dihedralcoeff.size()!=38) {cout<<"ERROR: Read parameters error --> dihedral_coeff "<<dihedralcoeff.size()<<" !=38"<<endl; return 1;}
   if(paircoeff.size()!=66) {cout<<"ERROR: Read parameters error --> pair_coeff "<<paircoeff.size()<<" !=66"<<endl; return 1;}
   if(mass.size()!=11) {cout<<"ERROR: Read parameters error --> mass "<<mass.size()<<" !=11"<<endl; return 1;}

   if(restr.size()==0) {
     restr=" 1";
   }
   else {
     vector<string> Vresid=string_to_vector_string(restr,0);
     map<int,int> resid_s_e;
     for(size_t ll=0;ll<Vresid.size();ll++) {
       string str=Vresid[ll];
       while(str.find(":")!=string::npos) {
         size_t found=str.find(":");
         str.replace(found,1," ");
       }
       vector<string> stoken=string_to_vector_string(str,0);
       int res_s=stoi(stoken[1]);
       int res_e=stoi(stoken[2]);
       resid_s_e.insert(pair<int,int>(res_s,res_e));
     }
     vector<int> ids;
     for(size_t ll=0;ll<Vallatoms[0].size();ll++) {
       vector<string> stoken=string_to_vector_string(Vallatoms[0][ll],0);
       int index=stoi(stoken[0]);
       int resid=stoi(stoken[2]);
       for(auto& it : resid_s_e) {
         if(resid>=it.first && resid <=it.second && count(ids.begin(),ids.end(),index)==0) 
           ids.push_back(index);
       }
     }
     restr=" "+to_string(ids[0])+":";
     for(size_t ll=1;ll<ids.size();ll++) {
       if((ids[ll]-ids[ll-1])==1) continue;
       restr+=to_string(ids[ll-1])+" "+to_string(ids[ll])+":";
     }
     restr+=to_string(ids.back());
   }
   
   
   string fname;
   if(type==0) fname="close";
   else fname="model";
   dmax=-1.0;
   for(int nn=0;nn<Vallatoms.size();nn++) {
     vector<string> outCG=Vallatoms[nn];

     if(nn==0 && type!=0) {
       string fstr=outDIR+fname+".cg";
       ofstream outD (fstr.c_str());
       for(int jj=0;jj<outCG.size();jj++)
         outD<<outCG[jj]<<endl;
       outD.close(); outD.clear();
     }

     vector<string> Bonds;
     vector<string> Angles;
     vector<string> Dihedrals;
     vector<string> Bends;
     vector<string> bonds_close;
     if(type==1) {
       string sym1=Vseq[1];
       if(build_cg_topology(outCG,Bonds,Angles,Dihedrals,sym1,0,Bends)) return 1;
     }
     else if(type==0) {
       if(Vseq.size()<3) {
         string sym1=Vseq[1];
         if(build_cg_topology(outCG,Bonds,Angles,Dihedrals,sym1,1,Bends)) return 1;
         for(int kk=0;kk<Bends.size();kk++) {
           string str="22 "+Bends[kk];
           bonds_close.push_back(str);
         }
       }
       else if(Vseq.size()==4) {
         string sym2=Vseq[2];
         if(build_cg_topology(outCG,Bonds,Angles,Dihedrals,sym2,1,Bends)) return 1;
         for(int kk=0;kk<Bends.size();kk++) {
           string str="22 "+Bends[kk];
           bonds_close.push_back(str);
         }
         string sym3=Vseq[3];
         vector<string> Vb,Va,Vd;
         Bends.clear();
         if(build_cg_topology(outCG,Vb,Va,Vd,sym3,1,Bends)) return 1;
         string BP_BOND[]={"4-11","5-9","6-10","7-9","6-9","6-11"};
         for(int kk=0;kk<Vb.size();kk++) {
           vector<string> stoken=string_to_vector_string(Vb[kk],0);
           string bname=stoken[4];
           if(bondtype.count(bname)==0) continue;
           int btype=bondtype[bname]+7;
           string str=to_string(btype)+" "+stoken[2]+" "+stoken[3];
           if(count(begin(BP_BOND),end(BP_BOND),bname)) bonds_close.push_back(str);
         }
       }
     }

     vector<string> Tbond=Bonds;
     Bonds.clear();
     int nbond=0;
     for(int ii=0;ii<Tbond.size();ii++) {
       vector<string> stoken=string_to_vector_string(Tbond[ii],0);
       string bname=stoken[4];
       string batom=stoken[2]+" "+stoken[3];
       if(bondtype.count(bname)==0) continue;
       int btype=bondtype[bname];
       nbond++;
       string str=to_string(nbond)+" "+to_string(btype)+" "+batom;
       Bonds.push_back(str);
     }
     if(type==0) {
       for(int jj=0;jj<bonds_close.size();jj++) {
         nbond++;
         string str=to_string(nbond)+" "+bonds_close[jj];
         Bonds.push_back(str);
       }
     }

     vector<string> Tangle=Angles;
     Angles.clear();
     int nangle=0;
     for(int ii=0;ii<Tangle.size();ii++) {
       vector<string> stoken=string_to_vector_string(Tangle[ii],0);
       string aname=stoken[5];
       string aatom=stoken[2]+" "+stoken[3]+" "+stoken[4];
       if(angletype.count(aname)==0) continue;
       int atype=angletype[aname];
       nangle++;
       string str=to_string(nangle)+" "+to_string(atype)+" "+aatom;
       Angles.push_back(str);
     }

     vector<string> Tdihedral=Dihedrals;
     Dihedrals.clear();
     int ndihedral=0;
     for(int ii=0;ii<Tdihedral.size();ii++) {
       vector<string> stoken=string_to_vector_string(Tdihedral[ii],0);
       string dname=stoken[6];
       string datom=stoken[2]+" "+stoken[3]+" "+stoken[4]+" "+stoken[5];
       if(dihedraltype.count(dname)==0) continue;
       int dtype=dihedraltype[dname];
       ndihedral++;
       string str=to_string(ndihedral)+" "+to_string(dtype)+" "+datom;
       Dihedrals.push_back(str);
     }

     filename=outDIR+"data."+fname+"."+int_to_string(nn+1);
     ofstream model (filename.c_str());

     double xlo=10000;
     double xhi=-10000;
     double ylo=10000;
     double yhi=-10000;
     double zlo=10000;
     double zhi=-10000;

     vector<string> Atomxyz;
     map<string,vector<double> > ID_xyz;
     char c_id0;
     for(int ii=0;ii<outCG.size();ii++) {
       vector<string> stoken=string_to_vector_string(outCG[ii],0);
       string atomid=stoken[0];
       if(ii==0) c_id0=stoken[1][0];
       int chainid=stoken[1][0]-c_id0;
       int resid=stoi(stoken[2]);
       int atomtype=stoi(stoken[4]);
       string xyz=stoken[5]+" "+stoken[6]+" "+stoken[7];
       string str=atomid;
       if(atomtype<=11)
         str+=" "+to_string(chainid)+" "+stoken[4]+" "+xyz;
       if(type!=0 && nn==0 && atomtype<=11) {
         string str=stoken[0]+" "+stoken[1]+" "+stoken[2]+" "+stoken[3]+" "+stoken[4];
         cg_beads.push_back(str);
       }
       Atomxyz.push_back(str);
       double x=stod(stoken[5]);
       double y=stod(stoken[6]);
       double z=stod(stoken[7]);
       vector<double> xyz1;
       xyz1.push_back(x);
       xyz1.push_back(y);
       xyz1.push_back(z);
       ID_xyz.emplace(atomid,xyz1);
       if(x<xlo) xlo=x;
       if(x>xhi) xhi=x;
       if(y<ylo) ylo=y;
       if(y>yhi) yhi=y;
       if(z<zlo) zlo=z;
       if(z>zhi) zhi=z;
     }
     xlo-=500;
     xhi+=500;
     ylo-=500;
     yhi+=500;
     zlo-=500;
     zhi+=500;

     if(type==0) {
       for(int jj=0;jj<bonds_close.size();jj++) {
         vector<string> stoken=string_to_vector_string(bonds_close[jj],0);
         string bi=stoken[1];
         string bj=stoken[2];
         if(ID_xyz.count(bi)==0 || ID_xyz.count(bj)==0) {
          cout<<"ID_xyz.count("<<bi<<")==0 || ID_xyz.count("<<bj<<")==0"<<endl;
          return 1;
         }
         double dx=ID_xyz[bi][0]-ID_xyz[bj][0];
         double dy=ID_xyz[bi][1]-ID_xyz[bj][1];
         double dz=ID_xyz[bi][2]-ID_xyz[bj][2];
         double r=sqrt(dx*dx+dy*dy+dz*dz);
         if(dmax<r) dmax=r;
       }
     }

     model<<"#RNA CG Model "<<filename<<endl;
     model<<Atomxyz.size()<<" atoms"<<endl;
     model<<nbond<<" bonds"<<endl;
     model<<nangle<<" angles"<<endl;
     model<<ndihedral<<" dihedrals"<<endl;
     model<<mass.size()<<" atom types"<<endl;
     if(type==0)
       model<<bondtype.size()+7<<" bond types"<<endl;
     else
       model<<bondtype.size()<<" bond types"<<endl;
     model<<angletype.size()<<" angle types"<<endl;
     model<<dihedraltype.size()<<" dihedral types"<<endl;
     model<<xlo<<"  "<<xhi<<" xlo xhi"<<endl;
     model<<ylo<<"  "<<yhi<<" ylo yhi"<<endl;
     model<<zlo<<"  "<<zhi<<" zlo zhi"<<endl;
     model<<endl;
     model<<"Atoms"<<endl<<endl;
     for(int jj=0;jj<Atomxyz.size();jj++) {
       model<<Atomxyz[jj]<<endl;
     }
     model<<endl;
     model<<"Bonds"<<endl<<endl;
     for(int jj=0;jj<Bonds.size();jj++)
       model<<Bonds[jj]<<endl;
     model<<endl;
     if(Angles.size()) {
       model<<"Angles"<<endl<<endl;
       for(int jj=0;jj<Angles.size();jj++)
         model<<Angles[jj]<<endl;
       model<<endl;
     }
     if(Dihedrals.size()) {
       model<<"Dihedrals"<<endl<<endl;
       for(int jj=0;jj<Dihedrals.size();jj++)
         model<<Dihedrals[jj]<<endl;
       model<<endl;
     }
     model<<"Bond Coeffs"<<endl<<endl;
     for(map<int,string>::iterator it=bondcoeff.begin(); it!=bondcoeff.end();it++) {
       model<<it->first<<" ";
       if(it->first>=16 && it->first<=21 && type==0) {
         vector<string> stoken=string_to_vector_string(it->second,0);
         double kb=stod(stoken[0]);
         model<<kb*0.01;
         for(int kk=1;kk<stoken.size();kk++) {
           if(kk==2) stoken[kk]="0.0";
           model<<" "<<stoken[kk];
         }
         model<<endl;
       }
       else {
         model<<it->second<<endl;
       }
     }
     if(type==0) {
       double BL0[]={3.9, 3.5, 3.6, 3.3, 3.4, 3.5, 3.8};
       for(int kk=0;kk<7;kk++)
         model<<bondcoeff.size()+1+kk<<" 0.001 "<<BL0[kk]<<" 0.0 3.75 0.2"<<endl;
     }
     model<<endl;
     model<<"Angle Coeffs"<<endl<<endl;
     for(auto& it : anglecoeff) {
       model<<it.first<<" "<<it.second<<endl;
     }
     model<<endl;
     model<<"Dihedral Coeffs"<<endl<<endl;
     for(auto& it : dihedralcoeff)
       model<<it.first<<" "<<it.second<<endl;
     model<<endl;
     model<<"PairIJ Coeffs"<<endl<<endl;
     for(auto& it : paircoeff)
       model<<it.first<<""<<it.second<<endl;
     model<<endl;
     model<<"Masses"<<endl<<endl;
     for(auto& it : mass)
       model<<it.first<<" "<<it.second<<endl;
     model.close(); model.clear();
   }

   return 0;
}

void write_MD_script(string outDIR, int nmodel, int Nstep, int Nevery, int type, string restr) {
   string fname;
   int T0;
   if(type==0) {
     fname="close"; 
     T0=500;
     int nloop=(int) nmodel/NP;
     int nlast=nmodel%NP;
     for(int jj=0;jj<=nloop;jj++) {
       if(jj==nloop && nlast==0) continue;
       string filename=outDIR+"in."+fname+"."+int_to_string(jj+1);
       ofstream script (filename.c_str());
       script<<"#LAMMPS Script for CGMD simulation"<<endl;
       script<<"units		        real"<<endl;
       script<<"dimension       3"<<endl;
       script<<"boundary        p p p"<<endl;
       script<<"atom_style	    molecular"<<endl;
       script<<"special_bonds   lj/coul 0.0 0.0 0.0 angle no dihedral no"<<endl;
       script<<endl;
       script<<"neighbor	      2.0 bin"<<endl;
       script<<"neigh_modify	  every 5 delay 5"<<endl;
       script<<endl;
       script<<"bond_style      harmonic/gauss"<<endl;
       script<<"angle_style     harmonic/gauss"<<endl;
       script<<"dihedral_style  fourier"<<endl;
       script<<"pair_style      morse/gauss2/lj9 "<<rcut0<<endl;
       script<<endl;
       script<<"variable        t world";
       if(jj<nloop) {
         for(int pp=0;pp<NP;pp++)
           script<<" "<<pp+1+jj*NP;
       }
       else {
         for(int pp=0;pp<nlast;pp++)
           script<<" "<<pp+1+nloop*NP;
       }
       script<<endl;
       script<<endl;
       script<<"read_data	      "<<outDIR<<"data."<<fname<<".$t"<<endl;
       script<<endl;
       script<<"thermo          "<<Nevery<<endl;
       script<<endl;
       script<<"log             "<<outDIR<<"log."<<fname<<".$t"<<endl;
       script<<endl;
       script<<"dump            1 all custom "<<Nevery<<" "<<outDIR<<"dump."<<fname<<".$t.lammpstrj id mol type x y z ix iy iz"<<endl;
       script<<endl;
       script<<"min_style       sd"<<endl;
       script<<"minimize        0.0 1.0e-6 20000 100000"<<endl;
       script<<endl;
       script<<"group           stat id"<<restr<<endl;
       script<<"group           other subtract all stat"<<endl;
       script<<endl;
       script<<"velocity        other create "<<T0<<" "<<37624+(int)(913240*randf())<<" rot yes dist gaussian"<<endl;
       script<<endl;
       int nstep=Nstep/5;
       double BL0[]={3.9, 3.5, 3.6, 3.3, 3.4, 3.5, 3.8};
       double K0[]={0.001, 0.01, 0.1, 1.0, 5.0};
       for(int kk=0;kk<5;kk++) {
         if(kk==2) {
           script<<"bond_coeff      16 0.2054 3.720 0.0 3.437 0.197"<<endl;
           script<<"bond_coeff      17 0.3369 3.678 0.0 3.532 0.201"<<endl;
           script<<"bond_coeff      18 0.2025 3.486 0.0 3.272 0.203"<<endl;
           script<<"bond_coeff      19 0.2329 3.599 0.0 3.361 0.229"<<endl;
           script<<"bond_coeff      20 0.1819 3.815 0.0 3.205 0.441"<<endl;
           script<<"bond_coeff      21 0.0814 3.817 0.0 3.875 0.360"<<endl;
         }
         else if(kk==4) {
           script<<"bond_coeff      16 2.054 3.720 -0.653 3.437 0.197"<<endl;
           script<<"bond_coeff      17 3.369 3.678 -0.283 3.532 0.201"<<endl;
           script<<"bond_coeff      18 2.025 3.486 -0.762 3.272 0.203"<<endl;
           script<<"bond_coeff      19 2.329 3.599 -0.981 3.361 0.229"<<endl;
           script<<"bond_coeff      20 1.819 3.815 -3.058 3.205 0.441"<<endl;
           script<<"bond_coeff      21 0.814 3.817 -1.201 3.875 0.360"<<endl;
         }
         for(int bb=0;bb<7;bb++) {
           script<<"bond_coeff      "<<bb+22<<" "<<K0[kk]<<" "<<BL0[bb]<<" 0.0 3.75 0.2"<<endl;
         }
         script<<endl;
         script<<"timestep	      0.1"<<endl;
         script<<endl;
         if(kk>0) script<<"unfix           myfix"<<endl;
         script<<"fix		          1 other langevin "<<T0-kk*50<<" "<<T0-kk*50<<" 1000.0 "<<57412+(int)(743891*randf())<<endl;
         if(kk==0) script<<"fix             2 other nve/limit 1"<<endl;
         script<<endl;
         if(kk==0) script<<"run             50000 upto"<<endl;
         else script<<"run             10000"<<endl;
         script<<endl;
         script<<"timestep	      1.0"<<endl;
         script<<endl;
         script<<"unfix           1"<<endl;
         if(kk==4)
           script<<"fix             myfix other langevin "<<T0-kk*50<<" "<<T0-kk*50<<" 1000.0 "<<83546+(int)(627043*randf())<<endl;
         else
           script<<"fix             myfix other langevin "<<T0-kk*50<<" "<<T0-(kk+1)*50<<" 1000.0 "<<83546+(int)(627043*randf())<<endl;
         script<<endl;
         script<<"run          "<<nstep<<endl;
         script<<endl;
       }

       script.close(); script.clear();
     }

     string fstr=outDIR+"close.log";
     ofstream outL (fstr.c_str());
     outL<<"Nstep: "<<Nstep+50000+10000*4<<endl;
     outL.close(); outL.clear();
   }
   else {
     fname="model"; 
     T0=280;
     for(int jj=0;jj<nmodel;jj++) {
       string filename=outDIR+"in."+fname+"."+int_to_string(jj+1);
       ofstream script (filename.c_str());
       script<<"#LAMMPS Script for CGMD simulation"<<endl;
       script<<"units		        real"<<endl;
       script<<"dimension       3"<<endl;
       script<<"boundary        p p p"<<endl;
       script<<"atom_style	    molecular"<<endl;
       script<<"special_bonds   lj/coul 0.0 0.0 0.0 angle no dihedral no"<<endl;
       script<<endl;
       script<<"neighbor	      2.0 bin"<<endl;
       script<<"neigh_modify	  every 5 delay 5"<<endl;
       script<<endl;
       script<<"bond_style      harmonic/gauss"<<endl;
       script<<"angle_style     harmonic/gauss"<<endl;
       script<<"dihedral_style  fourier"<<endl;
       script<<"pair_style      morse/gauss2/lj9 "<<rcut0<<endl;
       script<<endl;
       script<<"variable        t world";
       for(int pp=0;pp<NP;pp++)
         script<<" "<<T0+pp*20;
       script<<endl;
       script<<endl;
       script<<"read_data	      "<<outDIR<<"data."<<fname<<"."<<jj+1<<endl;
       script<<endl;
       script<<"thermo          "<<Nevery<<endl;
       script<<endl;
       script<<"log             "<<outDIR<<"log."<<fname<<"."<<jj+1<<".$t"<<endl;
       script<<endl;
       script<<"dump            1 all custom "<<Nevery<<" "<<outDIR<<"dump."<<fname<<"."<<jj+1<<".$t.lammpstrj id mol type x y z ix iy iz"<<endl;
       script<<endl;
       script<<"min_style       sd"<<endl;
       script<<"minimize        0.0 1.0e-6 20000 100000"<<endl;
       script<<endl;
       script<<"group           stat id"<<restr<<endl;
       script<<"group           other subtract all stat"<<endl;
       script<<endl;
       script<<"timestep	      0.1"<<endl;
       script<<endl;
       script<<"velocity        other create 300 "<<37624+(int)(913240*randf())<<" rot yes dist gaussian"<<endl;
       script<<"fix		          1 other langevin 300 298 1000.0 "<<57412+(int)(743891*randf())<<endl;
       script<<"fix             2 other nve/limit 1"<<endl;
       script<<endl;
       script<<"run             50000 upto"<<endl;
       script<<endl;
       script<<"timestep	      1.0"<<endl;
       script<<endl;
       script<<"unfix           1"<<endl;
       script<<"fix             myfix other langevin $t $t 1000.0 "<<83546+(int)(627043*randf())<<endl;
       script<<endl;
       script<<"run          "<<Nstep<<endl;
       
       script.close(); script.clear();
     }

     string fstr=outDIR+"REMD.log";
     ofstream outL (fstr.c_str());
     outL<<"Nstep: "<<Nstep+50000<<endl;
     outL.close(); outL.clear();
   }
}

void run_MD(string outDIR, string lmp, int nmodel, int type) {
   string flog=outDIR;
   if(type==0) {
     flog+="close.log";
     int nloop=(int) nmodel/NP;
     int nlast=nmodel%NP;
     int Nround=nloop;
     if(nlast>0) Nround+=1;
     for(int jj=0;jj<=nloop;jj++) {
       if(jj==nloop && nlast==0) continue;
       ofstream outL (flog.c_str(), ios::app);
       string cmd=lmp+" -in "+outDIR+"in.close."+int_to_string(jj+1);
       cout<<"  Round "<<jj+1<<"/"<<Nround<<": "<<cmd<<endl;
       outL<<"Round "<<jj+1<<"/"<<Nround<<": "<<endl;
       outL<<cmd<<endl;
       outL.close(); outL.clear();
       cmd+=" >> "+flog;
       system(cmd.c_str());
     }
   }
   else {
     flog+="REMD.log";
     for(int ii=1;ii<=nmodel;ii++) {
       ofstream outL (flog.c_str(), ios::app);
       string cmd=lmp+" -in "+outDIR+"in.model."+int_to_string(ii);
       cout<<"  Duplicate "<<ii<<"/"<<nmodel<<": "<<cmd<<endl;
       outL<<"Duplicate "<<ii<<"/"<<nmodel<<": "<<endl;
       outL<<cmd<<endl;
       outL.close(); outL.clear();
       cmd+=" >> "+flog;
       system(cmd.c_str());
     }
   }
}

bool cmp(string str1, string str2) {
   vector<string> stoken=string_to_vector_string(str1,0);
   int n=stoken.size();
   double eng1=stod(stoken[n-1]);
   stoken=string_to_vector_string(str2,0);
   n=stoken.size();
   double eng2=stod(stoken[n-1]);

   return eng1<eng2;
}

/////ps: Fraction $ps of snapshots collected; pe: top $pe structure with lowest energy for clustering
int read_structure(string inDIR, int nmodel, int Nstep, double ps, double pe, vector<vector<string> > &VVxyz, int type) {
   VVxyz.clear();

   int Nstart=round((1-ps)*Nstep);
   int Nstop=Nstep;
   string fname;
   
   if(type==0) {
     fname="close";
     Nstart+=90000;
     Nstop+=90000;

     ifstream ineng;
     ifstream inxyz;
     string sline;
     vector<string> stoken;

     for(int nn=1;nn<=nmodel;nn++) {
       vector<string> Senergy;
       string fstr=inDIR+"log."+fname+"."+int_to_string(nn);
       ineng.open(fstr.c_str());
       if(!ineng.is_open())
         {cout<<"ERROR: Open file failed: "<<fstr<<endl; return 1;}
       int flag=0;
       vector<int> Vstep;
       while(getline(ineng,sline)) {
         if(sline.find("Step")!=string::npos&&sline.find("E_pair")!=string::npos&&sline.find("E_mol")!=string::npos)
           {flag=1; continue;}
         if(sline.find("Loop")!=string::npos&&sline.find("time")!=string::npos&&sline.find("procs")!=string::npos)
           {flag=0; continue;}
         if(flag==1) {
           stoken=string_to_vector_string(sline,0);
           if(stoken.size()!=6) continue;
           if(stoken[0][0]<'0'||stoken[0][0]>'9') continue;
           int step=atoi(stoken[0].c_str());
           if(count(Vstep.begin(),Vstep.end(),step)==0)
             Vstep.push_back(step);
           else
             continue;
           if(step<Nstart||step>Nstop) continue;
           double E_pair=atof(stoken[2].c_str());
           double E_mol=atof(stoken[3].c_str());
           double E_pot=E_pair+E_mol;
           string str=int_to_string(nn)+" "+int_to_string(step)+" "+double_to_string(E_pot);
           Senergy.push_back(str);
         }
       }//while
       ineng.close(); ineng.clear();

       sort(Senergy.begin(),Senergy.end(),cmp);

       int ns=ceil(Senergy.size()*pe);
       map<string,double> energy;
       for(int jj=0;jj<ns;jj++) {
         stoken=string_to_vector_string(Senergy[jj],0);
         string step=stoken[0]+" "+stoken[1];
         double E_pot=stod(stoken[2]);
         if(energy.count(step)==0) {
           energy.insert(pair<string,double>(step,E_pot));
         }
       }

       fstr=inDIR+"dump."+fname+"."+int_to_string(nn)+".lammpstrj";
       inxyz.open(fstr.c_str());
       if(!inxyz.is_open())
         {cout<<"ERROR: Open file failed: "<<fstr<<endl; return 1;}
       while(getline(inxyz,sline)) {
         if(sline.find("TIMESTEP")!=string::npos){
           getline(inxyz,sline);
           stoken=string_to_vector_string(sline,0);
           int step=atoi(stoken[0].c_str());
           getline(inxyz,sline);
           getline(inxyz,sline);
           stoken=string_to_vector_string(sline,0);
           int natom=atoi(stoken[0].c_str());
           string Sstep=int_to_string(nn)+" "+int_to_string(step);
           if(step<Nstart||step>=Nstop||energy.count(Sstep)==0) {
             for(int jj=0;jj<natom+5;jj++)
               getline(inxyz,sline);
             continue;
           }
           getline(inxyz,sline);
           getline(inxyz,sline);
           getline(inxyz,sline);
           getline(inxyz,sline);
           getline(inxyz,sline);
           vector<string> Vxyz;
           Vxyz.resize(natom+1);
           double E_pot=energy[Sstep];
           string str="#Energy: "+double_to_string(E_pot);
           Vxyz[0]=str;
           for(int jj=0;jj<natom;jj++) {
             getline(inxyz,sline);
             stoken=string_to_vector_string(sline,0);
             int index=stoi(stoken[0]);
             string xyz=stoken[0]+" "+stoken[1]+" "+stoken[2]+" "+stoken[3]+" "+stoken[4]+" "+stoken[5];
             Vxyz[index]=xyz;
           }
           stoken=string_to_vector_string(Vxyz[1],0);
           int mol_id0=stoi(stoken[1]);
           for(int jj=1;jj<=natom;jj++) {
             stoken=string_to_vector_string(Vxyz[jj],0);
             int mol_id=stoi(stoken[1]);
             string str=stoken[0]+" "+int_to_string(mol_id-mol_id0)+" "+stoken[2]+" "+stoken[3]+" "+stoken[4]+" "+stoken[5];
             Vxyz[jj]=str;
           }
           VVxyz.push_back(Vxyz);
         }//if-TIMESTEP
       }//while
       inxyz.close(); inxyz.clear();
     }
   }
   else {
     fname="model";
     int T0=280;
     Nstart+=50000;
     Nstop+=50000;

     ifstream ineng;
     ifstream inxyz;
     string sline;
     vector<string> stoken;

     for(int nn=1;nn<=nmodel;nn++) {
       vector<string> Senergy;
       for(int ii=0;ii<NP;ii++) {
         string fstr=inDIR+"log."+fname+"."+int_to_string(nn)+"."+int_to_string(ii*20+T0);
         ineng.open(fstr.c_str());
         if(!ineng.is_open())
           {cout<<"ERROR: Open file failed: "<<fstr<<endl; return 1;}
         int flag=0;
         vector<int> Vstep;
         while(getline(ineng,sline)) {
           if(sline.find("Step")!=string::npos&&sline.find("E_pair")!=string::npos&&sline.find("E_mol")!=string::npos)
             {flag=1; continue;}
           if(sline.find("Loop")!=string::npos&&sline.find("time")!=string::npos&&sline.find("procs")!=string::npos)
             {flag=0; continue;}
           if(flag==1) {
             stoken=string_to_vector_string(sline,0);
             if(stoken.size()!=6) continue;
             if(stoken[0][0]<'0'||stoken[0][0]>'9') continue;
             int step=atoi(stoken[0].c_str());
             if(count(Vstep.begin(),Vstep.end(),step)==0)
               Vstep.push_back(step);
             else
               continue;
             if(step<Nstart||step>Nstop) continue;
             double E_pair=atof(stoken[2].c_str());
             double E_mol=atof(stoken[3].c_str());
             double E_pot=E_pair+E_mol;
             string str=int_to_string(ii)+" "+int_to_string(step)+" "+double_to_string(E_pot);
             Senergy.push_back(str);
           }
         }//while
         ineng.close(); ineng.clear();
       }

       sort(Senergy.begin(),Senergy.end(),cmp);

       int ns=ceil(Senergy.size()*pe);
       map<string,double> energy;
       for(int jj=0;jj<ns;jj++) {
         stoken=string_to_vector_string(Senergy[jj],0);
         string step=stoken[0]+" "+stoken[1];
         double E_pot=stod(stoken[2]);
         if(energy.count(step)==0) {
           energy.insert(pair<string,double>(step,E_pot));
         }
       }

       for(int ii=0;ii<NP;ii++) {
         string fstr=inDIR+"dump."+fname+"."+int_to_string(nn)+"."+int_to_string(ii*20+T0)+".lammpstrj";
         inxyz.open(fstr.c_str());
         if(!inxyz.is_open())
           {cout<<"ERROR: Open file failed: "<<fstr<<endl; return 1;}
         while(getline(inxyz,sline)) {
           if(sline.find("TIMESTEP")!=string::npos){
             getline(inxyz,sline);
             stoken=string_to_vector_string(sline,0);
             int step=atoi(stoken[0].c_str());
             getline(inxyz,sline);
             getline(inxyz,sline);
             stoken=string_to_vector_string(sline,0);
             int natom=atoi(stoken[0].c_str());
             string Sstep=int_to_string(ii)+" "+int_to_string(step);
             if(step<Nstart||step>=Nstop||energy.count(Sstep)==0) {
               for(int jj=0;jj<natom+5;jj++)
                 getline(inxyz,sline);
               continue;
             }
             getline(inxyz,sline);
             getline(inxyz,sline);
             getline(inxyz,sline);
             getline(inxyz,sline);
             getline(inxyz,sline);
             vector<string> Vxyz;
             Vxyz.resize(natom+1);
             double E_pot=energy[Sstep];
             string str="#Energy: "+double_to_string(E_pot);
             Vxyz[0]=str;
             for(int jj=0;jj<natom;jj++) {
               getline(inxyz,sline);
               stoken=string_to_vector_string(sline,0);
               int index=stoi(stoken[0]);
               string xyz=stoken[0]+" "+stoken[1]+" "+stoken[2]+" "+stoken[3]+" "+stoken[4]+" "+stoken[5];
               Vxyz[index]=xyz;
             }
             stoken=string_to_vector_string(Vxyz[1],0);
             int mol_id0=stoi(stoken[1]);
             for(int jj=1;jj<=natom;jj++) {
               stoken=string_to_vector_string(Vxyz[jj],0);
               int mol_id=stoi(stoken[1]);
               string str=stoken[0]+" "+int_to_string(mol_id-mol_id0)+" "+stoken[2]+" "+stoken[3]+" "+stoken[4]+" "+stoken[5];
               Vxyz[jj]=str;
             }
             VVxyz.push_back(Vxyz);
           }//if-TIMESTEP
         }//while
         inxyz.close(); inxyz.clear();
       }//for-ii
     }
   }

   return 0;
}

int calculate_pairwise_RMSD(vector<vector<double> > Vref, vector<vector<double> > Vtar, vector<double> &Vrmsd, int nth) {
   int natom=Vref.size();
   double (*xref)[3]=new double[natom][3];
   double (*xcal)[3]=new double[natom][3];
   for(int kk=0;kk<natom;kk++)
     for(int ll=0;ll<3;ll++)
       xref[kk][ll]=Vref[kk][ll];
   for(int kk=0;kk<natom;kk++)
     for(int ll=0;ll<3;ll++)
       xcal[kk][ll]=Vtar[kk][ll];
   double x0cen[3]={0.0};
   double xcen[3]={0.0};
   double M[3][3];
   double rmsd=RMSD_arrays_cens_M(natom,xref,xcal,x0cen,xcen,M);
   Vrmsd[nth]=rmsd;

   delete [] xref;
   delete [] xcal;

   return 0;
}

/////rmsd_cut<0: use default rmsd_cut (min(0.1*nt,FCLU0*nstru)); otherwise: use user defined rmsd_cut for clustering
int cluster_structure_RMSD(vector<vector<string> > Stru_xyzs, double rmsd_cut, vector<vector<string> > &Vclu_xyz, vector<string> &Vclu_info) {
   const double FCLU0=0.65;
   vector<vector<vector<double> > > VVxyzs;
   int natom=Stru_xyzs[0].size()-1;
   int nstru=Stru_xyzs.size();
   int nres=0;
   for(int ii=0;ii<nstru;ii++) {
     vector<vector<double> > Vxyzs;
     if(Stru_xyzs[ii].size()-1!=natom)
       {cout<<"ERROR: Atom is missed for structure snapshots --> "<<Stru_xyzs[ii].size()<<"/"<<natom<<endl; return 1;}
     for(int jj=1;jj<=natom;jj++) {
       vector<string> stoken=string_to_vector_string(Stru_xyzs[ii][jj],0);
       if(stoken.size()!=6)
         {cout<<"ERROR: Wrong data format --> "<<Stru_xyzs[ii][jj]<<endl; return 1;}
       vector<double> vtmp;
       for(int kk=3;kk<6;kk++)
         vtmp.push_back(stod(stoken[kk]));
       Vxyzs.push_back(vtmp);
       if(ii==0) {
         int atomtype=stoi(stoken[2]);
         if(atomtype==2)
           nres++;
       }
     }
     VVxyzs.push_back(Vxyzs);
   }

   vector<vector<double> > rmsdij;
   for(int ii=0;ii<nstru;ii++) {
     vector<double> rmsdi;
     rmsdi.resize(nstru);
     for(int jj=0;jj<ii;jj++)
       rmsdi[jj]=rmsdij[jj][ii];
     rmsdi[ii]=0.0;
     vector<vector<double> > Vi=VVxyzs[ii];
     int nij=nstru-ii-1;
     int nloop=(int) nij/NP;
     int nlast=nij%NP;
     std::thread t[NP];
     for(int nl=0;nl<nloop;nl++) {
       int nl0=ii+1+nl*NP;
       vector<vector<vector<double> > > VVj;
       VVj.resize(NP);
       for(int kk=0;kk<NP;kk++)
         VVj[kk]=VVxyzs[nl0+kk];
       vector<double> Vrmsd;
       Vrmsd.resize(NP);
       for(int jj=0;jj<NP;jj++)
         t[jj]=std::thread(calculate_pairwise_RMSD,Vi,VVj[jj],std::ref(Vrmsd),jj);
       for(int jj=0;jj<NP;jj++)
         t[jj].join();
       for(int kk=0;kk<NP;kk++)
         rmsdi[nl0+kk]=Vrmsd[kk];
     }
     if(nlast!=0) {
       int nl0=ii+1+nloop*NP;
       vector<vector<vector<double> > > VVj;
       VVj.resize(NP);
       for(int kk=0;kk<nlast;kk++)
         VVj[kk]=VVxyzs[nl0+kk];
       vector<double> Vrmsd;
       Vrmsd.resize(NP);
       for(int jj=0;jj<nlast;jj++)
         t[jj]=std::thread(calculate_pairwise_RMSD,Vi,VVj[jj],std::ref(Vrmsd),jj);
       for(int jj=0;jj<nlast;jj++)
         t[jj].join();
       for(int kk=0;kk<nlast;kk++)
         rmsdi[nl0+kk]=Vrmsd[kk];
     }
     rmsdij.push_back(rmsdi);
   }

   if(rmsd_cut<0) {
     double rmsd_cut0=0.1*nres;
     int ncut0=round(nstru*FCLU0);
     for(int ii=0;ii<nstru;ii++) {
       vector<double> rmsdi=rmsdij[ii];
       sort(rmsdi.begin(),rmsdi.end());
       double rmsd=rmsdi[ncut0-1];
       if(rmsd<rmsd_cut0)
         rmsd_cut0=rmsd;
     }
     rmsd_cut=rmsd_cut0;
   }

   int clumax;
   int nmax=0;
   for(int ii=0;ii<nstru;ii++) {
     int nmi=0;
     for(int jj=0;jj<nstru;jj++)
       if(rmsdij[ii][jj]<=rmsd_cut)
         nmi++;
     if(nmi>nmax) {
       nmax=nmi;
       clumax=ii;
     }
   }
   vector<int> Vidmax;
   double aver_eng=0.0;
   for(int ii=0;ii<nstru;ii++)
     if(rmsdij[clumax][ii]<=rmsd_cut) {
        Vidmax.push_back(ii);
        vector<string> stoken=string_to_vector_string(Stru_xyzs[ii][0],0);
        aver_eng+=stod(stoken[1]);
     }

   vector<int> Vclucen;
   vector<int> Vclunum;
   vector<double> Vclueng;
   Vclucen.push_back(clumax);
   Vclunum.push_back(Vidmax.size());
   aver_eng/=Vidmax.size();
   Vclueng.push_back(aver_eng);
   map<int,vector<int> > Mneighs;
   int ceni=-1;
   int numi=-1;
   vector<int> Vsingle;
   for(int ii=0;ii<nstru;ii++) {
     if(count(Vidmax.begin(),Vidmax.end(),ii)) continue;
     vector<int> Vneigh;
     for(int jj=0;jj<nstru;jj++) {
       if(jj==ii) continue;
       if(count(Vidmax.begin(),Vidmax.end(),jj)) continue;
       if(rmsdij[ii][jj]<=rmsd_cut)
         Vneigh.push_back(jj);
     }
     int num=Vneigh.size();
     if(num==0)
       {Vsingle.push_back(ii); continue;}
     Mneighs.insert(pair<int,vector<int> >(ii,Vneigh));
     if(num>numi) {
       ceni=ii;
       numi=num;
     }
   }

   while(Mneighs.size()>0) {
     Vclucen.push_back(ceni);
     Vclunum.push_back(numi+1);
     vector<int> Vids=Mneighs[ceni];
     Vids.push_back(ceni);
     aver_eng=0.0;
     for(auto id : Vids) {
       Mneighs.erase(id);
       vector<string> stoken=string_to_vector_string(Stru_xyzs[id][0],0);
       aver_eng+=stod(stoken[1]);
     }
     aver_eng/=numi+1;
     Vclueng.push_back(aver_eng);

     ceni=-1;
     numi=0;
     vector<int> Vs;
     for(auto& it : Mneighs) {
       vector<int> vid;
       for(auto id : it.second) {
         if(count(Vids.begin(),Vids.end(),id)==0)
           vid.push_back(id);
       }
       if(vid.size()==0) {
         Vs.push_back(it.first);
         continue;
       }
       if(vid.size()>numi) {
         numi=vid.size();
         ceni=it.first;
       }
       Mneighs[it.first]=vid;
     }
     if(Vs.size()>0) {
       Vsingle.insert(Vsingle.end(),Vs.begin(),Vs.end());
       for(auto id : Vs)
         Mneighs.erase(id);
     }
   }
   for(auto id : Vsingle) {
     Vclucen.push_back(id);
     Vclunum.push_back(1);
     vector<string> stoken=string_to_vector_string(Stru_xyzs[id][0],0);
     aver_eng=stod(stoken[1]);
     Vclueng.push_back(aver_eng);
   }

   Vclu_xyz.clear();
   Vclu_info.clear();

   string str="Number of structures : "+int_to_string(nstru);
   Vclu_info.push_back(str);
   str="Number of clusters : "+int_to_string(Vclucen.size());
   Vclu_info.push_back(str);
   str="Length of RNA : "+int_to_string(nres);
   Vclu_info.push_back(str);
   str="RMSD threshold for clustering : "+double_to_string(rmsd_cut);
   Vclu_info.push_back(str);
   str=" ";
   Vclu_info.push_back(str);
   str="#Cluster Percentage_of_clustered_structures Number_of_clustered_structures Average_energy";
   Vclu_info.push_back(str);

   for(int ii=0;ii<Vclucen.size();ii++) {
     int id=Vclucen[ii];
     double ps=Vclunum[ii]*1.0/nstru*100;
     vector<string> Vxyz=Stru_xyzs[id];
     Vclu_xyz.push_back(Vxyz);
     string str="#"+int_to_string(ii+1)+" "+double_to_string(ps)+" "+int_to_string(Vclunum[ii])+" "+double_to_string(Vclueng[ii]);
     Vclu_info.push_back(str);
   }

   return 0;
}

int close_ends(string outDIR, vector<string> Vseq, vector<vector<string> > &VVatoms, string coeffDIR, string lmp, int Nstep, string restr) {
   int nmodel=VVatoms.size();
   double dmax=-1.0;
   if(write_CG_model(outDIR,VVatoms,coeffDIR,Vseq,0,dmax,restr)) return 1;
   if(Nstep<0) {
    Nstep=round(dmax)*100000;
    if(Nstep>50000000) Nstep=50000000;
    else if(Nstep<10000000) Nstep=10000000;
   }
   int Nevery=Nstep/1000; if(Nevery<1) Nevery=1;

   write_MD_script(outDIR,nmodel,Nstep,Nevery,0,restr);
   run_MD(outDIR,lmp,nmodel,0);
   
   double ps=0.1;
   double pe=0.5;
   vector<vector<string> > VVxyz;
   if(read_structure(outDIR,nmodel,Nstep,ps,pe,VVxyz,0)) return 1;
   int ns=VVxyz.size()/nmodel;
   for(int ii=0;ii<nmodel;ii++) {
     vector<vector<string> > Stru_xyzs;
     for(int jj=0;jj<ns;jj++) {
       int kk=ii*ns+jj;
       Stru_xyzs.push_back(VVxyz[kk]);
     }
     vector<vector<string> > Vclu_xyz;
     vector<string> Vclu_info;
     double rmsd_cut=-1;
     if(cluster_structure_RMSD(Stru_xyzs,rmsd_cut,Vclu_xyz,Vclu_info)) return 1;
     vector<string> Vatom=VVatoms[ii];
     vector<string> Vxyz=Vclu_xyz[0];
     Vxyz.erase(Vxyz.begin());
     if(Vatom.size()!=Vxyz.size())
       {cout<<"ERROR: Reset xyz failed in closing ends: "<<Vatom.size()<<"/"<<Vxyz.size()<<endl; return 1;}
     for(int jj=0;jj<Vatom.size();jj++) {
       vector<string> stoken=string_to_vector_string(Vatom[jj],0);
       string str="";
       for(int kk=0;kk<5;kk++)
         str+=stoken[kk]+" ";
       stoken=string_to_vector_string(Vxyz[jj],0);
       str+=stoken[3]+" "+stoken[4]+" "+stoken[5];
       Vatom[jj]=str;
     }
     VVatoms[ii]=Vatom;
   }

   return 0;
}

int energy_minimize_CG(string outDIR, vector<vector<string> > &VVatoms, string lmp) {
   int nmodel=VVatoms.size();
   vector<string> data_before;
   vector<string> data_after;
   int check=0;
   string sline;
   string filename=outDIR+"data.model.1";
   ifstream inD (filename.c_str());
   getline(inD,sline);
   while(getline(inD,sline)) {
     if(sline.find("Atoms")!=string::npos) check=1;
     else if(sline.find("Bonds")!=string::npos) check=2;
     if(check==0)
       data_before.push_back(sline);
     else if(check==2)
       data_after.push_back(sline);
     else
       continue;
   }
   inD.close(); inD.clear();
   for(int ii=0;ii<nmodel;ii++) {
     filename=outDIR+"data.min."+int_to_string(ii+1);
     ofstream model (filename.c_str());
     model<<"#RNA CG Model for Minimize"<<endl;
     for(int jj=0;jj<data_before.size();jj++)
       model<<data_before[jj]<<endl;
     model<<"Atoms"<<endl<<endl;
     for(int jj=0;jj<VVatoms[ii].size();jj++) {
       sline=VVatoms[ii][jj];
       if(sline.find("#")!=string::npos) continue;
       model<<sline<<endl;
     }
     model<<endl;
     for(int jj=0;jj<data_after.size();jj++)
      model<<data_after[jj]<<endl;
     model.close(); model.clear();
   }

   int ns=nmodel/NP;
   int nm=nmodel%NP;
   for(int jj=0;jj<=ns;jj++) {
     if(jj==ns&&nm==0) continue;
     filename=outDIR+"in.min."+int_to_string(jj+1);
     ofstream script (filename.c_str());
     script<<"#LAMMPS Script for CG Model Minimize"<<endl;
     script<<"units	      real"<<endl;
     script<<"dimension       3"<<endl;
     script<<"boundary        p p p"<<endl;
     script<<"atom_style      molecular"<<endl;
     script<<"special_bonds   lj/coul 0.0 0.0 0.0 angle no dihedral no"<<endl;
     script<<endl;
     script<<"neighbor	      2.0 bin"<<endl;
     script<<"neigh_modify    every 5 delay 5"<<endl;
     script<<endl;
     script<<"bond_style      harmonic/gauss"<<endl;
     script<<"angle_style     harmonic/gauss"<<endl;
     script<<"dihedral_style  fourier"<<endl;
     script<<"pair_style      morse/gauss2/lj9 "<<rcut0<<endl;
     script<<endl;
     script<<"variable        t world";
     if(jj==ns)
       for(int kk=1;kk<=nm;kk++)
         script<<" "<<kk+ns*NP;
     else
       for(int kk=1;kk<=NP;kk++)
         script<<" "<<kk+jj*NP;
     script<<endl<<endl;
     script<<"read_data	      "<<outDIR<<"data.min.$t"<<endl;
     script<<endl;
     script<<"log             "<<outDIR<<"log.min.$t"<<endl;
     script<<endl;
     script<<"thermo          1000"<<endl;
     script<<endl;
     script<<"dump            1 all custom 1000 "<<outDIR<<"dump.min.$t.lammpstrj id mol type x y z ix iy iz"<<endl;
     script<<endl;
     script<<"min_style       sd"<<endl;
     script<<"minimize        1.0e-4 1.0e-6 30000 1000000"<<endl;
     script.close(); script.clear();
   }

   for(int ii=0;ii<ns;ii++) {
     string cmd=lmp+" -in "+outDIR+"in.min."+int_to_string(ii+1)+" -sc none";
     system(cmd.c_str());
   }
   if(nm!=0) {
     string cmd=lmp+" -in "+outDIR+"in.min."+int_to_string(ns+1)+" -sc none";
     system(cmd.c_str());
   }

   VVatoms.clear();
   for(int ii=0;ii<nmodel;ii++) {
     filename=outDIR+"dump.min."+int_to_string(ii+1)+".lammpstrj";
     ifstream inxyz (filename.c_str());
     double xlo,xhi,ylo,yhi,zlo,zhi;
     vector<string> xyz;
     vector<string> stoken;
     while(getline(inxyz,sline)) {
       if(sline.find("TIMESTEP")!=string::npos) {
         getline(inxyz,sline);
         getline(inxyz,sline);
         getline(inxyz,sline);
         stoken=string_to_vector_string(sline,0);
         int natom=atoi(stoken[0].c_str());
         getline(inxyz,sline);
         getline(inxyz,sline);
         vector<string> stoken=string_to_vector_string(sline,0);
         xlo=atof(stoken[0].c_str());
         xhi=atof(stoken[1].c_str());
         getline(inxyz,sline);
         stoken=string_to_vector_string(sline,0);
         ylo=atof(stoken[0].c_str());
         yhi=atof(stoken[1].c_str());
         getline(inxyz,sline);
         stoken=string_to_vector_string(sline,0);
         zlo=atof(stoken[0].c_str());
         zhi=atof(stoken[1].c_str());
         getline(inxyz,sline);
         xyz.clear();
         for(int jj=0;jj<natom;jj++) {
           getline(inxyz,sline);
           xyz.push_back(sline);
         }
       }//if
     }//while
     inxyz.close(); inxyz.clear();
     int natom=xyz.size();
     int *mol_id=new int[natom];
     int *atom_type=new int[natom];
     double *CG_x=new double[natom];
     double *CG_y=new double[natom];
     double *CG_z=new double[natom];
     for(int jj=0;jj<natom;jj++) {
       stoken=string_to_vector_string(xyz[jj],0);
       int index=atoi(stoken[0].c_str());
       double xx=atof(stoken[3].c_str());
       double yy=atof(stoken[4].c_str());
       double zz=atof(stoken[5].c_str());
       int ix=atoi(stoken[6].c_str());
       int iy=atoi(stoken[7].c_str());
       int iz=atoi(stoken[8].c_str());
       index-=1;
       mol_id[index]=atoi(stoken[1].c_str());
       atom_type[index]=atoi(stoken[2].c_str());
       CG_x[index]=xx+(xhi-xlo)*ix;
       CG_y[index]=yy+(yhi-ylo)*iy;
       CG_z[index]=zz+(zhi-zlo)*iz;
     }//for-jj
     xyz.clear();
     for(int jj=0;jj<natom;jj++) {
       string str=int_to_string(jj+1)+" "+int_to_string(mol_id[jj])+" "+int_to_string(atom_type[jj])+" ";
       str+=double_to_string(CG_x[jj])+" "+double_to_string(CG_y[jj])+" "+double_to_string(CG_z[jj]);
       xyz.push_back(str);
     }
     VVatoms.push_back(xyz);
     delete [] mol_id;
     delete [] atom_type;
     delete [] CG_x;
     delete [] CG_y;
     delete [] CG_z;
   }

   return 0;
}

int transfer_CG_to_allatom(vector<string> Vcg, vector<string> &Vallatoms, int nth, string coeffDIR) {
   for(size_t ii=0;ii<Vcg.size();ii++) {
     vector<string> stoken=string_to_vector_string(Vcg[ii],0);
     string str=cg_beads[ii]+" "+stoken[3]+" "+stoken[4]+" "+stoken[5];
     Vcg[ii]=str;
   }
   vector<string> outAA;
   if(cg_to_allatom(Vcg,outAA,coeffDIR,0)) return 1;
   Vallatoms=outAA;

   return 0;
}

void output_PDB(vector<vector<string> > VVatoms, vector<vector<string> > &VVpdbs, string coeffDIR) {
   VVpdbs.clear();
   int nmodel=VVatoms.size();
   cout<<"  output_PDB: nmodel="<<nmodel<<", NP="<<NP<<endl;
   int nloop=(int) nmodel/NP;
   int nlast=nmodel%NP;
   cout<<"  nloop="<<nloop<<", nlast="<<nlast<<endl;
   // Serial processing instead of threads for debugging
   for(int nl=0;nl<nloop;nl++) {
     for(int kk=0;kk<NP;kk++) {
       vector<string> VVcg=VVatoms[nl*NP+kk];
       vector<string> Vallatom;
       cout<<"  Converting model "<<nl*NP+kk+1<<"..."<<endl;
       if(transfer_CG_to_allatom(VVcg,Vallatom,kk,coeffDIR)) {
         cout<<"  ERROR: transfer_CG_to_allatom failed for model "<<nl*NP+kk+1<<endl;
         continue;
       }
       VVpdbs.push_back(Vallatom);
       cout<<"  OK: model "<<nl*NP+kk+1<<" converted, "<<Vallatom.size()<<" atoms"<<endl;
     }
   }
   if(nlast!=0) {
     for(int kk=0;kk<nlast;kk++) {
       vector<string> VVcg=VVatoms[nloop*NP+kk];
       vector<string> Vallatom;
       cout<<"  Converting last model "<<kk+1<<"..."<<endl;
       if(transfer_CG_to_allatom(VVcg,Vallatom,kk,coeffDIR)) {
         cout<<"  ERROR: transfer_CG_to_allatom failed for last model "<<kk+1<<endl;
         continue;
       }
       VVpdbs.push_back(Vallatom);
       cout<<"  OK: last model "<<kk+1<<" converted, "<<Vallatom.size()<<" atoms"<<endl;
     }
   }
}

// ═══════════════════════════════════════════════════════════
//  分层模式: 分段 Vfold3D + Kabsch 拼装 (Type=2)
// ═══════════════════════════════════════════════════════════

struct ChunkSeg {
   int start, end;       // [start, end) 在全链中的位置
   string seq;           // 该段序列
   string ss;            // 该段二级结构
   bool bsj_aware;       // 是否跨 BSJ
};

// 分段: 返回 ChunkSeg 列表
vector<ChunkSeg> split_sequence_cpp(string seq, string ss, int max_seg_len, int overlap) {
   vector<ChunkSeg> chunks;
   int L = seq.size();
   int stride = max_seg_len - overlap;

   // 找 BSJ 位点 (序列首尾相同 k-mer)
   int bsj_pos = -1;
   for(int k = 8; k <= 20 && bsj_pos < 0; k++) {
      if(L > k && seq.substr(0, k) == seq.substr(L - k, k))
         bsj_pos = 0;  // BSJ 在 0/L 处
   }

   for(int s = 0; s < L; s += stride) {
      ChunkSeg seg;
      seg.start = s;
      seg.end = min(s + max_seg_len, L);
      seg.seq = seq.substr(seg.start, seg.end - seg.start);
      seg.ss = ss.substr(seg.start, seg.end - seg.start);
      seg.bsj_aware = (bsj_pos >= 0 &&
                        (seg.start == 0 || seg.end == L));
      chunks.push_back(seg);
      if(seg.end >= L) break;
   }
   return chunks;
}

// Kabsch 对齐: 将 coords_b 对齐到 coords_a, 返回变换后的 coords_b
// coords_a, coords_b: 逐原子 [x1,y1,z1, x2,y2,z2, ...]
vector<double> kabsch_align_cpp(
   const vector<double> &coords_a,
   const vector<double> &coords_b)
{
   int n = coords_a.size() / 3;
   if(n < 3 || coords_b.size() != coords_a.size()) return coords_b;

   // 中心化
   double ca[3] = {0,0,0}, cb[3] = {0,0,0};
   for(int i = 0; i < n; i++) {
      for(int k = 0; k < 3; k++) {
         ca[k] += coords_a[i*3+k];
         cb[k] += coords_b[i*3+k];
      }
   }
   for(int k = 0; k < 3; k++) { ca[k] /= n; cb[k] /= n; }

   // 协方差矩阵 H = A^T B
   double H[3][3] = {{0}};
   for(int i = 0; i < n; i++)
      for(int r = 0; r < 3; r++)
         for(int c = 0; c < 3; c++)
            H[r][c] += (coords_a[i*3+r] - ca[r]) * (coords_b[i*3+c] - cb[c]);

   // 用 FIT_RMSD 的 Kabsch 求旋转矩阵 M
   double x1[n][3], x2[n][3];
   for(int i = 0; i < n; i++) {
      for(int k = 0; k < 3; k++) {
         x1[i][k] = coords_a[i*3+k] - ca[k];
         x2[i][k] = coords_b[i*3+k] - cb[k];
      }
   }
   double x1cen[3] = {0}, x2cen[3] = {0};
   double M[3][3] = {{1,0,0},{0,1,0},{0,0,1}};
   double rmsd = FIT_RMSD_MM(n, x1, x2, x1cen, x2cen, M);

   // 应用变换: result = M * (b - cb) + ca
   vector<double> result(n * 3);
   for(int i = 0; i < n; i++) {
      double db[3];
      for(int k = 0; k < 3; k++) db[k] = coords_b[i*3+k] - cb[k];
      for(int r = 0; r < 3; r++) {
         double val = ca[r];
         for(int c = 0; c < 3; c++) val += M[r][c] * db[c];
         result[i*3+r] = val;
      }
   }
   return result;
}

// 拼装: 将多个 chunk 的 CG 坐标合并成全链坐标
// chunk_coords: 每个 chunk 的 P 原子坐标列表
// chunks: 分段信息
// L: 全链长度
// 返回: (L*3,) 的坐标数组
vector<double> assemble_chunks_cpp(
   const vector<vector<double>> &chunk_coords,
   const vector<ChunkSeg> &chunks,
   int L)
{
   vector<double> full(L * 3, 0.0);
   vector<int> count(L, 0);

   for(int ci = 0; ci < (int)chunks.size(); ci++) {
      const auto &coords = chunk_coords[ci];
      int n_atoms = (int)coords.size() / 3;
      int offset = chunks[ci].start;

      for(int i = 0; i < n_atoms && (offset + i) < L; i++) {
         int pos = offset + i;
         for(int k = 0; k < 3; k++)
            full[pos*3+k] += coords[i*3+k];
         count[pos]++;
      }
   }

   // 平均重叠区
   for(int i = 0; i < L; i++) {
      if(count[i] > 1) {
         for(int k = 0; k < 3; k++)
            full[i*3+k] /= count[i];
      }
   }

   // 填充空位 (用最近的非零原子)
   for(int i = 0; i < L; i++) {
      if(count[i] == 0) {
         // 找最近的有坐标的位置
         int best = -1;
         for(int j = 0; j < L; j++) {
            if(count[j] > 0 && (best < 0 || abs(j-i) < abs(best-i)))
               best = j;
         }
         if(best >= 0) {
            for(int k = 0; k < 3; k++)
               full[i*3+k] = full[best*3+k];
         }
      }
   }

   return full;
}

// 分层模式入口: 分段 Vfold3D → Kabsch 拼装 → close_ends → REMD
int segmented_pipeline(
   string INPUT, string outDIR, string Name,
   vector<string> Vseq, string coeffDIR, string lmp,
   int Nstep, int Nstep_close, int Nstru,
   int max_seg_len, int overlap)
{
   int L = Vseq[0].size();
   string seq = Vseq[0];
   string ss = Vseq[1];

   cout<<"=== Segmented Pipeline (Type=2) ==="<<endl;
   cout<<"  Sequence length: "<<L<<" nt"<<endl;

   // 1. 分段
   vector<ChunkSeg> chunks = split_sequence_cpp(seq, ss, max_seg_len, overlap);
   cout<<"  Split into "<<chunks.size()<<" chunks"<<endl;
   for(int i = 0; i < (int)chunks.size(); i++) {
      cout<<"    chunk_"<<i<<": ["<<chunks[i].start<<"-"<<chunks[i].end
          <<"] "<<(chunks[i].end-chunks[i].start)<<"nt"
          <<(chunks[i].bsj_aware?" BSJ":"")<<endl;
   }

   // 2. 每段独立 Vfold3D
   vector<vector<double>> chunk_coords(chunks.size());
   for(int ci = 0; ci < (int)chunks.size(); ci++) {
      string seg_dir = outDIR + "/chunk_" + to_string(ci) + "/";
      string seg_name = "chunk_" + to_string(ci);
      string cmd = "mkdir -p " + seg_dir;
      system(cmd.c_str());

      // 写 .2d 文件
      string f2d = seg_dir + seg_name + ".2d";
      ofstream outS(f2d.c_str());
      outS<<chunks[ci].seq<<endl;
      outS<<chunks[ci].ss<<endl;
      outS.close();

      // 调用 Vfold3D
      vector<vector<string>> VVatoms;
      vector<string> Vseg = {chunks[ci].seq, chunks[ci].ss};
      if(get_initial_structures_vfold3D(INPUT, seg_dir, seg_name, Vseg, VVatoms)) {
         cout<<"    chunk_"<<ci<<": Vfold3D failed, using default helix"<<endl;
         // 默认螺旋坐标
         int n = chunks[ci].end - chunks[ci].start;
         vector<double> coords(n * 3);
         for(int i = 0; i < n; i++) {
            double angle = i * 33.0 * M_PI / 180.0;
            coords[i*3+0] = 4.4 * cos(angle);
            coords[i*3+1] = 4.4 * sin(angle);
            coords[i*3+2] = i * 2.8;
         }
         chunk_coords[ci] = coords;
      } else {
         // 提取 P 原子坐标
         if(VVatoms.size() > 0) {
            vector<double> coords;
            for(int i = 0; i < (int)VVatoms[0].size(); i++) {
               vector<string> stoken = string_to_vector_string(VVatoms[0][i], 0);
               coords.push_back(stod(stoken[5]));
               coords.push_back(stod(stoken[6]));
               coords.push_back(stod(stoken[7]));
            }
            chunk_coords[ci] = coords;
            cout<<"    chunk_"<<ci<<": "<<coords.size()/3<<" P atoms"<<endl;
         }
      }
   }

   // 3. Kabsch 拼装 (以第一个 chunk 为参考)
   // 将所有 chunk 对齐到参考坐标系
   if(chunk_coords.size() > 1 && chunk_coords[0].size() > 0) {
      for(int ci = 1; ci < (int)chunk_coords.size(); ci++) {
         if(chunk_coords[ci].empty()) continue;
         // 找重叠区
         int ol_s = max(chunks[ci].start, chunks[0].start);
         int ol_e = min(chunks[ci].end, chunks[0].end);
         if(ol_e <= ol_s) continue;

         int ol_len = ol_e - ol_s;
         int la = ol_s - chunks[0].start;
         int lb = ol_s - chunks[ci].start;

         if(la + ol_len <= (int)chunk_coords[0].size()/3 &&
            lb + ol_len <= (int)chunk_coords[ci].size()/3) {
            // 提取重叠区坐标
            vector<double> ref_ol, seg_ol;
            for(int i = 0; i < ol_len; i++) {
               for(int k = 0; k < 3; k++) {
                  ref_ol.push_back(chunk_coords[0][(la+i)*3+k]);
                  seg_ol.push_back(chunk_coords[ci][(lb+i)*3+k]);
               }
            }
            // Kabsch 对齐整个 chunk
            chunk_coords[ci] = kabsch_align_cpp(ref_ol, chunk_coords[ci]);
         }
      }
   }

   // 4. 合并成全链坐标
   vector<double> full_coords = assemble_chunks_cpp(chunk_coords, chunks, L);
   cout<<"  Assembled: "<<full_coords.size()/3<<" P atoms"<<endl;

   // 5. 写入 PDB + 转 CG → 进入 close_ends + REMD
   // 将 full_coords 写成 VVatoms 格式 (兼容后续流程)
   vector<vector<string>> VVatoms_all;
   {
      vector<string> Vatom_line;
      // 构建全链 CG model (P atom only)
      for(int i = 0; i < L; i++) {
         string line = "P " + string(1, seq[i]) + " " + to_string(i+1) + " A "
                     + to_string(i+1) + " "
                     + to_string(full_coords[i*3+0]) + " "
                     + to_string(full_coords[i*3+1]) + " "
                     + to_string(full_coords[i*3+2]);
         Vatom_line.push_back(line);
      }
      VVatoms_all.push_back(Vatom_line);
   }

   // 写初始 PDB
   string fpdb = outDIR + "/" + Name + "_segmented_ini.pdb";
   ofstream outP(fpdb.c_str());
   outP<<"MODEL      1"<<endl;
   for(int i = 0; i < (int)VVatoms_all[0].size(); i++) {
      vector<string> stoken = string_to_vector_string(VVatoms_all[0][i], 0);
      outP<<"ATOM  "<<setw(5)<<i+1<<"  P   "
          <<stoken[1]<<" A"<<setw(4)<<stoi(stoken[3])
          <<"    "<<setw(8)<<stod(stoken[5])
          <<setw(8)<<stod(stoken[6])
          <<setw(8)<<stod(stoken[7])
          <<"  1.00  0.00           P"<<endl;
   }
   outP<<"ENDMDL"<<endl;
   outP<<"END"<<endl;
   outP.close();

   // 6. close_ends + REMD (复用现有流程)
   int Nevery_local = Nstep / Nstru;
   double dmax = -1.0;
   string restr = "";

   cout<<"Step 2: Close ends..."<<endl;
   if(close_ends(outDIR, Vseq, VVatoms_all, coeffDIR, lmp, Nstep_close, restr)) return 1;

   cout<<"Step 3: Run REMD simulations..."<<endl;
   int nmodel = VVatoms_all.size();
   if(write_CG_model(outDIR, VVatoms_all, coeffDIR, Vseq, 1, dmax, restr)) return 1;
   write_MD_script(outDIR, nmodel, Nstep, Nevery_local, 1, restr);
   run_MD(outDIR, lmp, nmodel, 1);

   cout<<"Step 4: Output predictions..."<<endl;
   // ... (复用 Type=0 的输出逻辑)

   return 0;
}

int main(int argc,char **argv) {
   if(argc<6||argc>8){cout<<"***example: ./*.o INPUT in2D outDIR Name inCONF Type inPDB"<<endl<<endl; return 1;}
   string INPUT=argv[1];
   string in2D=argv[2];
   string outDIR=argv[3];
   string Name=argv[4];
   string inCONF=argv[5];
   int Type=atoi(argv[6]);
   if((Type==1&&argc<8))
     {cout<<"Wrong input argv[]"<<endl; return 1;}
   string inPDB;
   if(Type)
     inPDB=argv[7];

   string restr="";

   if(INPUT.back()=='/') INPUT.pop_back();
   if(outDIR.back()=='/') outDIR.pop_back();

   string coeffDIR=INPUT+"/data/IsRNA2/";
   string lmp=INPUT+"/lmp_serial";
   string NAMDDIR=INPUT+"/data/NAMD";

   outDIR+="/"+Name+"/";
   string cmd="mkdir "+outDIR;
   system(cmd.c_str());

   string exfstr=outDIR+"excluded_pdblist_file.dat";
   ofstream outEx(exfstr.c_str());
   outEx.close(); outEx.clear();
   excluded_pdblist_file=exfstr;

   map<string,string> Mconfs;
   ifstream inC (inCONF.c_str());
   if(!inC.is_open()) {cout<<"ERROR: Cannot open config file: "<<inCONF<<endl; return 1;}
   string sline;
   while(getline(inC,sline)) {
     if(sline.size()<3) continue;
     vector<string> stoken=string_to_vector_string(sline,0);
     if(stoken.size()<2) continue;
     if(stoken[0].find("#")!=string::npos) continue;
     Mconfs.insert(pair<string,string>(stoken[0],stoken[1]));
   }
   inC.close(); inC.clear();
   cout<<"Config: Nstep="<<Mconfs["Nstep"]<<", Nstep_close="<<Mconfs["Nstep_close"]<<endl;
   int Nstep=stoi(Mconfs["Nstep"]);
   int Nstep_close=stoi(Mconfs["Nstep_close"]);
   int Nstru=stoi(Mconfs["Nstru"]);
   double Ps=stod(Mconfs["PS"]);
   double Pe=stod(Mconfs["PE"]);
   double rmsd_cut=stod(Mconfs["RMSD_Cut"]);
   int Nout=stoi(Mconfs["Nout"]);
   int Nmax=3;

   time_t tstart,tend;
   time (&tstart);

   vector<string> Vseq;
   if(read_2D(in2D,Vseq)) return 1;

   int length=Vseq[0].size();
  
   int Nevery=Nstep/Nstru;

   vector<vector<string> > VVatoms;

   // ── Type=2: 分层模式 (分段 Vfold3D + Kabsch 拼装) ──
   bool skip_steps23 = false;  // Type=2 已在 segmented_pipeline 内完成
   if(Type==2) {
     int max_seg_len = 200;
     int seg_overlap = 20;
     if(Mconfs.find("MaxSegLen") != Mconfs.end()) max_seg_len = stoi(Mconfs["MaxSegLen"]);
     if(Mconfs.find("Overlap") != Mconfs.end()) seg_overlap = stoi(Mconfs["Overlap"]);

     if(segmented_pipeline(INPUT, outDIR, Name, Vseq, coeffDIR, lmp,
                           Nstep, Nstep_close, Nstru,
                           max_seg_len, seg_overlap))
       return 1;
     skip_steps23 = true;
   }

   if(Type==0) {
     cout<<"Step 1: Generate initial 3D structures by Vfold3D/VfoldLA..."<<endl;

     int check1=0;
     if(get_initial_structures_vfold3D(INPUT,outDIR,Name,Vseq,VVatoms)) check1=1;

     vector<vector<string> > VVpdbs;
     if(check1==0) {
       string fpdb=outDIR+Name+"_vfold3D.pdb";
       if(read_PDBs(fpdb,Vseq[0],VVpdbs,0)) check1=1;
     }
     cout<<check1<<endl;
     int check2=0;
     vector<vector<string> > VVatom1;
     vector<vector<string> > VVpdbs1;
     if(VVatoms.size()<Nmax) {
       if(get_initial_structures_vfoldLA(INPUT,outDIR,Name,Vseq[0],VVatom1)) check2=1;
       if(check2==0) {
         string fpdb=outDIR+Name+"_vfoldLA.pdb";
         if(read_PDBs(fpdb,Vseq[0],VVpdbs1,0)) check2=1;
       }
     }
     if(check1&&check2) {
       if(Vseq.size()==2) {
         cout<<"ERROR: Fail to get initial 3D structures by Vfold3D/VfoldLA for the given 2D structure."<<endl;
           return 1;
       }
       else {
         cout<<"Warning: Open the tertiary base pairs to get initial 3D structures by Vfold3D/VfoldLA."<<endl;
         vector<string> Vseq1;
         Vseq1.push_back(Vseq[0]);
         Vseq1.push_back(Vseq[2]);
         check1=0;
         check2=0;

         if(get_initial_structures_vfold3D(INPUT,outDIR,Name,Vseq1,VVatoms)) check1=1;
         if(check1==0) {
           string fpdb=outDIR+Name+"_vfold3D.pdb";
           if(read_PDBs(fpdb,Vseq1[0],VVpdbs,0)) check1=1;
         }

         if(VVatoms.size()<Nmax) {
           if(get_initial_structures_vfoldLA(INPUT,outDIR,Name,Vseq1[0],VVatom1)) check2=1;
           if(check2==0) {
             string fpdb=outDIR+Name+"_vfoldLA.pdb";
             if(read_PDBs(fpdb,Vseq1[0],VVpdbs1,0)) check2=1;
           }

           if(check1&&check2) {
             cout<<"ERROR: Fail to get initial 3D structures by Vfold3D/VfoldLA for the given 2D structure."<<endl;
             return 1;
           }
         }
       }
     }

     if(VVatoms.size()==0) {
       VVatoms=VVatom1;
       VVpdbs=VVpdbs1;
     }
     else if(VVatoms.size()<Nmax) {
       vector<vector<double> > VVxyz_ref;
       for(int ii=0;ii<VVatoms.size();ii++) {
         vector<double> Vxyz_ref;
         for(int jj=0;jj<VVatoms[ii].size();jj++) {
           vector<string> stoken=string_to_vector_string(VVatoms[ii][jj],0);
           for(int kk=5;kk<8;kk++)
             Vxyz_ref.push_back(stod(stoken[kk]));
         }
         VVxyz_ref.push_back(Vxyz_ref);
       }
       for(int ii=0;ii<VVatom1.size();ii++) {
         vector<double> Vxyz_tar;
         for(int jj=0;jj<VVatom1[ii].size();jj++) {
           vector<string> stoken=string_to_vector_string(VVatom1[ii][jj],0);
           for(int kk=5;kk<8;kk++)
             Vxyz_tar.push_back(stod(stoken[kk]));
         }
         int check=0;
         for(int jj=0;jj<VVxyz_ref.size();jj++) {
           double rmsd=RMSD_vectors_rmsd(Vxyz_tar,VVxyz_ref[jj]);
           if(rmsd<=RMSDCUT)
             {check=1; break;}
         }
         if(check) continue;
         VVatoms.push_back(VVatom1[ii]);
         VVpdbs.push_back(VVpdbs1[ii]);
         if(VVatoms.size()>=Nmax) break;
       }
     }

     cout<<"  Get "<<VVatoms.size()<<" initial models by Vfold3D/VfoldLA."<<endl;
     string fpdb=outDIR+"/"+Name+"_ini.pdb";
     ofstream outP (fpdb.c_str());
     for(int jj=0;jj<VVpdbs.size();jj++) {
       outP<<"MODEL      "<<jj+1<<endl;
       for(auto str : VVpdbs[jj])
         outP<<str<<endl;
       outP<<"ENDMDL"<<endl;
     }
     outP<<"END"<<endl;
     outP.close(); outP.clear();
   }
   else {
     cout<<"Step 1: Read initial 3D structure(s) from given file..."<<endl;
     if(read_PDBs(inPDB,Vseq[0],VVatoms,1)) return 1;
     vector<vector<string> > VVpdbs;
     if(read_PDBs(inPDB,Vseq[0],VVpdbs,0)) return 1;
     cout<<"  Read "<<VVatoms.size()<<" initial models from the given file."<<endl;
     string fpdb=outDIR+"/"+Name+"_ini.pdb";
     ofstream outP (fpdb.c_str());
     for(int jj=0;jj<VVpdbs.size();jj++) {
       outP<<"MODEL      "<<jj+1<<endl;
       for(auto str : VVpdbs[jj])
         outP<<str<<endl;
       outP<<"ENDMDL"<<endl;
     }
     outP<<"END"<<endl;
     outP.close(); outP.clear();
   }

   int nmodel=VVatoms.size();

   if(!skip_steps23) {
     cout<<"Step 2: Close ends..."<<endl;
     if(close_ends(outDIR,Vseq,VVatoms,coeffDIR,lmp,Nstep_close,restr)) return 1;

     cout<<"Step 3: Run REMD simulations..."<<endl;
     double dmax=-1.0;
     if(write_CG_model(outDIR,VVatoms,coeffDIR,Vseq,1,dmax,restr)) return 1;
     write_MD_script(outDIR,nmodel,Nstep,Nevery,1,restr);
     //exit(0);
     run_MD(outDIR,lmp,nmodel,1);
   }

   cout<<"Step 4: Output predictions..."<<endl;
   vector<vector<string> > VVxyzs;
   cout<<"  Read structure..."<<endl;
   read_structure(outDIR,nmodel,Nstep,Ps,Pe,VVxyzs,1);
   vector<vector<string> > Vclu_xyz;
   vector<string> Vclu_info;
   cout<<"  Cluster structure..."<<endl;
   if(cluster_structure_RMSD(VVxyzs,rmsd_cut,Vclu_xyz,Vclu_info)) return 1;
   string fstr=outDIR+"Clustering_info.dat";
   ofstream outC (fstr.c_str());
   for(auto str : Vclu_info)
     outC<<str<<endl;
   outC.close(); outC.clear();
   vector<vector<string> > Vpreds;
   int nout=Vclu_xyz.size();
   if(nout>Nout) nout=Nout;
   for(int ii=0;ii<nout;ii++) {
     vector<string> Vxyz=Vclu_xyz[ii];
     Vxyz.erase(Vxyz.begin());
     Vpreds.push_back(Vxyz);
   }
   if(energy_minimize_CG(outDIR,Vpreds,lmp)) return 1;
   vector<vector<string> > VVpdbs;
   cout<<"  Recover all-atom..."<<endl;
   output_PDB(Vpreds,VVpdbs,coeffDIR);
   cout<<"  Obtain "<<VVpdbs.size()<<" 3D predicted structures."<<endl;
   fstr=outDIR+Name+"_IsRNAcirc.pdb";
   ofstream outP (fstr.c_str());
   for(int ii=0;ii<VVpdbs.size();ii++) {
     outP<<"MODEL        "<<ii+1<<endl;
     for(auto str : VVpdbs[ii])
       outP<<str<<endl;
     outP<<"ENDMDL"<<endl;
   }
   outP<<"END"<<endl;
   outP.close(); outP.clear();

   time (&tend);

   double dtime=difftime(tend,tstart);
   int dH=dtime/3600;
   int dM=(dtime-dH*3600)/60;
   int dS=dtime-dH*3600-dM*60;
   cout<<"Total runtime: "<<dH<<" Hours "<<dM<<" Minutes "<<dS<<" Seconds."<<endl;

   return 0;
}

← 返回文件树 · 在 GitHub 上查看