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