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