2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2013,2014,2015, by the GROMACS development team, led by
5 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6 * and including many others, as listed in the AUTHORS file in the
7 * top-level source directory and at http://www.gromacs.org.
9 * GROMACS is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public License
11 * as published by the Free Software Foundation; either version 2.1
12 * of the License, or (at your option) any later version.
14 * GROMACS is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with GROMACS; if not, see
21 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 * If you want to redistribute modifications to GROMACS, please
25 * consider that scientific software is very special. Version
26 * control is crucial - bugs must be traceable. We will be happy to
27 * consider code for inclusion in the official distribution, but
28 * derived work must not be called official GROMACS. Details are found
29 * in the README & COPYING files - if they are missing, get the
30 * official version at http://www.gromacs.org.
32 * To help us fund GROMACS development, we humbly ask that you cite
33 * the research papers on the package. Check out http://www.gromacs.org.
37 * Implements gmx::analysismodules::Freevolume.
39 * \author Titov Anatoly <Wapuk-cobaka@yandex.ru>
40 * \ingroup module_trajectoryanalysis
43 #include <gromacs/trajectoryanalysis.h>
44 #include <gromacs/trajectoryanalysis/topologyinformation.h>
45 #include <gromacs/selection/nbsearch.h>
56 // структура углов для одной краски
57 struct colorLocalAngles {
62 std::vector< double > betaAngles;
65 // хрен пойми почему, но захотелось рекурсивно сделать | можно сделать и через вайл
66 long long returnBetaEnd(const std::string ¤tLine, long long pos) {
67 switch (currentLine[pos]) {
69 returnBetaEnd(currentLine, pos + 1);
72 returnBetaEnd(currentLine, pos + 1);
78 return (pos - 1); // формально логически лишняя строчка, но Qt ругается
81 // функция парсинга одной строки
82 void parseBetaListDATLine(const std::string ¤tLine, std::vector< std::vector< unsigned int > > &localInputBL) {
83 size_t equalCount = 0;
84 std::vector< unsigned int > a;
86 for (size_t i = 0; i < currentLine.size(); ++i) {
87 if (currentLine[i] == '=') { // подсчитываем число "пустых" символов
90 long long temp = returnBetaEnd(currentLine, i);
91 if (temp - static_cast< long long >(i) > 3) {
92 localInputBL.push_back(a);
93 for (size_t j = i; j <= temp; ++j) {
94 localInputBL.back().push_back(j - equalCount);
102 // функция нахождения бета-листов в структуре по файлу ДССП
103 void betaListDigestion(const std::string &inputFile, std::vector< std::vector< std::vector< unsigned int > > > &inputBL) {
105 std::ifstream file(inputFile);
107 getline(file, line); // считываем число в первой строке - кол-во осмысленных элементов в строках - нам не нужно
109 if (line.size() > 3) {
111 inputBL.resize(inputBL.size() + 1);
112 parseBetaListDATLine(line, inputBL.back());
115 } while (line.size() > 3);
117 throw "DSSP DAT FILE IS EMPTY";
122 // функция выделения индексов для бэталистов
123 inline void aminoacidsIndexation(const std::vector< size_t > &inputIndex, const gmx::TopologyInformation &top, std::vector< std::vector< size_t > > &aminoacidsIndex) {
124 aminoacidsIndex.resize(0);
125 for (size_t i = 0; i < inputIndex.size(); ++i) {
126 aminoacidsIndex.resize(std::max(aminoacidsIndex.size(), static_cast< size_t >(top.atoms()->atom[inputIndex[i]].resind + 1)));
127 aminoacidsIndex[top.atoms()->atom[inputIndex[i]].resind].push_back(inputIndex[i]);
131 // функция поиска RVec в кадре по имени->индексу
132 gmx::RVec returnRVec(const std::vector< gmx::RVec > &frame, const std::vector< std::pair< std::string, size_t > > &colorsIndex, std::string toFind) {
133 for (auto &i : colorsIndex) {
134 if (i.first == toFind) {
135 return frame[i.second];
138 throw "WRONG COLOR ATOM NAME TO EVALUATE VECTORS";
141 // функция векторного произведения двух RVec'ов
142 inline void RVecVecMultiply(gmx::RVec &n, const gmx::RVec &a, const gmx::RVec &b) {
143 n[0] = a[1] * b[2] - a[2] * b[1];
144 n[1] = a[2] * b[0] - a[0] * b[2];
145 n[2] = a[0] * b[1] - a[2] * b[0];
148 // поиск угла между двумя RVec'ами
149 inline double RVecAngle(const gmx::RVec &a, const gmx::RVec &b) {
150 return std::acos((a[0] * b[0] + a[1] * b[1] + a[2] * b[2]) / (a.norm() * b.norm()));
153 // вычисление внутренних углов в краске
154 void colorsAnglesEvaluation(const std::vector< gmx::RVec > &frame, const std::vector< std::vector< std::pair< std::string, size_t > > > &colorsIndex, std::vector< colorLocalAngles > &colorStruct) {
155 colorStruct.resize(colorsIndex.size());
156 #pragma omp parallel for ordered schedule(dynamic)
157 for (size_t i = 0; i < colorsIndex.size(); ++i) {
158 colorStruct[i].betaAngles.resize(0);
160 colorStruct[i].a1 = returnRVec(frame, colorsIndex[i], "CAF") - returnRVec(frame, colorsIndex[i], "CAJ") + returnRVec(frame, colorsIndex[i], "CAK") - returnRVec(frame, colorsIndex[i], "CAO");
161 colorStruct[i].a1 /= colorStruct[i].a1.norm();
162 colorStruct[i].b1 = returnRVec(frame, colorsIndex[i], "CAO") - returnRVec(frame, colorsIndex[i], "CAJ") + returnRVec(frame, colorsIndex[i], "CAM") - returnRVec(frame, colorsIndex[i], "CAH") + returnRVec(frame, colorsIndex[i], "CAK") - returnRVec(frame, colorsIndex[i], "CAF");
163 colorStruct[i].b1 /= colorStruct[i].b1.norm();
164 RVecVecMultiply(colorStruct[i].n1, colorStruct[i].a1, colorStruct[i].b1);
165 colorStruct[i].n1 /= colorStruct[i].n1.norm();
167 colorStruct[i].a2 = returnRVec(frame, colorsIndex[i], "CAB") - returnRVec(frame, colorsIndex[i], "CBQ") + returnRVec(frame, colorsIndex[i], "CBP") - returnRVec(frame, colorsIndex[i], "CBL");
168 colorStruct[i].a2 /= colorStruct[i].a2.norm();
169 colorStruct[i].b2 = returnRVec(frame, colorsIndex[i], "CBL") - returnRVec(frame, colorsIndex[i], "CBQ") + returnRVec(frame, colorsIndex[i], "CBN") - returnRVec(frame, colorsIndex[i], "CBS") + returnRVec(frame, colorsIndex[i], "CBP") - returnRVec(frame, colorsIndex[i], "CAB");
170 colorStruct[i].b2 /= colorStruct[i].b2.norm();
171 RVecVecMultiply(colorStruct[i].n2, colorStruct[i].a2, colorStruct[i].b2);
172 colorStruct[i].n2 *= -1; // для "сонаправленности" векторов нормали
173 colorStruct[i].n2 /= colorStruct[i].n2.norm();
174 colorStruct[i].a12 = RVecAngle(colorStruct[i].a1, colorStruct[i].a2);
175 colorStruct[i].b12 = RVecAngle(colorStruct[i].b1, colorStruct[i].b2);
176 colorStruct[i].n12 = RVecAngle(colorStruct[i].n1, colorStruct[i].n2);
181 // вычисление направляющего вектора в бэта-листе
182 inline void betaListsRVecsEvaluation(const std::vector< gmx::RVec > &frame, const std::vector< std::vector< unsigned int > > &inputBetaLists, std::vector< gmx::RVec > &temp, const std::vector< size_t > &inputCA) {
185 for (const auto &i : inputBetaLists) {
186 tempA = frame[inputCA[i[i.size() - 1]]] + frame[inputCA[i[i.size() - 2]]] - frame[inputCA[i[1]]] - frame[inputCA[i[0]]];
187 tempA /= tempA.norm();
188 temp.push_back(tempA);
192 // определение близко ли к белку находится краска
193 bool isNearPeptide(const t_trxframe &fr, const t_pbc *pbc, const std::vector< gmx::RVec > &inputFrame,
194 gmx::AnalysisNeighborhood &nbhood, const std::vector< size_t > &inputIndex,
195 const std::vector< std::pair< std::string, size_t > > &inputColor) {
196 gmx::AnalysisNeighborhoodSearch nbsearch = nbhood.initSearch(pbc, gmx::AnalysisNeighborhoodPositions(fr.x, fr.natoms));
197 gmx::AnalysisNeighborhoodPair pair;
198 for (const auto &i : inputColor) {
199 std::cout << i.first << std::endl;
201 gmx::AnalysisNeighborhoodPairSearch pairSearch = nbsearch.startPairSearch(inputFrame[i.second].as_vec());
202 while (pairSearch.findNextPair(&pair)) {
203 std::cout << ++count << std::endl;
204 for (const auto &j : inputIndex) {
205 if (pair.refIndex() == j) {
214 // поиск ближайших к краске бэта-листов
215 inline void searchNearBetaLists(const t_trxframe &fr, const t_pbc *pbc, const std::vector< gmx::RVec > inputFrame,
216 gmx::AnalysisNeighborhood &nbhood,
217 const std::vector< std::vector< unsigned int > > inputBLists,
218 const std::vector< std::pair< std::string, size_t > > &inputColor,
219 std::vector< bool > &outputList, const std::vector< std::vector< size_t > > &inputAminoacids) {
220 outputList.resize(0);
221 outputList.resize(inputBLists.size(), false);
222 gmx::AnalysisNeighborhoodSearch nbsearch = nbhood.initSearch(pbc, gmx::AnalysisNeighborhoodPositions(fr.x, fr.natoms));
223 gmx::AnalysisNeighborhoodPair pair;
224 for (const auto &i : inputColor) {
225 while (nbsearch.startPairSearch(inputFrame[i.second].as_vec()).findNextPair(&pair)) {
226 for (size_t j = 0; j < inputBLists.size(); ++j) {
227 for (size_t k = 0; k < inputBLists[j].size(); ++k) {
228 for (size_t m = 0; m < inputAminoacids[inputBLists[j][k]].size(); ++m) {
229 if (pair.testIndex() == inputAminoacids[inputBLists[j][k]][m]) {
230 outputList[j] = true;
240 // определение углов между краской и направляющим вектором бэта-листа
241 inline void computeAnglesColorsVsBeta(const gmx::RVec &inputBetaRVec, colorLocalAngles &colorFormation) {
242 colorFormation.betaAngles.push_back(RVecAngle(inputBetaRVec, colorFormation.a1));
243 colorFormation.betaAngles.push_back(RVecAngle(inputBetaRVec, colorFormation.b1));
244 colorFormation.betaAngles.push_back(RVecAngle(inputBetaRVec, colorFormation.n1));
245 colorFormation.betaAngles.push_back(RVecAngle(inputBetaRVec, colorFormation.a2));
246 colorFormation.betaAngles.push_back(RVecAngle(inputBetaRVec, colorFormation.b2));
247 colorFormation.betaAngles.push_back(RVecAngle(inputBetaRVec, colorFormation.n2));
250 // функция записи в файл значений углов для кадра
251 void anglesFileDump(const int frameNum, const std::string &output, const std::vector< bool > &toPeptide, const std::vector< colorLocalAngles > &colorFormation) {
252 std::ofstream file(output);
254 std::vector< double > betaTemp;
256 file << "frame =" << std::setw(8) << frameNum << std::endl;
257 for (size_t i = 0; i < colorFormation.size(); ++i) {
258 file << "color #" << std::setw(3) << i;
260 file << std::setw(4) << "yes";
262 file << std::setw(4) << "no";
264 file << std::setw(7) << std::setprecision(2) << colorFormation[i].a12 << colorFormation[i].b12 << colorFormation[i].n12;
265 temp = colorFormation[i].betaAngles.size() / 6;
267 file << std::setw(4) << 0;
269 betaTemp.resize(6, 0.); // magic number, meh
270 for (size_t j = 0; j < colorFormation[i].betaAngles.size(); ++j) {
271 betaTemp[j % 6] += colorFormation[i].betaAngles[j];
273 for (size_t j = 0; j < betaTemp.size(); ++j) {
276 file << std::setw(4) << temp;
277 for (size_t j = 0; j < betaTemp.size(); ++j) {
278 file << std::setw(7) << std::setprecision(2) << betaTemp[j];
280 for (size_t j = 0; j < colorFormation[i].betaAngles.size(); ++j) {
281 file << std::setw(7) << std::setprecision(2) << colorFormation[i].betaAngles[j];
289 * \ingroup module_trajectoryanalysis
291 class colorVec : public gmx::TrajectoryAnalysisModule
298 //! Set the options and setting
299 virtual void initOptions(gmx::IOptionsContainer *options,
300 gmx::TrajectoryAnalysisSettings *settings);
302 //! First routine called by the analysis framework
303 // virtual void initAnalysis(const t_trxframe &fr, t_pbc *pbc);
304 virtual void initAnalysis(const gmx::TrajectoryAnalysisSettings &settings,
305 const gmx::TopologyInformation &top);
307 //! Call for each frame of the trajectory
308 // virtual void analyzeFrame(const t_trxframe &fr, t_pbc *pbc);
309 virtual void analyzeFrame(int frnr, const t_trxframe &fr, t_pbc *pbc,
310 gmx::TrajectoryAnalysisModuleData *pdata);
312 //! Last routine called by the analysis framework
313 // virtual void finishAnalysis(t_pbc *pbc);
314 virtual void finishAnalysis(int nframes);
316 //! Routine to write output, that is additional over the built-in
317 virtual void writeOutput();
321 gmx::SelectionList sel_;
322 std::string fnOut {"name"}; // selectable
323 std::string fnBetaListsDat; // selectable
324 float effRad {0.8}; // selectable
325 std::vector< size_t > index;
326 std::vector< size_t > indexCA;
327 std::vector< std::vector< size_t > > aminoacidsIndex;
328 std::vector< std::vector< std::pair< std::string, size_t > > > colorsNames;
329 std::vector< std::vector< std::vector< unsigned int > > > betaLists;
330 gmx::AnalysisNeighborhood nb_;
332 // Copy and assign disallowed by base.
335 colorVec::colorVec(): TrajectoryAnalysisModule()
339 colorVec::~colorVec()
352 colorVec::initOptions( gmx::IOptionsContainer *options,
353 gmx::TrajectoryAnalysisSettings *settings)
355 static const char *const desc[] = {
356 "[THISMODULE] to be done"
358 // Add the descriptive text (program help text) to the options
359 settings->setHelpText(desc);
360 // Add option for selection list
361 options->addOption(gmx::SelectionOption("sel")
363 .required().dynamicMask().multiValue()
364 .description("select pepride and colors / -sf"));
365 // Add option for input file names
366 options->addOption(gmx::StringOption("dat")
367 .store(&fnBetaListsDat)
368 .description("a file to make dynamic beta lists"));
369 // Add option for output file name
370 options->addOption(gmx::StringOption("out")
372 .description("Index file for the algorithm output."));
373 // Add option for effRad constant
374 options->addOption(gmx::FloatOption("efRad")
376 .description("max distance from colors to peptide in nm to consider to be \"near\""));
377 // Control input settings
378 settings->setFlags(gmx::TrajectoryAnalysisSettings::efNoUserPBC);
379 settings->setFlag(gmx::TrajectoryAnalysisSettings::efUseTopX);
380 //settings->setFlag(TrajectoryAnalysisSettings::efRequireTop);
381 settings->setPBC(true);
385 colorVec::initAnalysis( const gmx::TrajectoryAnalysisSettings &settings,
386 const gmx::TopologyInformation &top)
388 // считывание индекса
390 for (gmx::ArrayRef< const int >::iterator ai {sel_.front().atomIndices().begin()}; (ai < sel_.front().atomIndices().end()); ai++) {
391 index.push_back(static_cast< size_t >(*ai));
393 // считывание индекса
395 for (gmx::ArrayRef< const int >::iterator ai {sel_[1].atomIndices().begin()}; (ai < sel_[2].atomIndices().end()); ai++) {
396 index.push_back(static_cast< size_t >(*ai));
399 colorsNames.resize(sel_.size() - 2);
400 for (size_t i = 2; i < sel_.size(); ++i) {
401 for (gmx::ArrayRef< const int >::iterator ai {sel_[i].atomIndices().begin()}; (ai < sel_[i].atomIndices().end()); ai++) {
402 colorsNames[i - 2].push_back(std::make_pair(*(top.atoms()->atomname[*ai]), static_cast< size_t >(*ai)));
405 // разбор dat файла для создания бэта листов
406 betaListDigestion(fnBetaListsDat, betaLists);
407 // разбор топологии для индексации бета листов
408 aminoacidsIndexation(index, top, aminoacidsIndex);
409 // задание радиуса рассматриваемых соседей
410 nb_.setCutoff(effRad);
412 * формально можно сделать:
413 * найти соотношение между именами для углов и индексными номерами
414 * заполнить std::vector< std::vector< size_t > > nameToIndex;
415 * и в последствии считать:
416 * a1 = frame[nameToIndex[0][1] + ... - ... - ...
417 * b1 a2 b2 по аналогии только для [@<-[1, 2, 3]]
423 colorVec::analyzeFrame(int frnr, const t_trxframe &fr, t_pbc *pbc, gmx::TrajectoryAnalysisModuleData *pdata)
425 std::cout << "\tFrame analisis start ..." << std::endl;
426 std::vector< gmx::RVec > trajectoryFrame;
427 trajectoryFrame.resize(0);
428 // считывания текущего фрейма траектории
429 for (size_t i {0}; i < index.size(); ++i) {
430 trajectoryFrame.push_back(fr.x[index[i]]);
432 // подсчёт углов в красках
433 std::vector< colorLocalAngles > colorFormation;
434 std::cout << "\t\tColors' angles evaluation." << std::endl;
435 colorsAnglesEvaluation(trajectoryFrame, colorsNames, colorFormation);
436 // рассчёт положения относительно белка
438 * формально можно совместить определение близости с белком и определение ближайших бэта-листов
439 * для этого думаю нужно как-то соотнести или сделать соотношение между индексом и бэта-листами (т.е. хранить что бы за О(1) делать)
443 std::vector< bool > colorsToPeptide;
444 colorsToPeptide.resize(0);
445 colorsToPeptide.resize(colorsNames.size(), false);
446 std::cout << "\t\tWhich colors are \"near\" the pepride mass." << std::endl;
447 for (size_t i = 0; i < colorsNames.size(); ++i) {
448 colorsToPeptide[i] = isNearPeptide(fr, pbc, trajectoryFrame, nb_, index, colorsNames[i]);
450 // расчёт угла и среднего угла с ближайшими бета листами
451 std::vector< std::vector< bool > > colorsToBeta;
452 colorsToBeta.resize(0);
453 colorsToBeta.resize(colorsNames.size());
454 std::vector< std::vector< double > > colorsToBetaAngles;
455 colorsToBetaAngles.resize(0);
456 std::vector< gmx::RVec > betaListsRVecs;
457 std::cout << "\t\tBeta-lists' RVecs search." << std::endl;
458 betaListsRVecsEvaluation(trajectoryFrame, betaLists[frnr], betaListsRVecs, indexCA);
459 std::cout << "\t\tSearching nearby beta-lists." << std::endl;
460 for (size_t i = 0; i < colorsToPeptide.size(); ++i) {
461 if (colorsToPeptide[i]) {
462 searchNearBetaLists(fr, pbc, trajectoryFrame, nb_, betaLists[frnr], colorsNames[i], colorsToBeta[i], aminoacidsIndex);
465 std::cout << "\t\tComputing angles colors vs betas." << std::endl;
466 for (size_t i = 0; i < colorsToBeta.size(); ++i) {
467 for (size_t j = 0; j < colorsToBeta[i].size(); ++j) {
468 if (colorsToBeta[i][j]) {
469 computeAnglesColorsVsBeta(betaListsRVecs[j], colorFormation[i]);
473 // вывод в файл(ы) информацию для фрейма
474 std::cout << "\t\tDumping data." << std::endl;
475 anglesFileDump(frnr, fnOut, colorsToPeptide, colorFormation);
476 std::cout << "\tFrame analysed." << std::endl;
480 colorVec::finishAnalysis(int nframes)
486 colorVec::writeOutput()
490 * frame #<current frame number>
491 * color #<color number> <yes/no for "close" to peptide> a12 b12 n12 <number of beta lists> <6 avg beta angles> [<6 angles for each beta list>]
494 std::cout << "\n\t colorAngles finished successfully" << std::endl;
498 * The main function for the analysis template.
501 main(int argc, char *argv[])
503 return gmx::TrajectoryAnalysisCommandLineRunner::runAsMain<colorVec>(argc, argv);