a2887e073183c84f7abb130caa2d7e8d70b91e86
[alexxy/gromacs-dssp.git] / src / dssptools.cpp
1 /*
2 * This file is part of the GROMACS molecular simulation package.
3 *
4 * Copyright (c) 2021, 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.
8 *
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.
13 *
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.
18 *
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.
23 *
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.
31 *
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.
34 */
35 /*! \internal \file
36 * \brief
37 * Implements gmx::analysismodules::Trajectory.
38 *
39 * \author Sergey Gorelov <gorelov_sv@pnpi.nrcki.ru>
40 * \author Anatoly Titov <titov_ai@pnpi.nrcki.ru>
41 * \author Alexey Shvetsov <alexxyum@gmail.com>
42 * \ingroup module_trajectoryanalysis
43 */
44
45 /*
46     There's something wrong with energy calculations of redidues with E ≈ -0
47 */
48
49
50 #include "dssptools.h"
51
52 #include <algorithm>
53 #include "gromacs/math/units.h"
54
55 #include "gromacs/pbcutil/pbc.h"
56 #include <gromacs/trajectoryanalysis.h>
57 #include "gromacs/trajectoryanalysis/topologyinformation.h"
58 #include <set>
59 #include <fstream>
60 #include <mutex>
61 #include <iostream>
62
63 namespace gmx
64 {
65
66 namespace analysismodules
67 {
68
69 //void ResInfo::setIndex(backboneAtomTypes atomTypeName, std::size_t atomIndex)
70 //{
71 //   _ResInfo.at(static_cast<std::size_t>(atomTypeName)) = atomIndex;
72 //}
73
74 //std::size_t ResInfo::getIndex(backboneAtomTypes atomTypeName) const
75 //{
76 //   return _ResInfo[static_cast<std::size_t>(atomTypeName)];
77 //}
78
79 std::size_t ResInfo::getIndex(backboneAtomTypes atomTypeName) const{
80     return _backboneIndices[static_cast<std::size_t>(atomTypeName)];
81 }
82
83 secondaryStructures::secondaryStructures(){
84 }
85 void secondaryStructures::initiateSearch(const std::vector<ResInfo> &ResInfoMatrix, const bool PiHelicesPreferencez){
86     SecondaryStructuresStatusMap.resize(0);
87     SecondaryStructuresStringLine.resize(0);
88     std::vector<std::size_t> temp; temp.resize(0),
89     PiHelixPreference = PiHelicesPreferencez;
90     ResInfoMap = &ResInfoMatrix;
91     SecondaryStructuresStatusMap.resize(ResInfoMatrix.size());
92     SecondaryStructuresStringLine.resize(ResInfoMatrix.size(), '~');
93 }
94
95 void secondaryStructures::secondaryStructuresData::setStatus(const secondaryStructureTypes secondaryStructureTypeName){
96     SecondaryStructuresStatusArray[static_cast<std::size_t>(secondaryStructureTypeName)] = true;
97 }
98
99 void secondaryStructures::secondaryStructuresData::setStatus(const HelixPositions helixPosition, const turnsTypes turn){
100     TurnsStatusArray[static_cast<std::size_t>(turn)] = helixPosition;
101 }
102
103 bool secondaryStructures::secondaryStructuresData::getStatus(const secondaryStructureTypes secondaryStructureTypeName) const{
104     return SecondaryStructuresStatusArray[static_cast<std::size_t>(secondaryStructureTypeName)];
105 }
106
107 bool secondaryStructures::secondaryStructuresData::isBreakPartnerWith(const secondaryStructuresData *partner) const{
108     return breakPartners[0] == partner || breakPartners[1] == partner;
109 }
110
111 HelixPositions secondaryStructures::secondaryStructuresData::getStatus(const turnsTypes turn) const{
112     return TurnsStatusArray[static_cast<std::size_t>(turn)];
113 }
114
115 void secondaryStructures::secondaryStructuresData::setBreak(secondaryStructuresData *breakPartner){
116     if (breakPartners[0] == nullptr){
117         breakPartners[0] = breakPartner;
118     }
119     else{
120         breakPartners[1] = breakPartner;
121     }
122     setStatus(secondaryStructureTypes::Break);
123 }
124
125 bool secondaryStructures::hasHBondBetween(std::size_t Donor, std::size_t Acceptor) const{ // prob should add resi name comparison ?
126     if( (*ResInfoMap)[Donor].acceptor[0] == nullptr ||
127         (*ResInfoMap)[Donor].acceptor[1] == nullptr ||
128         (*ResInfoMap)[Acceptor].info == nullptr ){
129         std::cout << "Bad hbond check. Reason(s): " ;
130         if ( (*ResInfoMap)[Donor].acceptor[0] == nullptr ){
131             std::cout << "Donor has no acceptor[0]; ";
132         }
133         if ( (*ResInfoMap)[Donor].acceptor[1] == nullptr ){
134             std::cout << "Donor has no acceptor[1]; ";
135         }
136         if ( (*ResInfoMap)[Acceptor].info == nullptr ){
137             std::cout << "No info about acceptor; ";
138         }
139         std::cout << std::endl;
140         return false;
141     }
142     else {
143         std::cout << "Comparing DONOR " << Donor << " And ACCEPTOR " << Acceptor << ": ";
144         std::cout << "DONOR's acceptor adresses are " << (*ResInfoMap)[Donor].acceptor[0] << ", " << (*ResInfoMap)[Donor].acceptor[1] << " and ACCEPTOR adress is " << (*ResInfoMap)[Acceptor].info << std::endl;
145         std::cout << "DONOR's acceptors' nr are = " << (*ResInfoMap)[Donor].acceptor[0]->nr << ", " << (*ResInfoMap)[Donor].acceptor[1]->nr << " And ACCEPTOR's nr = " << (*ResInfoMap)[Acceptor].info->nr << std::endl;
146         std::cout << "DONOR's acceptors' chainID are = " << (*ResInfoMap)[Donor].acceptor[0]->chainid << ", " << (*ResInfoMap)[Donor].acceptor[1]->chainid << " And ACCEPTOR's chainID = " << (*ResInfoMap)[Acceptor].info->chainid << std::endl;
147         if( ( (*ResInfoMap)[Donor].acceptor[0] == (*ResInfoMap)[Acceptor].info && (*ResInfoMap)[Donor].acceptorEnergy[0] < HBondEnergyCutOff ) ||
148                 ( (*ResInfoMap)[Donor].acceptor[1] == (*ResInfoMap)[Acceptor].info && (*ResInfoMap)[Donor].acceptorEnergy[1] < HBondEnergyCutOff ) ){
149             std::cout << "HBond Exist" << std::endl;
150         }
151     }
152
153     return ( (*ResInfoMap)[Donor].acceptor[0] == (*ResInfoMap)[Acceptor].info && (*ResInfoMap)[Donor].acceptorEnergy[0] < HBondEnergyCutOff ) ||
154            ( (*ResInfoMap)[Donor].acceptor[1] == (*ResInfoMap)[Acceptor].info && (*ResInfoMap)[Donor].acceptorEnergy[1] < HBondEnergyCutOff );
155
156
157 }
158
159 bool secondaryStructures::NoChainBreaksBetween(std::size_t Resi1, std::size_t Resi2) const{
160     std::size_t i{Resi1}, j{Resi2}; // From i to j → i <= j
161     if ( i > j ){
162         std::swap(i, j);
163     }
164
165     for (; i != j; ++i){
166         if ( SecondaryStructuresStatusMap[i].isBreakPartnerWith(&SecondaryStructuresStatusMap[i + 1]) && SecondaryStructuresStatusMap[i + 1].isBreakPartnerWith(&SecondaryStructuresStatusMap[i]) ){
167             std::cout << "Patternsearch has detected a CHAINBREAK between " << Resi1 << " and " << Resi2 << std::endl;
168             return false;
169         }
170     }
171     return true;
172 }
173
174 bridgeTypes secondaryStructures::calculateBridge(std::size_t i, std::size_t j) const{
175     if( i < 1 || j < 1 || i + 1 >= ResInfoMap->size() || j + 1 >= ResInfoMap->size() ){
176         return bridgeTypes::None;
177     }
178     if(NoChainBreaksBetween(i - 1, i + 1) && NoChainBreaksBetween(j - 1, j + 1)){
179         if((hasHBondBetween(i + 1, j) && hasHBondBetween(j, i - 1)) || (hasHBondBetween(j + 1, i) && hasHBondBetween(i, j - 1)) ){ //possibly swap
180             return bridgeTypes::ParallelBridge;
181         }
182         else if((hasHBondBetween(i + 1, j - 1) && hasHBondBetween(j + 1, i - 1)) || (hasHBondBetween(j, i) && hasHBondBetween(i, j)) ){ //possibly swap
183             return bridgeTypes::AntiParallelBridge;
184         }
185     }
186     return bridgeTypes::None;
187 }
188
189 void secondaryStructures::analyzeBridgesAndLaddersPatterns(){
190     for(std::size_t i {1}; i + 4 < SecondaryStructuresStatusMap.size(); ++i){
191         for(std::size_t j {i + 3}; j + 1 < SecondaryStructuresStatusMap.size(); ++j ){
192             bridgeTypes type {calculateBridge(i, j)};
193             if (type == bridgeTypes::None){
194                 continue;
195             }
196             bool found {false};
197         }
198     }
199
200
201
202
203
204
205
206
207
208
209
210
211 //    for (std::size_t i{ 1 }; i < HBondsMap.front().size() - 1; ++i){
212 //        for (std::size_t j{ 1 }; j < HBondsMap.front().size() - 1; ++j){
213 //            if (std::abs(static_cast<int>(i) - static_cast<int>(j)) > 2){
214 //                if ((HBondsMap[i - 1][j] && HBondsMap[j][i + 1])    ||
215 //                    (HBondsMap[j - 1][i] && HBondsMap[i][j + 1])){
216 //                    Bridge[i].push_back(j);
217 //                }
218 //                if ((HBondsMap[i][j] && HBondsMap[j][i])    ||
219 //                    (HBondsMap[i - 1][j + 1] && HBondsMap[j - 1][i + 1])){
220 //                    AntiBridge[i].push_back(j);
221 //                }
222 //            }
223 //        }
224 //    }
225 //    for (std::size_t i{ 0 }; i < HBondsMap.front().size(); ++i){
226 //        if ((!Bridge[i].empty() || !AntiBridge[i].empty())){
227 //            setStatus(i, secondaryStructureTypes::Bulge);
228 //        }
229 //    }
230 //    for (std::size_t i{ 2 }; i + 2 < HBondsMap.front().size(); ++i){
231 //        for (std::size_t j { i - 2 }; j <= (i + 2); ++j){
232 //            if (j == i){
233 //                continue;
234 //            }
235 //            else {
236 //                for (std::vector<bridgeTypes>::const_iterator bridge {Bridges.begin()}; bridge != Bridges.end(); ++bridge ){
237 //                    if (!getBridge(*bridge)[i].empty() || !getBridge(*bridge)[j].empty()){
238 //                        for (std::size_t i_resi{ 0 }; i_resi < getBridge(*bridge)[i].size(); ++i_resi){
239 //                            for (std::size_t j_resi{ 0 }; j_resi < getBridge(*bridge)[j].size(); ++j_resi){
240 //                                if (abs(static_cast<int>(getBridge(*bridge)[i][i_resi])
241 //                                        - static_cast<int>(getBridge(*bridge)[j][j_resi]))
242 //                                        && (abs(static_cast<int>(getBridge(*bridge)[i][i_resi])
243 //                                        - static_cast<int>(getBridge(*bridge)[j][j_resi]))
244 //                                        < 5)){
245 //                                    if (j < i){
246 //                                        for (std::size_t k{ 0 }; k <= i - j; ++k){
247 //                                            setStatus(i + k, secondaryStructureTypes::Ladder);
248 //                                        }
249 //                                    }
250 //                                    else{
251 //                                        for (std::size_t k{ 0 }; k <= j - i; ++k){
252 //                                            setStatus(i + k, secondaryStructureTypes::Ladder);
253 //                                        }
254 //                                    }
255 //                                }
256 //                            }
257 //                        }
258 //                    }
259 //                }
260 //            }
261 //        }
262 //    }
263 }
264
265 void secondaryStructures::analyzeTurnsAndHelicesPatterns(){
266     for(const turnsTypes &i : { turnsTypes::Turn_4, turnsTypes::Turn_3, turnsTypes::Turn_5 }){
267         std::size_t stride {static_cast<std::size_t>(i) + 3};
268         std::cout << "Testing Helix_" << stride << std::endl;
269         for(std::size_t j {0}; j + stride < SecondaryStructuresStatusMap.size(); ++j){
270             std::cout << "Testing " << j << " and " << j + stride << std::endl;
271             if ( hasHBondBetween(j, j + stride) && NoChainBreaksBetween(j, j + stride) ){
272                 std::cout << j << " and " << j + stride << " has hbond!" << std::endl;
273                 SecondaryStructuresStatusMap[j + stride].setStatus(HelixPositions::End, i);
274
275                 for (std::size_t k {1}; k < stride; ++k){
276                     if( SecondaryStructuresStatusMap[j + k].getStatus(i) == HelixPositions::None ){
277                         SecondaryStructuresStatusMap[j + k].setStatus(HelixPositions::Middle, i);
278                         SecondaryStructuresStatusMap[j + k].setStatus(secondaryStructureTypes::Turn);
279                     }
280
281                 }
282
283                 if( SecondaryStructuresStatusMap[j].getStatus(i) == HelixPositions::End ){
284                     SecondaryStructuresStatusMap[j].setStatus(HelixPositions::Start_AND_End, i);
285                 }
286                 else {
287                     SecondaryStructuresStatusMap[j].setStatus(HelixPositions::Start, i);
288                 }
289             }
290         }
291     }
292
293     for(const turnsTypes &i : { turnsTypes::Turn_4, turnsTypes::Turn_3, turnsTypes::Turn_5 }){
294         std::size_t stride {static_cast<std::size_t>(i) + 3};
295         for(std::size_t j {1}; j + stride < SecondaryStructuresStatusMap.size(); ++j){
296             if ( (SecondaryStructuresStatusMap[j - 1].getStatus(i) == HelixPositions::Start || SecondaryStructuresStatusMap[j - 1].getStatus(i) == HelixPositions::Start_AND_End ) &&
297                  (SecondaryStructuresStatusMap[j].getStatus(i) == HelixPositions::Start || SecondaryStructuresStatusMap[j].getStatus(i) == HelixPositions::Start_AND_End ) ){
298                 bool empty = true;
299                 secondaryStructureTypes Helix;
300                 switch(i){
301                 case turnsTypes::Turn_3:
302                     for (std::size_t k {0}; empty && k < stride; ++k){
303                         empty = SecondaryStructuresStatusMap[j + k].getStatus(secondaryStructureTypes::Loop ) || SecondaryStructuresStatusMap[j + k].getStatus(secondaryStructureTypes::Helix_3);
304                     }
305                     Helix = secondaryStructureTypes::Helix_3;
306                     break;
307                 case turnsTypes::Turn_5:
308                     for (std::size_t k {0}; empty && k < stride; ++k){
309                         empty = SecondaryStructuresStatusMap[j + k].getStatus(secondaryStructureTypes::Loop ) || SecondaryStructuresStatusMap[j + k].getStatus(secondaryStructureTypes::Helix_5) || (PiHelixPreference && SecondaryStructuresStatusMap[j + k].getStatus(secondaryStructureTypes::Helix_4)); //TODO
310                     }
311                     Helix = secondaryStructureTypes::Helix_5;
312                     break;
313                 default:
314                     Helix = secondaryStructureTypes::Helix_4;
315                     break;
316                 }
317                 if ( empty || Helix == secondaryStructureTypes::Helix_4 ){
318                     for(std::size_t k {0}; k < stride - 1; ++k ){
319                         SecondaryStructuresStatusMap[j + k].setStatus(Helix);
320                     }
321                 }
322             }
323         }
324     }
325
326 //    for(std::size_t i {1}; i + 1 < SecondaryStructuresStatusMap.size(); ++i){
327 //        if (SecondaryStructuresStatusMap[i].getStatus(secondaryStructureTypes::Loop)){
328 //            bool isTurn = false;
329 //            for(const turnsTypes &j : {turnsTypes::Turn_3, turnsTypes::Turn_4, turnsTypes::Turn_5}){
330 //                std::size_t stride {static_cast<std::size_t>(i) + 3};
331 //                for(std::size_t k {1}; k < stride; ++k){
332 //                    isTurn = (i >= k) && (SecondaryStructuresStatusMap[i - k].getStatus(j) == HelixPositions::Start || SecondaryStructuresStatusMap[i - k].getStatus(j) == HelixPositions::Start_AND_End) ;
333 //                }
334 //            }
335
336 //            if (isTurn){
337 //                SecondaryStructuresStatusMap[i].setStatus(secondaryStructureTypes::Turn);
338 //            }
339 //            else if (SecondaryStructuresStatusMap[i].getStatus(secondaryStructureTypes::Bend)){
340 //                SecondaryStructuresStatusMap[i].setStatus(secondaryStructureTypes::Bend);
341 //            }
342 //        }
343 //    }
344
345 }
346
347 void secondaryStructures::analyzePPHelicesPatterns(){}
348
349 std::string secondaryStructures::patternSearch(){
350
351
352 //    analyzeBridgesAndLaddersPatterns();
353     analyzeTurnsAndHelicesPatterns();
354 //    analyzePPHelicesPatterns();
355
356 //    for(std::size_t i {0}; i < ResInfoMap->size(); ++i){
357 //        std::cout << (*ResInfoMap)[i].info->nr << " " << *((*ResInfoMap)[i].info->name) << std::endl;
358 //    }
359
360 //    std::cout.precision(5);
361 //    for(std::size_t i{0}; i < ResInfoMap->size(); ++i, std::cout << std::endl << std::endl){
362 //        std::cout << (*ResInfoMap)[i].info->nr << " " << *((*ResInfoMap)[i].info->name) ;
363 //        if ( (*ResInfoMap)[i].donor[0] != nullptr ){
364 //            std::cout << " has donor[0] = " << (*ResInfoMap)[i].donor[0]->nr << " " << *((*ResInfoMap)[i].donor[0]->name) << " with E = " << (*ResInfoMap)[i].donorEnergy[0] << " and" ;
365 //        }
366 //        else {
367 //            std::cout << " has no donor[0] and" ;
368 //        }
369 //        if ( (*ResInfoMap)[i].acceptor[0] != nullptr ){
370 //            std::cout << " has acceptor[0] = " << (*ResInfoMap)[i].acceptor[0]->nr << " " << *((*ResInfoMap)[i].acceptor[0]->name) << " with E = " << (*ResInfoMap)[i].acceptorEnergy[0] ;
371 //        }
372 //        else {
373 //            std::cout << " has no acceptor[0]" ;
374 //        }
375 //        std::cout << std::endl << "Also, " << (*ResInfoMap)[i].info->nr << " " << *((*ResInfoMap)[i].info->name);
376 //        if ( (*ResInfoMap)[i].donor[1] != nullptr ){
377 //            std::cout << " has donor[1] = " << (*ResInfoMap)[i].donor[1]->nr << " " << *((*ResInfoMap)[i].donor[1]->name) << " with E = " << (*ResInfoMap)[i].donorEnergy[1] << " and" ;
378 //        }
379 //        else {
380 //            std::cout << " has no donor[1] and" ;
381 //        }
382 //        if ( (*ResInfoMap)[i].acceptor[1] != nullptr ){
383 //            std::cout << " has acceptor[1] = " << (*ResInfoMap)[i].acceptor[1]->nr << " " << *((*ResInfoMap)[i].acceptor[1]->name) << " with E = " << (*ResInfoMap)[i].acceptorEnergy[1] ;
384 //        }
385 //        else {
386 //            std::cout << " has no acceptor[1]" ;
387 //        }
388 //    }
389
390     /*Write Data*/
391
392     for(std::size_t i {static_cast<std::size_t>(secondaryStructureTypes::Bend)}; i != static_cast<std::size_t>(secondaryStructureTypes::Count); ++i){
393         for(std::size_t j {0}; j < SecondaryStructuresStatusMap.size(); ++j){
394             if (SecondaryStructuresStatusMap[j].getStatus(static_cast<secondaryStructureTypes>(i))){
395                 SecondaryStructuresStringLine[j] = secondaryStructureTypeNames[i] ;
396             }
397         }
398     }
399
400     /*Add breaks*/
401
402     if(SecondaryStructuresStatusMap.size() > 1){
403         for(std::size_t i {0}, linefactor{1}; i + 1 < SecondaryStructuresStatusMap.size(); ++i){
404             if( SecondaryStructuresStatusMap[i].getStatus(secondaryStructureTypes::Break) && SecondaryStructuresStatusMap[i + 1].getStatus(secondaryStructureTypes::Break) ){
405                 if(SecondaryStructuresStatusMap[i].isBreakPartnerWith(&SecondaryStructuresStatusMap[i + 1]) && SecondaryStructuresStatusMap[i + 1].isBreakPartnerWith(&SecondaryStructuresStatusMap[i]) ){
406                     SecondaryStructuresStringLine.insert(SecondaryStructuresStringLine.begin() + i + linefactor, secondaryStructureTypeNames[secondaryStructureTypes::Break]);
407                     ++linefactor;
408                 }
409             }
410         }
411     }
412     return SecondaryStructuresStringLine;
413 }
414
415 secondaryStructures::~secondaryStructures(){
416     SecondaryStructuresStatusMap.resize(0);
417     SecondaryStructuresStringLine.resize(0);
418 }
419
420 DsspTool::DsspStorage::DsspStorage(){
421     storaged_data.resize(0);
422 }
423
424 void DsspTool::DsspStorage::clearAll(){
425     storaged_data.resize(0);
426 }
427
428 std::mutex DsspTool::DsspStorage::mx;
429
430 void DsspTool::DsspStorage::storageData(int frnr, std::string data){
431     std::lock_guard<std::mutex> guardian(mx);
432     std::pair<int, std::string> datapair(frnr, data);
433     storaged_data.push_back(datapair);
434 }
435
436 std::vector<std::pair<int, std::string>> DsspTool::DsspStorage::returnData(){
437     std::sort(storaged_data.begin(), storaged_data.end());
438     return storaged_data;
439 }
440
441 void alternateNeighborhoodSearch::setCutoff(const real &cutoff_init){
442     cutoff = cutoff_init;
443 }
444
445 void alternateNeighborhoodSearch::FixAtomCoordinates(real &coordinate, const real vector_length){
446     while (coordinate < 0) {
447         coordinate += vector_length;
448     }
449     while (coordinate >= vector_length) {
450         coordinate -= vector_length;
451     }
452 }
453
454 void alternateNeighborhoodSearch::ReCalculatePBC(int &x, const int &x_max) {
455     if (x < 0) {
456         x += x_max;
457     }
458     if (x >= x_max) {
459         x -= x_max;
460     }
461 }
462
463 void alternateNeighborhoodSearch::GetMiniBoxesMap(const t_trxframe &fr, const std::vector<ResInfo> &IndexMap){
464     rvec coordinates, box_vector_length;
465     num_of_miniboxes.resize(0);
466     num_of_miniboxes.resize(3);
467     for (std::size_t i{XX}; i <= ZZ; ++i) {
468         box_vector_length[i] = std::sqrt(
469                     std::pow(fr.box[i][XX], 2) + std::pow(fr.box[i][YY], 2) + std::pow(fr.box[i][ZZ], 2));
470         num_of_miniboxes[i] = std::floor((box_vector_length[i] / cutoff)) + 1;
471     }
472     MiniBoxesMap.resize(0);
473     MiniBoxesReverseMap.resize(0);
474     MiniBoxesMap.resize(num_of_miniboxes[XX], std::vector<std::vector<std::vector<std::size_t> > >(
475                              num_of_miniboxes[YY], std::vector<std::vector<std::size_t> >(
476                              num_of_miniboxes[ZZ], std::vector<std::size_t>(
477                              0))));
478     MiniBoxesReverseMap.resize(IndexMap.size(), std::vector<std::size_t>(3));
479     for (std::vector<ResInfo>::const_iterator i {IndexMap.begin()}; i != IndexMap.end(); ++i) {
480         for (std::size_t j{XX}; j <= ZZ; ++j) {
481             coordinates[j] = fr.x[i->getIndex(backboneAtomTypes::AtomCA)][j];
482             FixAtomCoordinates(coordinates[j], box_vector_length[j]);
483         }
484         MiniBoxesMap[std::floor(coordinates[XX] / cutoff)][std::floor(coordinates[YY] / cutoff)][std::floor(
485                           coordinates[ZZ] / cutoff)].push_back(i - IndexMap.begin());
486         for (std::size_t j{XX}; j <= ZZ; ++j){
487             MiniBoxesReverseMap[i - IndexMap.begin()][j] = std::floor(coordinates[j] / cutoff);
488         }
489     }
490 }
491
492 void alternateNeighborhoodSearch::AltPairSearch(const t_trxframe &fr, const std::vector<ResInfo> &IndexMap){
493     GetMiniBoxesMap(fr, IndexMap);
494     MiniBoxSize[XX] = MiniBoxesMap.size();
495     MiniBoxSize[YY] = MiniBoxesMap.front().size();
496     MiniBoxSize[ZZ] = MiniBoxesMap.front().front().size();
497     PairMap.resize(0);
498     PairMap.resize(IndexMap.size(), std::vector<bool>(IndexMap.size(), false));
499     ResiI = PairMap.begin();
500     ResiJ = ResiI->begin();
501
502     for (std::vector<ResInfo>::const_iterator i = IndexMap.begin(); i != IndexMap.end(); ++i){
503         for (offset[XX] = -1; offset[XX] <= 1; ++offset[XX]) {
504             for (offset[YY] = -1; offset[YY] <= 1; ++offset[YY]) {
505                 for (offset[ZZ] = -1; offset[ZZ] <= 1; ++offset[ZZ]) {
506                     for (std::size_t k{XX}; k <= ZZ; ++k) {
507                         fixBox[k] = MiniBoxesReverseMap[i - IndexMap.begin()][k] + offset[k];
508                         ReCalculatePBC(fixBox[k], MiniBoxSize[k]);
509                     }
510                     for (std::size_t j{0}; j < MiniBoxesMap[fixBox[XX]][fixBox[YY]][fixBox[ZZ]].size(); ++j) {
511                         if ( (i - IndexMap.begin()) != MiniBoxesMap[fixBox[XX]][fixBox[YY]][fixBox[ZZ]][j]){
512                             PairMap[i - IndexMap.begin()][MiniBoxesMap[fixBox[XX]][fixBox[YY]][fixBox[ZZ]][j]] = true;
513                             PairMap[MiniBoxesMap[fixBox[XX]][fixBox[YY]][fixBox[ZZ]][j]][i - IndexMap.begin()] = true;
514                         }
515                     }
516                 }
517             }
518         }
519     }
520 }
521
522 bool alternateNeighborhoodSearch::findNextPair(){
523
524     if(!PairMap.size()){
525         return false;
526     }
527
528     for(; ResiI != PairMap.end(); ++ResiI, ResiJ = ResiI->begin() ){
529         for(; ResiJ != ResiI->end(); ++ResiJ){
530             if(*ResiJ){
531                 resiIpos = ResiI - PairMap.begin();
532                 resiJpos = ResiJ - ResiI->begin();
533                 if ( ResiJ != ResiI->end() ){
534                     ++ResiJ;
535                 }
536                 else if (ResiI != PairMap.end()) {
537                     ++ResiI;
538                     ResiJ = ResiI->begin();
539                 }
540                 else {
541                     return false; // ???
542                 }
543                 return true;
544             }
545         }
546     }
547
548     return false;
549 }
550
551 std::size_t alternateNeighborhoodSearch::getResiI() const {
552     return resiIpos;
553 }
554
555 std::size_t alternateNeighborhoodSearch::getResiJ() const {
556     return resiJpos;
557 }
558
559
560 DsspTool::DsspStorage DsspTool::Storage;
561
562 DsspTool::DsspTool(){
563 }
564
565 void DsspTool::calculateBends(const t_trxframe &fr, const t_pbc *pbc)
566 {
567    const float benddegree{ 70.0 }, maxdist{ 2.5 };
568    float       degree{ 0 }, vdist{ 0 }, vprod{ 0 };
569    gmx::RVec   a{ 0, 0, 0 }, b{ 0, 0, 0 };
570    for (std::size_t i{ 0 }; i + 1 < IndexMap.size(); ++i)
571    {
572        if (CalculateAtomicDistances(static_cast<int>(IndexMap[i].getIndex(backboneAtomTypes::AtomC)),
573                                     static_cast<int>(IndexMap[i + 1].getIndex(backboneAtomTypes::AtomN)),
574                                     fr,
575                                     pbc)
576            > maxdist)
577        {
578            PatternSearch.SecondaryStructuresStatusMap[i].setBreak(&PatternSearch.SecondaryStructuresStatusMap[i + 1]);
579            PatternSearch.SecondaryStructuresStatusMap[i + 1].setBreak(&PatternSearch.SecondaryStructuresStatusMap[i]);
580
581 //           std::cout << "Break between " << i + 1 << " and " << i + 2 << std::endl;
582        }
583    }
584    for (std::size_t i{ 2 }; i + 2 < IndexMap.size() ; ++i)
585    {
586        if (PatternSearch.SecondaryStructuresStatusMap[i - 2].getStatus(secondaryStructureTypes::Break) ||
587            PatternSearch.SecondaryStructuresStatusMap[i - 1].getStatus(secondaryStructureTypes::Break) ||
588            PatternSearch.SecondaryStructuresStatusMap[i].getStatus(secondaryStructureTypes::Break) ||
589            PatternSearch.SecondaryStructuresStatusMap[i + 1].getStatus(secondaryStructureTypes::Break)
590           )
591        {
592            continue;
593        }
594        for (int j{ 0 }; j < 3; ++j)
595        {
596            a[j] = fr.x[IndexMap[i].getIndex(backboneAtomTypes::AtomCA)][j]
597                   - fr.x[IndexMap[i - 2].getIndex(backboneAtomTypes::AtomCA)][j];
598            b[j] = fr.x[IndexMap[i + 2].getIndex(backboneAtomTypes::AtomCA)][j]
599                   - fr.x[IndexMap[i].getIndex(backboneAtomTypes::AtomCA)][j];
600        }
601        vdist = (a[0] * b[0]) + (a[1] * b[1]) + (a[2] * b[2]);
602        vprod = CalculateAtomicDistances(IndexMap[i - 2].getIndex(backboneAtomTypes::AtomCA),
603                                         IndexMap[i].getIndex(backboneAtomTypes::AtomCA),
604                                         fr,
605                                         pbc)
606                * gmx::c_angstrom / gmx::c_nano
607                * CalculateAtomicDistances(IndexMap[i].getIndex(backboneAtomTypes::AtomCA),
608                                           IndexMap[i + 2].getIndex(backboneAtomTypes::AtomCA),
609                                           fr,
610                                           pbc)
611                * gmx::c_angstrom / gmx::c_nano;
612        degree = std::acos(vdist / vprod) * gmx::c_rad2Deg;
613        if (degree > benddegree)
614        {
615            PatternSearch.SecondaryStructuresStatusMap[i].setStatus(secondaryStructureTypes::Bend);
616        }
617    }
618 }
619
620 void DsspTool::calculateHBondEnergy(ResInfo& Donor,
621                        ResInfo& Acceptor,
622                        const t_trxframe&          fr,
623                        const t_pbc*               pbc)
624 {
625    /*
626     * DSSP uses eq from dssp 2.x
627     * kCouplingConstant = 27.888,  //  = 332 * 0.42 * 0.2
628     * E = k * (1/rON + 1/rCH - 1/rOH - 1/rCN) where CO comes from one AA and NH from another
629     * if R is in A
630     * Hbond if E < -0.5
631     *
632     * For the note, H-Bond Donor is N-H («Donor of H») and H-Bond Acceptor is C=O («Acceptor of H»)
633     *
634     */
635
636     if (CalculateAtomicDistances(
637                 Donor.getIndex(backboneAtomTypes::AtomCA), Acceptor.getIndex(backboneAtomTypes::AtomCA), fr, pbc)
638         >= minimalCAdistance)
639     {
640         return void();
641     }
642
643     const float kCouplingConstant = 27.888;
644     const float minimalAtomDistance{ 0.5 },
645             minEnergy{ -9.9 };
646     float HbondEnergy{ 0 };
647     float distanceNO{ 0 }, distanceHC{ 0 }, distanceHO{ 0 }, distanceNC{ 0 };
648
649 //    std::cout << "For Donor №" << Donor.info->nr - 1 << " and Accpetor №" << Acceptor.info->nr - 1 << std::endl;
650
651     if( !(Donor.is_proline) && (Acceptor.getIndex(backboneAtomTypes::AtomC) && Acceptor.getIndex(backboneAtomTypes::AtomO)
652                                 && Donor.getIndex(backboneAtomTypes::AtomN) && ( Donor.getIndex(backboneAtomTypes::AtomH) || initParams.addHydrogens ) ) ){ // TODO
653         distanceNO = CalculateAtomicDistances(
654                Donor.getIndex(backboneAtomTypes::AtomN), Acceptor.getIndex(backboneAtomTypes::AtomO), fr, pbc);
655         distanceNC = CalculateAtomicDistances(
656                Donor.getIndex(backboneAtomTypes::AtomN), Acceptor.getIndex(backboneAtomTypes::AtomC), fr, pbc);
657         if (initParams.addHydrogens){
658             if (Donor.prevResi != nullptr && Donor.prevResi->getIndex(backboneAtomTypes::AtomC) && Donor.prevResi->getIndex(backboneAtomTypes::AtomO)){
659                rvec atomH{};
660                float prevCODist {CalculateAtomicDistances(Donor.prevResi->getIndex(backboneAtomTypes::AtomC), Donor.prevResi->getIndex(backboneAtomTypes::AtomO), fr, pbc)};
661                for (int i{XX}; i <= ZZ; ++i){
662                    float prevCO = fr.x[Donor.prevResi->getIndex(backboneAtomTypes::AtomC)][i] - fr.x[Donor.prevResi->getIndex(backboneAtomTypes::AtomO)][i];
663                    atomH[i] = fr.x[Donor.getIndex(backboneAtomTypes::AtomH)][i]; // Но на самом деле берутся координаты N
664                    atomH[i] += prevCO / prevCODist;
665                }
666                distanceHO = CalculateAtomicDistances(atomH, Acceptor.getIndex(backboneAtomTypes::AtomO), fr, pbc);
667                distanceHC = CalculateAtomicDistances(atomH, Acceptor.getIndex(backboneAtomTypes::AtomC), fr, pbc);
668             }
669             else{
670                 distanceHO = distanceNO;
671                 distanceHC = distanceNC;
672             }
673        }
674        else {
675            distanceHO = CalculateAtomicDistances(
676                    Donor.getIndex(backboneAtomTypes::AtomH), Acceptor.getIndex(backboneAtomTypes::AtomO), fr, pbc);
677            distanceHC = CalculateAtomicDistances(
678                    Donor.getIndex(backboneAtomTypes::AtomH), Acceptor.getIndex(backboneAtomTypes::AtomC), fr, pbc);
679        }
680        if ((distanceNO < minimalAtomDistance) || (distanceHC < minimalAtomDistance)
681         || (distanceHO < minimalAtomDistance) || (distanceNC < minimalAtomDistance))
682        {
683             HbondEnergy = minEnergy;
684        }
685        else{
686            HbondEnergy =
687                    kCouplingConstant
688                    * ((1 / distanceNO) + (1 / distanceHC) - (1 / distanceHO) - (1 / distanceNC));
689        }
690
691 //       std::cout << "CA-CA distance: " << CalculateAtomicDistances(
692 //                        Donor.getIndex(backboneAtomTypes::AtomCA), Acceptor.getIndex(backboneAtomTypes::AtomCA), fr, pbc) << std::endl;
693 //       std::cout << "N-O distance: " << distanceNO << std::endl;
694 //       std::cout << "N-C distance: " << distanceNC << std::endl;
695 //       std::cout << "H-O distance: " << distanceHO << std::endl;
696 //       std::cout << "H-C distance: " << distanceHC << std::endl;
697
698        HbondEnergy = std::round(HbondEnergy * 1000) / 1000;
699
700        if ( HbondEnergy < minEnergy ){
701             HbondEnergy = minEnergy;
702        }
703
704 //       std::cout << "Calculated energy = " << HbondEnergy << std::endl;
705     }
706 //    else{
707 //        std::cout << "Donor Is Proline" << std::endl;
708 //    }
709
710     if (HbondEnergy < Donor.acceptorEnergy[0]){
711            Donor.acceptor[1] = Donor.acceptor[0];
712            Donor.acceptor[0] = Acceptor.info;
713            Donor.acceptorEnergy[0] = HbondEnergy;
714     }
715     else if (HbondEnergy < Donor.acceptorEnergy[1]){
716            Donor.acceptor[1] = Acceptor.info;
717            Donor.acceptorEnergy[1] = HbondEnergy;
718     }
719
720     if (HbondEnergy < Acceptor.donorEnergy[0]){
721            Acceptor.donor[1] = Acceptor.donor[0];
722            Acceptor.donor[0] = Donor.info;
723            Acceptor.donorEnergy[0] = HbondEnergy;
724     }
725     else if (HbondEnergy < Acceptor.donorEnergy[1]){
726            Acceptor.donor[1] = Donor.info;
727            Acceptor.donorEnergy[1] = HbondEnergy;
728     }
729 }
730
731
732 /* Calculate Distance From B to A */
733 float DsspTool::CalculateAtomicDistances(const int &A, const int &B, const t_trxframe &fr, const t_pbc *pbc)
734 {
735    gmx::RVec r{ 0, 0, 0 };
736    pbc_dx(pbc, fr.x[A], fr.x[B], r.as_vec());
737    return r.norm() * gmx::c_nm2A; // НЕ ТРОГАТЬ
738 }
739
740 /* Calculate Distance From B to A, where A is only fake coordinates */
741 float DsspTool::CalculateAtomicDistances(const rvec &A, const int &B, const t_trxframe &fr, const t_pbc *pbc)
742 {
743    gmx::RVec r{ 0, 0, 0 };
744    pbc_dx(pbc, A, fr.x[B], r.as_vec());
745    return r.norm() * gmx::c_nm2A; // НЕ ТРОГАТЬ
746 }
747
748 void DsspTool::initAnalysis(/*const TrajectoryAnalysisSettings &settings,*/const TopologyInformation& top, const initParameters &initParamz)
749 {
750    initParams = initParamz;
751    ResInfo _backboneAtoms;
752    std::size_t                 i{ 0 };
753    std::string proLINE;
754    int resicompare{ top.atoms()->atom[static_cast<std::size_t>(*(initParams.sel_.atomIndices().begin()))].resind };
755    IndexMap.resize(0);
756    IndexMap.push_back(_backboneAtoms);
757    IndexMap[i].info = &(top.atoms()->resinfo[resicompare]);
758    proLINE = *(IndexMap[i].info->name);
759    if( proLINE.compare("PRO") == 0 ){
760        IndexMap[i].is_proline = true;
761    }
762
763    for (gmx::ArrayRef<const int>::iterator ai{ initParams.sel_.atomIndices().begin() }; (ai != initParams.sel_.atomIndices().end()); ++ai){
764        if (resicompare != top.atoms()->atom[static_cast<std::size_t>(*ai)].resind)
765        {
766            ++i;
767            resicompare = top.atoms()->atom[static_cast<std::size_t>(*ai)].resind;
768            IndexMap.emplace_back(_backboneAtoms);
769            IndexMap[i].info = &(top.atoms()->resinfo[resicompare]);
770            proLINE = *(IndexMap[i].info->name);
771            if( proLINE.compare("PRO") == 0 ){
772                IndexMap[i].is_proline = true;
773            }
774
775        }
776        std::string atomname(*(top.atoms()->atomname[static_cast<std::size_t>(*ai)]));
777        if (atomname == backboneAtomTypeNames[backboneAtomTypes::AtomCA])
778        {
779            IndexMap[i]._backboneIndices[static_cast<std::size_t>(backboneAtomTypes::AtomCA)] = *ai;
780        }
781        else if (atomname == backboneAtomTypeNames[backboneAtomTypes::AtomC])
782        {
783            IndexMap[i]._backboneIndices[static_cast<std::size_t>(backboneAtomTypes::AtomC)] = *ai;
784        }
785        else if (atomname == backboneAtomTypeNames[backboneAtomTypes::AtomO])
786        {
787            IndexMap[i]._backboneIndices[static_cast<std::size_t>(backboneAtomTypes::AtomO)] = *ai;
788        }
789        else if (atomname == backboneAtomTypeNames[backboneAtomTypes::AtomN])
790        {
791            IndexMap[i]._backboneIndices[static_cast<std::size_t>(backboneAtomTypes::AtomN)] = *ai;
792            if (initParamz.addHydrogens == true){
793                IndexMap[i]._backboneIndices[static_cast<std::size_t>(backboneAtomTypes::AtomH)] = *ai;
794            }
795        }
796        else if (atomname == backboneAtomTypeNames[backboneAtomTypes::AtomH] && initParamz.addHydrogens == false) // Юзать водород в структуре
797        {
798            IndexMap[i]._backboneIndices[static_cast<std::size_t>(backboneAtomTypes::AtomH)] = *ai;
799        }
800
801
802
803 //       if( atomname == backboneAtomTypeNames[backboneAtomTypes::AtomCA] || atomname == backboneAtomTypeNames[backboneAtomTypes::AtomC] || atomname == backboneAtomTypeNames[backboneAtomTypes::AtomO]
804 //       || atomname == backboneAtomTypeNames[backboneAtomTypes::AtomN] || atomname == backboneAtomTypeNames[backboneAtomTypes::AtomH]){
805 //           std::cout << "Atom " << atomname << " №" << *ai << " From Resi " << *(top.atoms()->resinfo[i].name) << " №" << resicompare << std::endl;
806 //       }
807    }
808
809    for (std::size_t j {1}; j < IndexMap.size(); ++j){
810        IndexMap[j].prevResi = &(IndexMap[j - 1]);
811
812        IndexMap[j - 1].nextResi = &(IndexMap[j]);
813
814 //           std::cout << "Resi " << IndexMap[i].info->nr << *(IndexMap[i].info->name) << std::endl;
815 //           std::cout << "Prev resi is " << IndexMap[i].prevResi->info->nr << *(IndexMap[i].prevResi->info->name) << std::endl;
816 //           std::cout << "Prev resi's next resi is " << IndexMap[i - 1].nextResi->info->nr << *(IndexMap[i - 1].nextResi->info->name) << std::endl;
817 //         std::cout << IndexMap[j].prevResi->info->nr;
818 //         std::cout << *(IndexMap[j].prevResi->info->name) ;
819 //         std::cout << " have CA = " << IndexMap[j].prevResi->getIndex(backboneAtomTypes::AtomCA) ;
820 //         std::cout << " C = " << IndexMap[j].prevResi->getIndex(backboneAtomTypes::AtomC);
821 //         std::cout << " O = " << IndexMap[j].prevResi->getIndex(backboneAtomTypes::AtomO);
822 //         std::cout << " N = " << IndexMap[j].prevResi->getIndex(backboneAtomTypes::AtomN);
823 //         std::cout << " H = " << IndexMap[j].prevResi->getIndex(backboneAtomTypes::AtomH) << std::endl;
824    }
825
826    nres = i + 1;
827 }
828
829 void DsspTool::analyzeFrame(int frnr, const t_trxframe &fr, t_pbc *pbc)
830 {
831
832     switch(initParams.NBS){
833     case (NBSearchMethod::Classique): {
834
835         // store positions of CA atoms to use them for nbSearch
836         std::vector<gmx::RVec> positionsCA_;
837         for (std::size_t i{ 0 }; i < IndexMap.size(); ++i)
838         {
839             positionsCA_.emplace_back(fr.x[IndexMap[i].getIndex(backboneAtomTypes::AtomCA)]);
840         }
841
842         AnalysisNeighborhood nb_;
843         nb_.setCutoff(initParams.cutoff_);
844         AnalysisNeighborhoodPositions       nbPos_(positionsCA_);
845         gmx::AnalysisNeighborhoodSearch     start      = nb_.initSearch(pbc, nbPos_);
846         gmx::AnalysisNeighborhoodPairSearch pairSearch = start.startPairSearch(nbPos_);
847         gmx::AnalysisNeighborhoodPair       pair;
848         while (pairSearch.findNextPair(&pair))
849         {
850             if(CalculateAtomicDistances(
851                         IndexMap[pair.refIndex()].getIndex(backboneAtomTypes::AtomCA), IndexMap[pair.testIndex()].getIndex(backboneAtomTypes::AtomCA), fr, pbc)
852                 < minimalCAdistance){
853                 calculateHBondEnergy(IndexMap[pair.refIndex()], IndexMap[pair.testIndex()], fr, pbc);
854                 if (IndexMap[pair.testIndex()].info != IndexMap[pair.refIndex() + 1].info){
855                     calculateHBondEnergy(IndexMap[pair.testIndex()], IndexMap[pair.refIndex()], fr, pbc);
856                 }
857             }
858         }
859
860         break;
861     }
862     case (NBSearchMethod::Experimental): { // TODO FIX
863
864         alternateNeighborhoodSearch as_;
865
866         as_.setCutoff(initParams.cutoff_);
867
868         as_.AltPairSearch(fr, IndexMap);
869
870         while (as_.findNextPair()){
871             if(CalculateAtomicDistances(
872                         IndexMap[as_.getResiI()].getIndex(backboneAtomTypes::AtomCA), IndexMap[as_.getResiJ()].getIndex(backboneAtomTypes::AtomCA), fr, pbc)
873                 < minimalCAdistance){
874                 calculateHBondEnergy(IndexMap[as_.getResiI()], IndexMap[as_.getResiJ()], fr, pbc);
875                 if (IndexMap[as_.getResiJ()].info != IndexMap[as_.getResiI() + 1].info){
876                     calculateHBondEnergy(IndexMap[as_.getResiJ()], IndexMap[as_.getResiI()], fr, pbc);
877                 }
878             }
879         }
880
881         break;
882     }
883     default: {
884
885         for(std::vector<ResInfo>::iterator Donor {IndexMap.begin()}; Donor != IndexMap.end() ; ++Donor){
886             for(std::vector<ResInfo>::iterator Acceptor {Donor + 1} ; Acceptor != IndexMap.end() ; ++Acceptor){
887                 if(CalculateAtomicDistances(
888                             Donor->getIndex(backboneAtomTypes::AtomCA), Acceptor->getIndex(backboneAtomTypes::AtomCA), fr, pbc)
889                     < minimalCAdistance){
890                     calculateHBondEnergy(*Donor, *Acceptor, fr, pbc);
891                     if (Acceptor != Donor + 1){
892                         calculateHBondEnergy(*Acceptor, *Donor, fr, pbc);
893                     }
894                 }
895             }
896         }
897         break;
898     }
899     }
900
901
902 //    for(std::size_t i {0}; i < IndexMap.size(); ++i){
903 //        std::cout << IndexMap[i].info->nr << " " << *(IndexMap[i].info->name) << std::endl;
904 //    }
905
906    PatternSearch.initiateSearch(IndexMap, initParams.PPHelices);
907    calculateBends(fr, pbc);
908    Storage.storageData(frnr, PatternSearch.patternSearch());
909
910 }
911
912 std::vector<std::pair<int, std::string>> DsspTool::getData(){
913     return Storage.returnData();
914 }
915
916 } // namespace analysismodules
917
918 } // namespace gmx