-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathAction_GIGIST.cpp
2399 lines (2235 loc) · 88.8 KB
/
Action_GIGIST.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "Action_GIGIST.h"
#include "GIGIST_six_corr.h"
#include <iostream>
#include <iomanip>
/**
* Standard constructor
*/
Action_GIGist::Action_GIGist() :
#ifdef CUDA
NBindex_c_(nullptr),
molecule_c_(nullptr),
paramsLJ_c_(nullptr),
result_w_c_(nullptr),
result_s_c_(nullptr),
result_O_c_(nullptr),
result_N_c_(nullptr),
#endif
list_(nullptr),
top_(nullptr),
dict_(DataDictionary()),
datafile_(nullptr),
dxfile_(nullptr),
febissWaterfile_(nullptr),
wrongNumberOfAtoms_(false)
{}
/**
* The help function.
*/
void Action_GIGist::Help() const {
mprintf(" Usage:\n"
" griddim [dimx dimy dimz] Defines the dimension of the grid.\n"
" <gridcntr [x y z]> Defines the center of the grid, default [0 0 0].\n"
" <temp 300> Defines the temperature of the simulation.\n"
" <gridspacn 0.5> Defines the grid spacing\n"
" <refdens 0.0329> Defines the reference density for the water model.\n"
" <febiss 104.57> Activates FEBISS placement with given ideal water angle (only available for water)\n"
" <out \"out.dat\"> Defines the name of the output file.\n"
" <dx> Set to write out dx files. Population is always written.\n"
" <solventStart [n]> Sets the first solvent as the nth molecule (necessary for CHCl3).\n"
" The griddimensions must be set in integer values and have to be larger than 0.\n"
" The greatest advantage, stems from the fact that this code is parallelized\n"
" on the GPU.\n\n"
" The code is meant to run on the GPU. Therefore, the CPU implementation of GIST\n"
" in this code is probably slower than the original GIST implementation.\n\n"
" When using this GIST implementation please cite:\n"
"# Johannes Kraml, Anna S. Kamenik, Franz Waibl, Michael Schauperl, Klaus R. Liedl, JCTC (2019)\n"
"# Steven Ramsey, Crystal Nguyen, Romelia Salomon-Ferrer, Ross C. Walker, Michael K. Gilson, and Tom Kurtzman\n"
"# J. Comp. Chem. 37 (21) 2016\n"
"# Crystal Nguyen, Michael K. Gilson, and Tom Young, arXiv:1108.4876v1 (2011)\n"
"# Crystal N. Nguyen, Tom Kurtzman Young, and Michael K. Gilson,\n"
"# J. Chem. Phys. 137, 044101 (2012)\n"
"# Lazaridis, J. Phys. Chem. B 102, 3531–3541 (1998)\n");
}
Action_GIGist::~Action_GIGist() {
// The GPU memory should already be freed, but just in case...
#ifdef CUDA
freeGPUMemory();
#endif
}
/*****
* @brief Calculate the start of the grid.
*
* Calculates the start of the grid, using the center, stepsize in each
* dimension and the voxel Size.
*/
void Action_GIGist::calcGridStart() noexcept
{
info_.grid.start.SetVec(info_.grid.center[0] - (info_.grid.dimensions[0] * 0.5) * info_.grid.voxelSize,
info_.grid.center[1] - (info_.grid.dimensions[1] * 0.5) * info_.grid.voxelSize,
info_.grid.center[2] - (info_.grid.dimensions[2] * 0.5) * info_.grid.voxelSize);
}
/*****
* @brief Calculate the end of the grid.
*
* Calculates the end of the grid, using the center, stepsize in each
* dimension and the voxel Size.
*/
void Action_GIGist::calcGridEnd() noexcept
{
info_.grid.end.SetVec(info_.grid.center[0] + info_.grid.dimensions[0] * info_.grid.voxelSize,
info_.grid.center[1] + info_.grid.dimensions[1] * info_.grid.voxelSize,
info_.grid.center[2] + info_.grid.dimensions[2] * info_.grid.voxelSize);
}
/*****
* @brief Get the info of the system.
*
* A helper function that takes the system specific information
* that is supplied by the user.
*/
void Action_GIGist::getSystemInfo(ArgList &argList)
{
info_.system.temperature = argList.getKeyDouble("temp", 300.0);
info_.system.rho0 = argList.getKeyDouble("refdens", 0.0329);
info_.system.nFrames = 0;
}
/*****
* @brief Get settings for the GIST calculation.
*
* This function takes the settings supplied by the user and sets the
* appropriate values.
*/
void Action_GIGist::getGistSettings(ArgList &argList)
{
info_.gist.solventStart = argList.getKeyInt("solventStart", -1);
info_.gist.neighborCutoff = argList.getKeyDouble("neighbour", 3.5);
info_.gist.neighborCutoff *= info_.gist.neighborCutoff;
info_.gist.calcEnergy = !(argList.hasKey("skipE"));
info_.gist.writeDx = argList.hasKey("dx");
info_.gist.doorder = argList.hasKey("doorder");
info_.gist.useCOM = argList.hasKey("com");
info_.gist.febiss = argList.hasKey("febiss");
}
/*****
* @brief Grid Calculation.
*
* Builds the grid structure from the settings of the user and then creates
* the logical concepts.
*/
bool Action_GIGist::buildGrid(ArgList &argList)
{
info_.grid.voxelSize = argList.getKeyDouble("gridspacn", 0.5);
info_.grid.voxelVolume = info_.grid.voxelSize * info_.grid.voxelSize * info_.grid.voxelSize;
if (argList.Contains("griddim")) {
ArgList dimArgs = argList.GetNstringKey("griddim", 3);
info_.grid.dimensions[0] = dimArgs.getNextInteger(-1.0);
info_.grid.dimensions[1] = dimArgs.getNextInteger(-1.0);
info_.grid.dimensions[2] = dimArgs.getNextInteger(-1.0);
if ( (info_.grid.dimensions[0] <= 0) ||
(info_.grid.dimensions[1] <= 0) ||
(info_.grid.dimensions[2] <= 0) ) {
mprinterr("Error: griddimension must be positive integers (non zero).\n\n");
return false;
}
info_.grid.nVoxels = info_.grid.dimensions[0] * info_.grid.dimensions[1] * info_.grid.dimensions[2];
} else {
mprinterr("Error: Dimensions must be set!\n\n");
return false;
}
double x = 0, y = 0, z = 0;
if (argList.Contains("gridcntr")) {
ArgList cntrArgs = argList.GetNstringKey("gridcntr", 3);
x = cntrArgs.getNextDouble(-1);
y = cntrArgs.getNextDouble(-1);
z = cntrArgs.getNextDouble(-1);
} else {
mprintf("Warning: No grid center specified, defaulting to origin!\n\n");
}
info_.grid.center.SetVec(x, y, z);
calcGridStart();
calcGridEnd();
return true;
}
/***
* Document in header FILE!
*
*/
bool Action_GIGist::analyzeInfo(ArgList &argList)
{
getSystemInfo(argList);
getGistSettings(argList);
bool ret{ buildGrid(argList) };
#ifdef CUDA
if (info_.gist.doorder && !info_.gist.calcEnergy) {
mprinterr("Error: For CUDA code, if energy is not calculated, order parameter cannot be calculated.");
ret = false;
}
#endif
return ret;
}
/*****
* @brief Print citation and info.
*/
void Action_GIGist::printCitationInfo() const noexcept
{
mprintf("Center: %g %g %g, Dimensions %d %d %d\n"
" When using this GIST implementation please cite:\n"
"# Johannes Kraml, Anna S. Kamenik, Franz Waibl, Michael Schauperl, Klaus R. Liedl, JCTC (2019)\n"
"# Steven Ramsey, Crystal Nguyen, Romelia Salomon-Ferrer, Ross C. Walker, Michael K. Gilson, and Tom Kurtzman\n"
"# J. Comp. Chem. 37 (21) 2016\n"
"# Crystal Nguyen, Michael K. Gilson, and Tom Young, arXiv:1108.4876v1 (2011)\n"
"# Crystal N. Nguyen, Tom Kurtzman Young, and Michael K. Gilson,\n"
"# J. Chem. Phys. 137, 044101 (2012)\n"
"# Lazaridis, J. Phys. Chem. B 102, 3531–3541 (1998)\n",
info_.grid.center[0],
info_.grid.center[1],
info_.grid.center[2],
static_cast<int>( info_.grid.dimensions[0] ),
static_cast<int>( info_.grid.dimensions[1] ),
static_cast<int>( info_.grid.dimensions[2] )
);
}
/*****
* @brief Prepare the variables for the calculation on the GPU.
*
* The different variables are set and prepared (i.e., memory allocated), so
* that the calculation on the GPU can be performed without any problems.
*/
bool Action_GIGist::prepareGPUCalc(ActionSetup &setup) {
#ifdef CUDA
if (info_.gist.calcEnergy) {
NonbondParmType nb{ setup.Top().Nonbond() };
NBIndex_ = nb.NBindex();
numberAtomTypes_ = nb.Ntypes();
for (unsigned int i = 0; i < nb.NBarray().size(); ++i) {
lJParamsA_.push_back( (float) nb.NBarray().at(i).A() );
lJParamsB_.push_back( (float) nb.NBarray().at(i).B() );
}
try {
allocateCuda_GIGIST(((void**)&NBindex_c_), NBIndex_.size() * sizeof(int));
allocateCuda_GIGIST((void**)&result_w_c_, info_.system.numberAtoms * sizeof(float));
allocateCuda_GIGIST((void**)&result_s_c_, info_.system.numberAtoms * sizeof(float));
allocateCuda_GIGIST((void**)&result_O_c_, info_.system.numberAtoms * 4 * sizeof(int));
allocateCuda_GIGIST((void**)&result_N_c_, info_.system.numberAtoms * sizeof(int));
} catch (CudaException &e) {
mprinterr("Error: Could not allocate memory on GPU!\n");
freeGPUMemory();
return false;
}
try {
copyToGPU();
} catch (CudaException &e) {
return false;
}
}
#endif
return true;
}
/*****
* @brief Resize the vectors needed for the calculation.
*/
void Action_GIGist::resizeVectors()
{
if (info_.gist.febiss) {
hVectors_.resize( info_.grid.nVoxels );
}
centersAndRotations_.resize(info_.grid.nVoxels, info_.system.numberSolvent * info_.system.nFrames);
}
/*****
* @brief Create the needed datafiles and datasets.
*
* This function creates the neceesary datasets, as well as datafiles. For the
* datasets, there are multiple different datasets, basically for the energies,
* the entropies, the dipole moments, neighbors, etc., as well as the densities
* for each atom of the solvent.
*
* @param argList The argument list that was given by the user
* @param actionInit The action initialization object
*/
void Action_GIGist::createDatasets(ArgList &argList, ActionInit &actionInit)
{
std::string outfilename{argList.GetStringKey("out", "out.dat")};
datafile_ = actionInit.DFL().AddCpptrajFile( outfilename, "GIST output" );
std::string dsname{ actionInit.DSL().GenerateDefaultName("GIST") };
result_ = std::vector<DataSet_3D *>(dict_.size());
for (unsigned int i = 0; i < dict_.size(); ++i) {
result_.at(i) = (DataSet_3D*)actionInit.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, dict_.getElement(i)));
result_.at(i)->Allocate_N_C_D(
info_.grid.dimensions[0],
info_.grid.dimensions[1],
info_.grid.dimensions[2],
info_.grid.center,
info_.grid.voxelSize
);
if (
( info_.gist.writeDx &&
dict_.getElement(i).compare("Eww") != 0 &&
dict_.getElement(i).compare("Esw") != 0 &&
dict_.getElement(i).compare("dipole_xtemp") != 0 &&
dict_.getElement(i).compare("dipole_ytemp") != 0 &&
dict_.getElement(i).compare("dipole_ztemp") != 0 &&
dict_.getElement(i).compare("order") != 0 &&
dict_.getElement(i).compare("neighbour") != 0 ) ||
i == 0
)
{
DataFile *file = actionInit.DFL().AddDataFile(dict_.getElement(i) + ".dx");
file->AddDataSet(result_.at(i));
}
}
if (info_.gist.febiss) {
this->febissWaterfile_ = actionInit.DFL().AddCpptrajFile( "febiss-waters.pdb", "GIST output");
}
}
/*****
* @brief Adds atom type information into the different vectors.
*
* This function adds the charges, atom types, masses and to which molecule a
* given atom belongs to the appropriate vectors.
*
* @param atom The atom for which the information should be extracted
*/
void Action_GIGist::addAtomType(const Atom &atom)
{
molecule_.push_back(atom.MolNum());
charges_.push_back(atom.Charge());
atomTypes_.push_back(atom.TypeIndex());
masses_.push_back(atom.Mass());
}
/*****
* @brief From a given molecule get all atom information needed.
*
* This function finds all the different parameters needed for the GIST
* calculation. Predominatntly, this function adds the different solvent
* specific informations about the atom. But also atom type information is
* added.
*
* @param setup The setup object, where setup stuff is safed.
* @param mol The molecule for which the atoms should be added
* @param firstRound A few informations are only needed for the first round,
* so that some things can be skipped during the other rounds.
*/
void Action_GIGist::setAtomInformation(
const ActionSetup &setup,
const Molecule& mol,
bool firstRound
)
{
int nAtoms{ mol.NumAtoms() };
for (int i = 0; i < nAtoms; ++i) {
addAtomType(setup.Top()[mol.MolUnit().Front() + i]);
// Check if the molecule is a solvent, either by the topology parameters or because force was set.
if ( (mol.IsSolvent() && info_.gist.solventStart == -1)
|| (( info_.gist.solventStart > -1 )
&&
( setup.Top()[mol.MolUnit().Front()].MolNum() >= info_.gist.solventStart ))
) {
std::string aName{ setup.Top()[mol.MolUnit().Front() + i].ElementName() };
// Check if dictionary already holds an entry for the atoms name, if not add it to
// the dictionary, if yes, add 1 to the correct solvent atom counter.
if (! (dict_.contains(aName)) ) {
dict_.add(aName);
solventAtomCounter_.push_back(1);
} else if (firstRound) {
solventAtomCounter_.at(dict_.getIndex(aName) - result_.size()) += 1;
}
// Check for the centerSolventAtom (which in this easy approximation is either C or O)
if ( weight(aName) < weight(info_.gist.centerAtom) ) {
info_.gist.centerAtom = setup.Top()[mol.MolUnit().Front() + i].ElementName();
info_.gist.centerIdx = i; // Assumes the same order of atoms.
info_.gist.centerType = setup.Top()[mol.MolUnit().Front() + i].TypeIndex();
}
// Set solvent to true
solvent_[mol.MolUnit().Front() + i] = true;
} else {
solvent_[mol.MolUnit().Front() + i] = false;
}
}
}
/*****
* @brief Goes over all molecules and sets the appropriate information for this
* molecule.
*
* Compared to the atom function, this function does not really change much by
* itself, but simply goes over all the different molecules and hands the
* different molecules to the atom function.
*
* @param setup The action setup object for setting up the GIST calculation
*/
void Action_GIGist::setMoleculeInformation(ActionSetup &setup)
{
bool firstRound{ true };
// Save different values, which depend on the molecules and/or atoms.
for (auto mol = setup.Top().MolStart();
mol != setup.Top().MolEnd(); ++mol) {
setAtomInformation(setup, *(mol.base()), firstRound);
if ((mol->IsSolvent() && info_.gist.solventStart == -1) ||
(
( info_.gist.solventStart > -1 )
&&
( setup.Top()[mol->MolUnit().Front()].MolNum() >= info_.gist.solventStart )
)
) {
firstRound = false;
}
}
}
/*****
* @brief Prepares the density grids
*
* Before this was changed, only water could be analyzed, so this stuff did
* not need to be dynamically managed. Since I changed that, this must also be
* changed, so that this is now dynamically allocated.
*/
void Action_GIGist::prepDensityGrids()
{
// Add results for the different solvent atoms.
for (unsigned int i = 0; i < (dict_.size() - result_.size()); ++i) {
resultV_.push_back(
std::vector<double>(
info_.grid.dimensions[0] *
info_.grid.dimensions[1] *
info_.grid.dimensions[2]
)
);
}
}
/*****
* @brief Prepares the quaternion calculation
*
* This function analyzes the molecule and picks appropriate atoms for the
* quaternion construction needed for the GIST calculations.
*
* @param frame The frame is needed, because for the calculation the
* coordinates are needed.
*/
void Action_GIGist::prepQuaternion(ActionFrame &frame)
{
for (Topology::mol_iterator mol = top_->MolStart(); mol < top_->MolEnd(); ++mol) {
int moleculeLength = mol->MolUnit().Back() - mol->MolUnit().Front() + 1;
if (moleculeLength < 3)
continue;
if ((mol->IsSolvent() && info_.gist.solventStart == -1 ) ||
(
( info_.gist.solventStart > -1 ) &&
( top_->operator[](mol->MolUnit().Front()).MolNum() >= info_.gist.solventStart )
)
) {
quat_indices_ = calcQuaternionIndices(mol->MolUnit().Front(), mol->MolUnit().Back(), frame.Frm().XYZ(mol->MolUnit().Front()));
break;
}
}
}
/**
* Initialize the GIST calculation by setting up the users input.
* @param argList: The argument list of the user.
* @param actionInit: The action initialization object.
* @return: Action::OK on success and Action::ERR on error.
*/
Action::RetType Action_GIGist::Init(ArgList &argList, ActionInit &actionInit, int test) {
#if defined MPI
if (actionInit.TrajComm().Size() > 1) {
mprinterr("Error: GIST cannot yet be used with MPI parallelization.\n"
" Maximum allowed processes is 1, you used %d.\n",
actionInit.TrajComm().Size());
return Action::ERR;
}
#endif
// Get Infos
if (! analyzeInfo(argList) ) {
return Action::ERR;
}
// Imaging
image_.InitImaging( true );
resizeVectors();
createDatasets(argList, actionInit);
printCitationInfo();
return Action::OK;
}
/**
* Setup for the GIST calculation. Does everything involving the Topology file.
* @param setup: The setup object of the cpptraj code libraries.
* @return: Action::OK on success, Action::ERR otherwise.
*/
Action::RetType Action_GIGist::Setup(ActionSetup &setup) {
solventAtomCounter_ = std::vector<int>();
// Setup imaging and topology parsing.
image_.SetupImaging( setup.CoordInfo().TrajBox().HasBox() );
// Save topology and topology related values
top_ = setup.TopAddress();
info_.system.numberAtoms = setup.Top().Natom();
info_.system.numberSolvent = setup.Top().Nsolvent();
//solvent_ = std::make_unique<bool []>(info_.system.numberAtoms);
solvent_ = std::unique_ptr<bool []>(new bool[info_.system.numberAtoms]);
setMoleculeInformation(setup);
prepDensityGrids();
if (!prepareGPUCalc(setup)) {
return Action::ERR;
}
return Action::OK;
}
Action_GIGist::TestObj Action_GIGist::calcBoxParameters(const ActionFrame &frame)
{
// Setting up Image type here, don't know why this is necessary at all...
if (image_.ImagingEnabled()) {
image_.SetImageType( frame.Frm().BoxCrd().Is_X_Aligned_Ortho() );
}
Matrix_3x3 ucell_m{}, recip_m{};
std::unique_ptr<float[]> recip;
std::unique_ptr<float[]> ucell;;
int boxinfo{};
// Check Boxinfo and write the necessary data into recip, ucell and boxinfo.
switch(image_.ImagingType()) {
case ImageOption::NONORTHO:
recip = std::unique_ptr<float[]>(new float[9]);
ucell = std::unique_ptr<float[]>(new float[9]);
ucell_m = frame.Frm().BoxCrd().UnitCell();
recip_m = frame.Frm().BoxCrd().FracCell();
//frame.Frm().BoxCrd().ToRecip(ucell_m, recip_m);
for (int i = 0; i < 9; ++i) {
ucell[i] = static_cast<float>( ucell_m.Dptr()[i] );
recip[i] = static_cast<float>( recip_m.Dptr()[i] );
}
boxinfo = 2;
break;
case ImageOption::ORTHO:
recip = std::unique_ptr<float[]>(new float[9]);
for (int i = 0; i < 3; ++i) {
recip[i] = static_cast<float>( frame.Frm().BoxCrd().XyzPtr()[i] );
}
ucell = nullptr;
boxinfo = 1;
break;
case ImageOption::NO_IMAGE:
recip = nullptr;
ucell = nullptr;
boxinfo = 0;
break;
default:
throw "Error: Unexpected box information found.";
}
TestObj test;
test.recip.swap(recip);
test.ucell.swap(ucell);
test.boxinfo = boxinfo;
return test;
}
void Action_GIGist::calcHVectors(
int voxel,
int headAtomIndex,
const std::vector<Vec3> &molAtomCoords)
{
Vec3 X;
Vec3 Y;
bool setX = false;
bool setY = false;
if (info_.gist.febiss){
for (unsigned int i = 0; i < molAtomCoords.size(); ++i) {
if ((int)i != headAtomIndex) {
if (setX && !setY) {
Y.SetVec(molAtomCoords.at(i)[0] - molAtomCoords.at(headAtomIndex)[0],
molAtomCoords.at(i)[1] - molAtomCoords.at(headAtomIndex)[1],
molAtomCoords.at(i)[2] - molAtomCoords.at(headAtomIndex)[2]);
hVectors_.at(voxel).push_back(Y);
Y.Normalize();
setY = true;
}
if (!setX) {
X.SetVec(molAtomCoords.at(i)[0] - molAtomCoords.at(headAtomIndex)[0],
molAtomCoords.at(i)[1] - molAtomCoords.at(headAtomIndex)[1],
molAtomCoords.at(i)[2] - molAtomCoords.at(headAtomIndex)[2]);
hVectors_.at(voxel).push_back(X);
X.Normalize();
setX = true;
}
if (setX && setY) {
break;
}
}
}
}
}
std::tuple<Vec3, int> Action_GIGist::prepCom(const Molecule& mol, const ActionFrame& frame) {
int mol_begin{ mol.MolUnit().Front() };
int mol_end{ mol.MolUnit().Back() };
Vec3 com{ calcCenterOfMass(mol_begin, mol_end, frame.Frm().XYZ(mol_begin)) };
return { com, bin(mol_begin, mol_end, com, frame) };
}
std::tuple<std::vector<DOUBLE_O_FLOAT>,
std::vector<DOUBLE_O_FLOAT>,
std::vector<int>,
std::vector<int>
> Action_GIGist::calcGPUEnergy(const ActionFrame &frame)
{
#ifdef CUDA
tEnergy_.Start();
std::vector<DOUBLE_O_FLOAT> eww_result;
std::vector<DOUBLE_O_FLOAT> esw_result;
std::vector<int> result_o( 4 * info_.system.numberAtoms );
std::vector<int> result_n( info_.system.numberAtoms );
if (info_.gist.calcEnergy){
auto boxParams{ calcBoxParameters(frame) };
// std::vector<int> result_o{ std::vector<int>(4 * info_.system.numberAtoms) };
// std::vector<int> result_n{ std::vector<int>(info_.system.numberAtoms) };
// TODO: Switch things around a bit and move the back copying to the end of the calculation.
// Then the time needed to go over all waters and the calculations that come with that can
// be hidden quite nicely behind the interaction energy calculation.
// Must create arrays from the vectors, does that by getting the address of the first element of the vector.
auto e_result{
doActionCudaEnergy_GIGIST(
frame.Frm().xAddress(),
NBindex_c_,
numberAtomTypes_,
paramsLJ_c_,
molecule_c_,
boxParams.boxinfo,
boxParams.recip.get(),
boxParams.ucell.get(),
info_.system.numberAtoms,
info_.gist.centerType,
info_.gist.neighborCutoff,
&(result_o[0]),
&(result_n[0]),
result_w_c_,
result_s_c_,
result_O_c_,
result_N_c_,
info_.gist.doorder) };
eww_result = std::move(e_result.eww);
esw_result = std::move(e_result.esw);
std::vector<std::vector<int>> order_indices{};
if (info_.gist.doorder) {
int counter{ 0 };
for (int i = 0; i < (4 * info_.system.numberAtoms); i += 4) {
++counter;
std::vector<int> temp{};
for (unsigned int j = 0; j < 4; ++j) {
temp.push_back(result_o.at(i + j));
}
order_indices.push_back(temp);
}
}
tEnergy_.Stop();
}
return { eww_result, esw_result, result_o, result_n };
#else
return {std::vector<DOUBLE_O_FLOAT>(),
std::vector<DOUBLE_O_FLOAT>(),
std::vector<int>(),
std::vector<int>()};
#endif
}
/**
* Starts the calculation of GIST. Can use either CUDA, OPENMP or single thread code.
* This function is actually way too long. Refactoring of this code might help with
* readability.
* @param frameNum: The number of the frame.
* @param frame: The frame itself.
* @return: Action::ERR on error, Action::OK if everything ran smoothly.
*/
Action::RetType Action_GIGist::DoAction(int frameNum, ActionFrame &frame) {
info_.system.nFrames++;
std::vector<DOUBLE_O_FLOAT> eww_result{};
std::vector<DOUBLE_O_FLOAT> esw_result{};
std::vector<std::vector<int> > order_indices{};
if (info_.gist.febiss && info_.system.nFrames == 1) {
this->writeOutSolute(frame);
}
if (info_.gist.useCOM && info_.system.nFrames == 1)
{
prepQuaternion(frame);
}
// CUDA necessary information
#ifdef CUDA
auto energyResults = calcGPUEnergy(frame);
eww_result = std::move(std::get<0>(energyResults));
esw_result = std::move(std::get<1>(energyResults));
#endif
std::vector<bool> onGrid(info_.system.numberAtoms, false);
/*for (unsigned int i = 0; i < onGrid.size(); ++i) {
onGrid.at(i) = false;
}*/
#if defined _OPENMP && defined CUDA
tHead_.Start();
#pragma omp parallel for
#endif
for (Topology::mol_iterator mol = top_->MolStart(); mol < top_->MolEnd(); ++mol) {
if ((mol->IsSolvent() && info_.gist.solventStart == -1) ||
(
( info_.gist.solventStart > -1 ) &&
( top_->operator[](mol->MolUnit().Front()).MolNum() >= info_.gist.solventStart )
)
) {
int headAtomIndex{ -1 };
// Keep voxel at -1 if it is not possible to put it on the grid
int voxel{ -1 };
std::vector<Vec3> molAtomCoords{};
Vec3 com{ 0, 0, 0 };
Vec3 coord{ 0, 0, 0 };
// If center of mass should be used, use this part.
if (info_.gist.useCOM) {
auto test = prepCom(*mol, frame);
com = std::get<0>(test);
coord = com;
voxel = std::get<1>(test);
}
#if !defined _OPENMP && !defined CUDA
tHead_.Start();
#endif
for (int atom1 = mol->MolUnit().Front(); atom1 < mol->MolUnit().Back(); ++atom1) {
bool first{ true };
if (solvent_[atom1]) { // Do we need that?
// Save coords for later use.
const double *vec = frame.Frm().XYZ(atom1);
molAtomCoords.push_back(Vec3(vec));
// Check if atom is "Head" atom of the solvent
// Could probably save some time here by writing head atom indices into an array.
// TODO: When assuming fixed atom position in topology, should be very easy.
if ( !info_.gist.useCOM && std::string((*top_)[atom1].ElementName()).compare(info_.gist.centerAtom) == 0 && first ) {
// Try to bin atom1 onto the grid. If it is possible, get the index and keep working,
// if not, calculate the energies between all atoms to this point.
voxel = bin(mol->MolUnit().Front(), mol->MolUnit().Back(), vec, frame);
coord = vec;
headAtomIndex = atom1 - mol->MolUnit().Front();
first = false;
} else {
size_t bin_i{}, bin_j{}, bin_k{};
if ( result_.at(dict_.getIndex("population"))->Bin().Calc(vec[0], vec[1], vec[2], bin_i, bin_j, bin_k)
/*&& bin_i < dimensions_[0] && bin_j < dimensions_[1] && bin_k < dimensions_[2]*/) {
std::string aName{ top_->operator[](atom1).ElementName() };
long voxTemp{ result_.at(dict_.getIndex("population"))->CalcIndex(bin_i, bin_j, bin_k) };
#ifdef _OPENMP
#pragma omp critical
{
#endif
try{
resultV_.at(dict_.getIndex(aName) - result_.size()).at(voxTemp) += 1.0;
} catch(std::out_of_range e)
{
std::cout << std::setprecision(30) << (size_t)((vec[0] + 35.0f) / 0.5f) << ", " << vec[1] << ", " << vec[2] << '\n';
std::cout << result_.at(dict_.getIndex("population"))->Bin().Calc(vec[0], vec[1], vec[2], bin_i, bin_j, bin_k) << '\n';
std::cout << bin_i << " " << bin_j << " " << bin_k << '\n';
std::cout << voxTemp << '\n';
throw std::out_of_range("");
}
#ifdef _OPENMP
}
#endif
}
}
}
}
#if !defined _OPENMP && !defined CUDA
tHead_.Stop();
#endif
if (voxel != -1) {
calcHVectors(voxel, headAtomIndex, molAtomCoords);
#if !defined _OPENMP
tRot_.Start();
#endif
Quaternion<DOUBLE_O_FLOAT> quat{};
// Create Quaternion for the rotation from the new coordintate system to the lab coordinate system.
if (!info_.gist.useCOM) {
quat = calcQuaternion(molAtomCoords, molAtomCoords.at(headAtomIndex), headAtomIndex);
} else {
// -1 Will never evaluate to true, so in the funciton it will have no consequence.
quat = calcQuaternion(molAtomCoords, com, quat_indices_);
}
//if (quat.initialized())
//{
#ifdef _OPENMP
#pragma omp critical
{
#endif
centersAndRotations_.push_back(voxel, {coord, quat, info_.system.nFrames});
#ifdef _OPENMP
}
#endif
//}
#if !defined _OPENMP
tRot_.Stop();
#endif
// If energies are already here, calculate the energies right away.
#ifdef CUDA
/*
* Calculation of the order parameters
* Following formula:
* q = 1 - 3/8 * SUM[a>b]( cos(Thet[a,b]) + 1/3 )**2
* This, however, only makes sense for water, so please do not
* use it for any other solvent.
*/
if (info_.gist.doorder) {
double sum{ 0 };
Vec3 cent{ frame.Frm().xAddress() + (mol->MolUnit().Front() + headAtomIndex) * 3 };
std::vector<Vec3> vectors{};
switch(image_.ImagingType()) {
case ImageOption::NONORTHO:
case ImageOption::ORTHO:
{
Matrix_3x3 ucell, recip;
ucell = frame.Frm().BoxCrd().UnitCell();
recip = frame.Frm().BoxCrd().FracCell();
//frame.Frm().BoxCrd().ToRecip(ucell, recip);
Vec3 vec(frame.Frm().xAddress() + (order_indices.at(mol->MolUnit().Front() + headAtomIndex).at(0) * 3));
vectors.push_back( MinImagedVec(vec, cent, ucell, recip));
vec = Vec3(frame.Frm().xAddress() + (order_indices.at(mol->MolUnit().Front() + headAtomIndex).at(1) * 3));
vectors.push_back( MinImagedVec(vec, cent, ucell, recip));
vec = Vec3(frame.Frm().xAddress() + (order_indices.at(mol->MolUnit().Front() + headAtomIndex).at(2) * 3));
vectors.push_back( MinImagedVec(vec, cent, ucell, recip));
vec = Vec3(frame.Frm().xAddress() + (order_indices.at(mol->MolUnit().Front() + headAtomIndex).at(3) * 3));
vectors.push_back( MinImagedVec(vec, cent, ucell, recip));
}
break;
default:
vectors.push_back( Vec3( frame.Frm().xAddress() + (order_indices.at(mol->MolUnit().Front() + headAtomIndex).at(0) * 3) ) - cent );
vectors.push_back( Vec3( frame.Frm().xAddress() + (order_indices.at(mol->MolUnit().Front() + headAtomIndex).at(1) * 3) ) - cent );
vectors.push_back( Vec3( frame.Frm().xAddress() + (order_indices.at(mol->MolUnit().Front() + headAtomIndex).at(2) * 3) ) - cent );
vectors.push_back( Vec3( frame.Frm().xAddress() + (order_indices.at(mol->MolUnit().Front() + headAtomIndex).at(3) * 3) ) - cent );
}
for (int i = 0; i < 3; ++i) {
for (int j = i + 1; j < 4; ++j) {
double cosThet{ (vectors.at(i) * vectors.at(j)) / sqrt(vectors.at(i).Magnitude2() * vectors.at(j).Magnitude2()) };
sum += (cosThet + 1.0/3) * (cosThet + 1.0/3);
}
}
#ifdef _OPENMP
#pragma omp critical
{
#endif
result_.at(dict_.getIndex("order"))->UpdateVoxel(voxel, 1.0 - (3.0/8.0) * sum);
#ifdef _OPENMP
}
#endif
}
#ifdef _OPENMP
#pragma omp critical
{
#endif
result_.at(dict_.getIndex("neighbour"))->UpdateVoxel(voxel, std::get<3>(energyResults).at(mol->MolUnit().Front() + headAtomIndex));
#ifdef _OPENMP
}
#endif
// End of calculation of the order parameters
#ifndef _OPENMP
tEadd_.Start();
#endif
#ifdef _OPENMP
#pragma omp critical
{
#endif
// There is absolutely nothing to check here, as the solute can not be in place here.
for (int atom = mol->MolUnit().Front(); atom < mol->MolUnit().Back(); ++atom) {
// Just adds up all the interaction energies for this voxel.
result_.at(dict_.getIndex("Eww"))->UpdateVoxel(voxel, static_cast<double>(eww_result.at(atom)));
result_.at(dict_.getIndex("Esw"))->UpdateVoxel(voxel, static_cast<double>(esw_result.at(atom)));
}
#ifdef _OPENMP
}
#endif
#ifndef _OPENMP
tEadd_.Stop();
#endif
#endif
}
// If CUDA is used, energy calculations are already done.
#ifndef CUDA
if (voxel != -1 ) {
std::vector<Vec3> nearestWaters(4);
// Use HUGE distances at the beginning. This is defined as 3.40282347e+38F.
double distances[4]{HUGE, HUGE, HUGE, HUGE};
// Needs to be fixed, one does not need to calculate all interactions each time.
for (int atom1 = mol->MolUnit().Front(); atom1 < mol->MolUnit().Back(); ++atom1) {
double eww{ 0 };
double esw{ 0 };
// OPENMP only over the inner loop
#pragma omp parallel for
for (unsigned int atom2 = 0; atom2 < info_.system.numberAtoms; ++atom2) {
if ( (*top_)[atom1].MolNum() != (*top_)[atom2].MolNum() ) {
tEadd_.Start();
double r_2{ calcDistanceSqrd(frame, atom1, atom2) };
double energy{ calcEnergy(r_2, atom1, atom2) };
tEadd_.Stop();
if (solvent_[atom2]) {
#pragma omp atomic
eww += energy;
} else {
#pragma omp atomic
esw += energy;
}
if (atomTypes_.at(atom1) == info_.gist.centerType &&
atomTypes_.at(atom2) == info_.gist.centerType) {
if (r_2 < distances[0]) {
distances[3] = distances[2];
distances[2] = distances[1];
distances[1] = distances[0];
distances[0] = r_2;
nearestWaters.at(3) = nearestWaters.at(2);
nearestWaters.at(2) = nearestWaters.at(1);
nearestWaters.at(1) = nearestWaters.at(0);
nearestWaters.at(0) = Vec3(frame.Frm().XYZ(atom2)) - Vec3(frame.Frm().XYZ(atom1));
} else if (r_2 < distances[1]) {
distances[3] = distances[2];
distances[2] = distances[1];
distances[1] = r_2;
nearestWaters.at(3) = nearestWaters.at(2);
nearestWaters.at(2) = nearestWaters.at(1);
nearestWaters.at(1) = Vec3(frame.Frm().XYZ(atom2)) - Vec3(frame.Frm().XYZ(atom1));
} else if (r_2 < distances[2]) {
distances[3] = distances[2];
distances[2] = r_2;
nearestWaters.at(3) = nearestWaters.at(2);
nearestWaters.at(2) = Vec3(frame.Frm().XYZ(atom2)) - Vec3(frame.Frm().XYZ(atom1));
} else if (r_2 < distances[3]) {
distances[3] = r_2;
nearestWaters.at(3) = Vec3(frame.Frm().XYZ(atom2)) - Vec3(frame.Frm().XYZ(atom1));
}
if (r_2 < info_.gist.neighborCutoff) {
#ifdef _OPENMP
#pragma omp critical
{
#endif
result_.at(dict_.getIndex("neighbour"))->UpdateVoxel(voxel, 1);
#ifdef _OPENMP
}
#endif
}
}
}
}
double sum{ 0 };
for (int i = 0; i < 3; ++i) {
for (int j = i + 1; j < 4; ++j) {
double cosThet{ (nearestWaters.at(i) * nearestWaters.at(j)) /
sqrt(nearestWaters.at(i).Magnitude2() * nearestWaters.at(j).Magnitude2()) };
sum += (cosThet + 1.0/3) * (cosThet + 1.0/3);
}
}
#ifdef _OPENMP
#pragma omp critical
{
#endif
result_.at(dict_.getIndex("order"))->UpdateVoxel(voxel, 1.0 - (3.0/8.0) * sum);
eww /= 2.0;
result_.at(dict_.getIndex("Eww"))->UpdateVoxel(voxel, eww);
result_.at(dict_.getIndex("Esw"))->UpdateVoxel(voxel, esw);
#ifdef _OPENMP
}