-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbioem.cpp
2126 lines (1911 loc) · 76.2 KB
/
bioem.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
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
< BioEM software for Bayesian inference of Electron Microscopy images>
Copyright (C) 2017 Pilar Cossio, David Rohr, Fabio Baruffa, Markus Rampp,
Luka Stanisic, Volker Lindenstruth and Gerhard Hummer.
Max Planck Institute of Biophysics, Frankfurt, Germany.
Frankfurt Institute for Advanced Studies, Goethe University Frankfurt,
Germany.
Max Planck Computing and Data Facility, Garching, Germany.
Released under the GNU Public License, v3.
See license statement for terms of distribution.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
#ifdef WITH_MPI
#include <mpi.h>
#define MPI_CHK(expr) \
if (expr != MPI_SUCCESS) \
{ \
fprintf(stderr, "Error - MPI function %s: %d\n", __FILE__, __LINE__); \
}
#endif
#include "MersenneTwister.h"
#include <algorithm>
#include <cmath>
#include <fstream>
#include <getopt.h>
#include <iostream>
#include <iterator>
#include <queue>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <vector>
#ifdef WITH_OPENMP
#include <omp.h>
#endif
#include "autotuner.h"
#include "timer.h"
#include <fftw3.h>
#include <math.h>
#include "bioem.h"
#include "map.h"
#include "model.h"
#include "param.h"
#ifdef BIOEM_USE_NVTX
#include "nvToolsExt.h"
const uint32_t colors[] = {0x0000ff00, 0x000000ff, 0x00ffff00, 0x00ff00ff,
0x0000ffff, 0x00ff0000, 0x00ffffff};
const int num_colors = sizeof(colors) / sizeof(colors[0]);
enum myColor
{
COLOR_PROJECTION,
COLOR_CONVOLUTION,
COLOR_COMPARISON,
COLOR_WORKLOAD,
COLOR_INIT
};
// Projection number is stored in category attribute
// Convolution number is stored in payload attribute
#define cuda_custom_timeslot(name, iMap, iConv, cid) \
{ \
int color_id = cid; \
color_id = color_id % num_colors; \
nvtxEventAttributes_t eventAttrib = {0}; \
eventAttrib.version = NVTX_VERSION; \
eventAttrib.size = NVTX_EVENT_ATTRIB_STRUCT_SIZE; \
eventAttrib.colorType = NVTX_COLOR_ARGB; \
eventAttrib.color = colors[color_id]; \
eventAttrib.category = iMap; \
eventAttrib.payloadType = NVTX_PAYLOAD_TYPE_UNSIGNED_INT64; \
eventAttrib.payload.llValue = iConv; \
eventAttrib.messageType = NVTX_MESSAGE_TYPE_ASCII; \
eventAttrib.message.ascii = name; \
nvtxRangePushEx(&eventAttrib); \
}
#define cuda_custom_timeslot_end nvtxRangePop();
#else
#define cuda_custom_timeslot(name, iMap, iConv, cid)
#define cuda_custom_timeslot_end
#endif
#include "bioem_algorithm.h"
using namespace std;
bioem::bioem()
{
BioEMAlgo = getenv("BIOEM_ALGO") == NULL ? 1 : atoi(getenv("BIOEM_ALGO"));
DebugOutput = getenv("BIOEM_DEBUG_OUTPUT") == NULL ?
0 :
atoi(getenv("BIOEM_DEBUG_OUTPUT"));
if (getenv("BIOEM_PROJ_CONV_AT_ONCE") != NULL)
{
nProjectionsAtOnce = atoi(getenv("BIOEM_PROJ_CONV_AT_ONCE"));
if (BioEMAlgo == 1 && getenv("GPU") && atoi(getenv("GPU")) &&
nProjectionsAtOnce > 1)
{
myWarning("Using parallel convolutions with GPUs can create race "
"condition and lead to inaccurate results. "
"BIOEM_PROJ_CONV_AT_ONCE is going to be set 1.");
nProjectionsAtOnce = 1;
}
}
else if (BioEMAlgo == 1)
nProjectionsAtOnce = 1;
else
nProjectionsAtOnce =
getenv("OMP_NUM_THREADS") == NULL ? 1 : atoi(getenv("OMP_NUM_THREADS"));
if (getenv("OMP_STACKSIZE") == NULL && nProjectionsAtOnce > 1)
{
myWarning("Using OMP parallelization without specifying OMP_STACKSIZE. "
"In case of memory issues and program crashes, consider "
"increasing OMP_STACKSIZE.");
}
if (getenv("BIOEM_CUDA_THREAD_COUNT") != NULL)
CudaThreadCount = atoi(getenv("BIOEM_CUDA_THREAD_COUNT"));
else if (BioEMAlgo == 1)
CudaThreadCount = CUDA_THREAD_COUNT_ALGO1;
else
CudaThreadCount = CUDA_THREAD_COUNT_ALGO2;
Autotuning = false;
}
bioem::~bioem() {}
void bioem::printOptions(myoption_t *myoptions, int myoptions_length)
{
printf("\nCommand line inputs:\n");
// Find longest column width
int maxlen = 0;
for (int i = 0; i < myoptions_length; i++)
{
if (myoptions[i].hidden)
continue;
if (maxlen < (int) strlen(myoptions[i].name))
maxlen = (int) strlen(myoptions[i].name);
}
for (int i = 0; i < myoptions_length; i++)
{
if (myoptions[i].hidden)
continue;
printf(" --%-*s", maxlen, myoptions[i].name);
if (myoptions[i].arg == required_argument)
printf(" arg");
else
printf(" ");
printf(" %s\n", myoptions[i].desc);
}
printf("\n");
}
int bioem::readOptions(int ac, char *av[])
{
HighResTimer timer;
// *** Inizialzing default variables ***
std::string infile, modelfile, mapfile, Inputanglefile, Inputbestmap;
Model.readPDB = false;
Model.readModelMRC = false;
param.param_device.writeAngles = 0;
param.dumpMap = false;
param.loadMap = false;
Model.dumpModel = false;
Model.loadModel = false;
Model.printCOORDREAD = false;
param.printModel = false;
RefMap.readMRC = false;
RefMap.readMultMRC = false;
param.notuniformangles = false;
OutfileName = "Output_Probabilities";
cout << " ++++++++++++ FROM COMMAND LINE +++++++++++\n\n";
// Write your options here
myoption_t myoptions[] = {
{"Modelfile", required_argument, "(Mandatory) Name of model file", false},
{"Particlesfile", required_argument,
"(Mandatory) Name of particle-image file", false},
{"Inputfile", required_argument,
"(Mandatory) Name of input parameter file", false},
{"PrintBestCalMap", required_argument,
"(Optional) Only print best calculated map. NO BioEM!", true},
{"ReadOrientation", required_argument,
"(Optional) Read file name containing orientations", false},
{"ReadPDB", no_argument, "(Optional) If reading model file in PDB format",
false},
{"ReadModelMRC", no_argument,
"(Optional) If reading model file in MRC format", false},
{"ReadMRC", no_argument,
"(Optional) If reading particle file in MRC format", false},
{"ReadMultipleMRC", no_argument, "(Optional) If reading multiple MRCs",
false},
{"DumpMaps", no_argument,
"(Optional) Dump maps after they were read from particle-image file",
false},
{"LoadMapDump", no_argument, "(Optional) Read maps from dump option",
false},
{"DumpModel", no_argument,
"(Optional) Dump model after it was read from model file", false},
{"LoadModelDump", no_argument, "(Optional) Read model from dump option",
false},
{"PrintCOORDREAD", no_argument, "(Optional) Print model coordinates",
false},
{"OutputFile", required_argument,
"(Optional) For changing the outputfile name", false},
{"help", no_argument, "(Optional) Produce help message", false}};
int myoptions_length = sizeof(myoptions) / sizeof(myoption_t);
// If not all mandatory parameters are defined
if ((ac < 2))
{
printf("Error - Need to specify all mandatory options\n");
printOptions(myoptions, myoptions_length);
return 1;
}
// Creating options structure for getopt_long()
struct option *long_options =
(option *) calloc((myoptions_length + 1), sizeof(option));
for (int i = 0; i < myoptions_length; i++)
{
long_options[i].name = myoptions[i].name;
long_options[i].has_arg = myoptions[i].arg;
}
int myopt;
while (1)
{
/* getopt_long stores the option index here. */
int option_index = 0;
myopt = getopt_long(ac, av, "", long_options, &option_index);
/* Detect the end of the options. */
if (myopt == -1)
break;
switch (myopt)
{
case 0:
#ifdef DEBUG
printf("option %s", long_options[option_index].name);
if (optarg)
printf(" with arg %s", optarg);
printf("\n");
#endif
// Here write actions for each option
if (!strcmp(long_options[option_index].name, "help"))
{
cout << "Usage: options_description [options]\n";
printOptions(myoptions, myoptions_length);
return 1;
}
if (!strcmp(long_options[option_index].name, "Inputfile"))
{
cout << "Input file is: " << optarg << "\n";
infile = optarg;
}
if (!strcmp(long_options[option_index].name, "Modelfile"))
{
cout << "Model file is: " << optarg << "\n";
modelfile = optarg;
}
if (!strcmp(long_options[option_index].name, "ReadPDB"))
{
cout << "Reading model file in PDB format.\n";
Model.readPDB = true;
}
if (!strcmp(long_options[option_index].name, "ReadModelMRC"))
{
cout << "Reading model file in MRC format.\n";
Model.readModelMRC = true;
}
if (!strcmp(long_options[option_index].name, "ReadOrientation"))
{
cout << "Reading Orientation from file: " << optarg << "\n";
cout << "Important: if using Quaternions, include ";
cout << "QUATERNIONS keyword in INPUT PARAMETER FILE\n";
cout << "First row in file should be the total number of "
"orientations (int)\n";
cout << "Euler angle format should be alpha (12.6f) beta (12.6f) "
"gamma (12.6f)\n";
cout << "Quaternion format q1 (12.6f) q2 (12.6f) q3 (12.6f) q4 "
"(12.6f)\n";
Inputanglefile = optarg;
param.notuniformangles = true;
}
if (!strcmp(long_options[option_index].name, "OutputFile"))
{
cout << "Writing OUTPUT to: " << optarg << "\n";
OutfileName = optarg;
}
if (!strcmp(long_options[option_index].name, "PrintBestCalMap"))
{
cout << "Reading best parameters from file: " << optarg << "\n";
Inputbestmap = optarg;
param.printModel = true;
}
if (!strcmp(long_options[option_index].name, "ReadMRC"))
{
cout << "Reading particle file in MRC format.\n";
RefMap.readMRC = true;
}
if (!strcmp(long_options[option_index].name, "ReadMultipleMRC"))
{
cout << "Reading multiple MRCs.\n";
RefMap.readMultMRC = true;
}
if (!strcmp(long_options[option_index].name, "DumpMaps"))
{
cout << "Dumping maps after reading from file.\n";
param.dumpMap = true;
}
if (!strcmp(long_options[option_index].name, "LoadMapDump"))
{
cout << "Loading map dump.\n";
param.loadMap = true;
}
if (!strcmp(long_options[option_index].name, "DumpModel"))
{
cout << "Dumping model after reading from file.\n";
Model.dumpModel = true;
}
if (!strcmp(long_options[option_index].name, "LoadModelDump"))
{
cout << "Loading model dump.\n";
Model.loadModel = true;
}
if (!strcmp(long_options[option_index].name, "PrintCOORDREAD"))
{
cout << "Print model coordinates.\n";
Model.printCOORDREAD = true;
}
if (!strcmp(long_options[option_index].name, "Particlesfile"))
{
cout << "Particle file is: " << optarg << "\n";
mapfile = optarg;
}
break;
case '?':
/* getopt_long already printed an error message. */
printOptions(myoptions, myoptions_length);
return 1;
default:
abort();
}
}
/* Print any remaining command line arguments (not options) and exit */
if (optind < ac)
{
printf("Error - Non-option ARGV-elements: ");
while (optind < ac)
printf("%s ", av[optind++]);
putchar('\n');
printOptions(myoptions, myoptions_length);
return 1;
}
// check for consistency in multiple MRCs
if (RefMap.readMultMRC && not(RefMap.readMRC))
{
myError("For multiple MRCs command --ReadMRC is necessary too");
}
if (DebugOutput >= 1 && mpi_rank == 0)
timer.ResetStart();
// *** Reading Parameter Input ***
if (!param.printModel)
{
// Standard definition for BioEM
param.readParameters(infile.c_str());
if (DebugOutput >= 1 && mpi_rank == 0)
{
printf("Reading Input Parameters Time: %f\n",
timer.GetCurrentElapsedTime());
timer.ResetStart();
}
// *** Reading Particle Maps Input ***
RefMap.readRefMaps(param, mapfile.c_str());
if (DebugOutput >= 1 && mpi_rank == 0)
{
printf("Reading Input Maps Time: %f\n", timer.GetCurrentElapsedTime());
timer.ResetStart();
}
}
else
{
// Reading parameters for only writting down Best projection
param.forprintBest(Inputbestmap.c_str());
}
// *** Reading Model Input ***
Model.readModel(param, modelfile.c_str());
if (DebugOutput >= 1 && mpi_rank == 0)
{
printf("Reading Input Model Time: %f\n", timer.GetCurrentElapsedTime());
timer.ResetStart();
}
// *** Printing Model Input ***
if (Model.printCOORDREAD)
{
Model.printCOOR();
if (DebugOutput >= 1 && mpi_rank == 0)
{
printf("Printing Model Coordinates Time: %f\n",
timer.GetCurrentElapsedTime());
timer.ResetStart();
}
}
// Generating Grids of orientations
if (!param.printModel)
param.CalculateGridsParam(Inputanglefile.c_str());
return (0);
}
int bioem::configure(int ac, char *av[])
{
// **************************************************************************************
// **** Configuration Routine using getopts for extracting parameters, models
// and maps ****
// **************************************************************************************
// ****** And Precalculating necessary grids, map crosscorrelations and
// kernels ********
// *************************************************************************************
HighResTimer timer;
if (mpi_rank == 0 && readOptions(ac, av))
return 1;
#ifdef WITH_MPI
// ********************* MPI inizialization/ Transfer of
// parameters******************
if (mpi_size > 1)
{
if (DebugOutput >= 2 && mpi_rank == 0)
timer.ResetStart();
MPI_Bcast(¶m, sizeof(param), MPI_BYTE, 0, MPI_COMM_WORLD);
// We have to reinitialize all pointers !!!!!!!!!!!!
if (mpi_rank != 0)
param.angprior = NULL;
if (mpi_rank != 0)
param.angles =
(myfloat3_t *) mallocchk(param.nTotGridAngles * sizeof(myfloat3_t));
MPI_Bcast(param.angles, param.nTotGridAngles * sizeof(myfloat3_t), MPI_BYTE,
0, MPI_COMM_WORLD);
#ifdef DEBUG
for (int n = 0; n < param.nTotGridAngles; n++)
{
cout << "CHECK: Angle orient " << mpi_rank << " " << n << " "
<< param.angles[n].pos[0] << " " << param.angles[n].pos[1] << " "
<< param.angles[n].pos[2] << " " << param.angles[n].quat4 << " "
<< "\n";
}
#endif
//****refCtf, CtfParam, angles automatically filled by precalculate function
// bellow
MPI_Bcast(&Model, sizeof(Model), MPI_BYTE, 0, MPI_COMM_WORLD);
if (mpi_rank != 0)
Model.points = (bioem_model::bioem_model_point *) mallocchk(
sizeof(bioem_model::bioem_model_point) * Model.nPointsModel);
MPI_Bcast(Model.points,
sizeof(bioem_model::bioem_model_point) * Model.nPointsModel,
MPI_BYTE, 0, MPI_COMM_WORLD);
MPI_Bcast(&RefMap, sizeof(RefMap), MPI_BYTE, 0, MPI_COMM_WORLD);
if (mpi_rank != 0)
RefMap.maps = (myfloat_t *) mallocchk(
RefMap.refMapSize * sizeof(myfloat_t) * RefMap.ntotRefMap);
MPI_Bcast(RefMap.maps,
RefMap.refMapSize * sizeof(myfloat_t) * RefMap.ntotRefMap,
MPI_BYTE, 0, MPI_COMM_WORLD);
if (DebugOutput >= 2 && mpi_rank == 0)
printf("MPI Broadcast of Input Data %f\n", timer.GetCurrentElapsedTime());
}
#endif
// ****************** Precalculating Necessary Stuff *********************
if (DebugOutput >= 2 && mpi_rank == 0)
timer.ResetStart();
param.PrepareFFTs();
if (DebugOutput >= 2 && mpi_rank == 0)
{
printf("Time Prepare FFTs %f\n", timer.GetCurrentElapsedTime());
timer.ResetStart();
}
precalculate();
// ****************** For debugging *********************
if (getenv("BIOEM_DEBUG_BREAK"))
{
const int cut = atoi(getenv("BIOEM_DEBUG_BREAK"));
if (param.nTotGridAngles > cut)
param.nTotGridAngles = cut;
if (param.nTotCTFs > cut)
param.nTotCTFs = cut;
}
if (DebugOutput >= 2 && mpi_rank == 0)
{
printf("Time Precalculate %f\n", timer.GetCurrentElapsedTime());
timer.ResetStart();
}
// Number of parallel Convolutions and Comparisons
param.nTotParallelConv = min(param.nTotCTFs, nProjectionsAtOnce);
// ****************** For autotuning **********************
if ((getenv("GPU") && atoi(getenv("GPU"))) && (BioEMAlgo == 1) &&
((!getenv("GPUWORKLOAD") || (atoi(getenv("GPUWORKLOAD")) == -1))) &&
(!getenv("BIOEM_DEBUG_BREAK") ||
(atoi(getenv("BIOEM_DEBUG_BREAK")) > FIRST_STABLE)))
{
Autotuning = true;
if (mpi_rank == 0)
printf("Autotuning of GPUWorkload enabled:\n\tAlgorithm "
"%d\n\tRecalibration at every %d projections\n\tComparisons are "
"considered stable after first %d comparisons\n",
AUTOTUNING_ALGORITHM, RECALIB_FACTOR, FIRST_STABLE);
}
else
{
Autotuning = false;
if (mpi_rank == 0)
{
printf("Autotuning of GPUWorkload disabled");
if (getenv("GPU") && atoi(getenv("GPU")))
printf(", using GPUWorkload: %d%%\n",
(getenv("GPUWORKLOAD") && (atoi(getenv("GPUWORKLOAD")) != -1)) ?
atoi(getenv("GPUWORKLOAD")) :
100);
else
printf(", please enable GPUs\n");
}
}
// ****************** Initializing pointers *********************
deviceInit();
if (DebugOutput >= 2 && mpi_rank == 0)
{
printf("Time Device Init %f\n", timer.GetCurrentElapsedTime());
timer.ResetStart();
}
if (!param.printModel)
pProb.init(RefMap.ntotRefMap, param.nTotGridAngles, *this);
if (DebugOutput >= 2 && mpi_rank == 0)
{
printf("Time Init Probabilities %f\n", timer.GetCurrentElapsedTime());
timer.ResetStart();
}
return (0);
}
void bioem::cleanup()
{
// Deleting allocated pointers
free_device_host(pProb.ptr);
RefMap.freePointers();
}
int bioem::precalculate()
{
// **************************************************************************************
// **Precalculating Routine of Orientation grids, Map crosscorrelations and
// CTF Kernels**
// **************************************************************************************
HighResTimer timer;
if (DebugOutput >= 2)
{
printf("\tTime Precalculate Grids Param: %f\n",
timer.GetCurrentElapsedTime());
timer.ResetStart();
}
// Precalculating CTF Kernels stored in class Param
param.CalculateRefCTF();
if (DebugOutput >= 2)
{
printf("\tTime Precalculate CTFs: %f\n", timer.GetCurrentElapsedTime());
timer.ResetStart();
}
// Precalculate Maps
if (!param.printModel)
RefMap.precalculate(param, *this);
if (DebugOutput >= 2)
printf("\tTime Precalculate Maps: %f\n", timer.GetCurrentElapsedTime());
return (0);
}
int bioem::printModel()
{
// **************************************************************************************
// ********** Secondary routine for printing out the only best projection
// ***************
// **************************************************************************************
cout << "\nAnalysis for printing best projection::: \n \n";
mycomplex_t *proj_mapsFFT;
myfloat_t *conv_map = NULL;
mycomplex_t *conv_mapFFT;
myfloat_t sumCONV, sumsquareCONV;
proj_mapsFFT = (mycomplex_t *) myfftw_malloc(
sizeof(mycomplex_t) * param.param_device.NumberPixels *
param.param_device.NumberFFTPixels1D);
conv_mapFFT = (mycomplex_t *) myfftw_malloc(
sizeof(mycomplex_t) * param.param_device.NumberPixels *
param.param_device.NumberFFTPixels1D);
conv_map = (myfloat_t *) myfftw_malloc(sizeof(myfloat_t) *
param.param_device.NumberPixels *
param.param_device.NumberPixels);
cout << "...... Calculating Projection .......................\n ";
createProjection(0, proj_mapsFFT);
cout << "...... Calculating Convolution .......................\n ";
createConvolutedProjectionMap_noFFT(proj_mapsFFT, conv_map, conv_mapFFT,
sumCONV, sumsquareCONV);
return (0);
}
int bioem::run()
{
// **************************************************************************************
// **** Main BioEM routine, projects, convolutes and compares with Map using
// OpenMP ****
// **************************************************************************************
// **** If we want to control the number of threads ->
// omp_set_num_threads(XX); ******
// ****************** Declarying class of Probability Pointer
// *************************
cuda_custom_timeslot("Initialization", -1, -1, COLOR_INIT);
if (mpi_rank == 0)
printf("\tInitializing Probabilities\n");
// Controls for MPI
if (mpi_size > param.nTotGridAngles)
{
myError("Wrong MPI setup: more MPI processes than orientations");
}
// Inizialzing Probabilites to zero and constant to -Infinity
for (int iRefMap = 0; iRefMap < RefMap.ntotRefMap; iRefMap++)
{
bioem_Probability_map &pProbMap = pProb.getProbMap(iRefMap);
pProbMap.Total = 0.0;
pProbMap.Constoadd = MIN_PROB;
if (param.param_device.writeAngles)
{
for (int iOrient = 0; iOrient < param.nTotGridAngles; iOrient++)
{
bioem_Probability_angle &pProbAngle =
pProb.getProbAngle(iRefMap, iOrient);
pProbAngle.forAngles = 0.0;
pProbAngle.ConstAngle = MIN_PROB;
}
}
}
// **************************************************************************************
deviceStartRun();
// ******************************** MAIN CYCLE
// ******************************************
mycomplex_t *proj_mapsFFT;
mycomplex_t *conv_mapsFFT;
myparam5_t *comp_params =
new myparam5_t[param.nTotParallelConv * PIPELINE_LVL];
int iPipeline = 0;
// allocating fftw_complex vector
const int ProjMapSize =
(param.FFTMapSize + 64) & ~63; // Make sure this is properly aligned for
// fftw..., Actually this should be ensureb by
// using FFTMapSize, but it is not due to a bug
// in CUFFT which cannot handle padding properly
//******** Allocating Vectors *************
proj_mapsFFT = (mycomplex_t *) myfftw_malloc(
sizeof(mycomplex_t) * ProjMapSize * nProjectionsAtOnce);
conv_mapsFFT =
(mycomplex_t *) myfftw_malloc(sizeof(mycomplex_t) * param.FFTMapSize *
param.nTotParallelConv * PIPELINE_LVL);
cuda_custom_timeslot_end; // Ending initialization
HighResTimer timer, timer2;
/* Autotuning */
Autotuner aut;
if (Autotuning)
{
aut.Initialize(AUTOTUNING_ALGORITHM, FIRST_STABLE);
rebalanceWrapper(aut.Workload());
}
if (DebugOutput >= 1 && mpi_rank == 0)
printf("\tMain Loop GridAngles %d, CTFs %d, RefMaps %d, Shifts (%d/%d)², "
"Pixels %d², OMP Threads %d, MPI Ranks %d\n",
param.nTotGridAngles, param.nTotCTFs, RefMap.ntotRefMap,
2 * param.param_device.maxDisplaceCenter +
param.param_device.GridSpaceCenter,
param.param_device.GridSpaceCenter, param.param_device.NumberPixels,
omp_get_max_threads(), mpi_size);
const int iOrientStart =
(int) ((long long int) mpi_rank * param.nTotGridAngles / mpi_size);
int iOrientEnd =
(int) ((long long int) (mpi_rank + 1) * param.nTotGridAngles / mpi_size);
if (iOrientEnd > param.nTotGridAngles)
iOrientEnd = param.nTotGridAngles;
/* Vectors for computing statistic on different parts of the code */
TimeStat ts((iOrientEnd - iOrientStart), param.nTotCTFs);
if (DebugOutput >= 1)
ts.InitTimeStat(4);
// **************************Loop Over
// orientations***************************************
for (int iOrientAtOnce = iOrientStart; iOrientAtOnce < iOrientEnd;
iOrientAtOnce += nProjectionsAtOnce)
{
// ***************************************************************************************
// ***** Creating Projection for given orientation and transforming to
// Fourier space *****
if (DebugOutput >= 1)
{
timer2.ResetStart();
timer.ResetStart();
}
int iOrientEndAtOnce =
std::min(iOrientEnd, iOrientAtOnce + nProjectionsAtOnce);
// **************************Parallel orientations for projections at
// once***************
#pragma omp parallel for
for (int iOrient = iOrientAtOnce; iOrient < iOrientEndAtOnce; iOrient++)
{
createProjection(iOrient,
&proj_mapsFFT[(iOrient - iOrientAtOnce) * ProjMapSize]);
}
if (DebugOutput >= 1)
{
ts.time = timer.GetCurrentElapsedTime();
ts.Add(TS_PROJECTION);
if (DebugOutput >= 2)
printf("\tTime Projection %d-%d: %f (rank %d)\n", iOrientAtOnce,
iOrientEndAtOnce - 1, ts.time, mpi_rank);
}
/* Recalibrate if needed */
if (Autotuning && ((iOrientAtOnce - iOrientStart) % RECALIB_FACTOR == 0) &&
((iOrientEnd - iOrientAtOnce) > RECALIB_FACTOR) &&
(iOrientAtOnce != iOrientStart))
{
aut.Reset();
rebalanceWrapper(aut.Workload());
}
for (int iOrient = iOrientAtOnce; iOrient < iOrientEndAtOnce; iOrient++)
{
mycomplex_t *proj_mapFFT =
&proj_mapsFFT[(iOrient - iOrientAtOnce) * ProjMapSize];
// ***************************************************************************************
// ***** **** Internal Loop over PSF/CTF convolutions **** *****
for (int iConvAtOnce = 0; iConvAtOnce < param.nTotCTFs;
iConvAtOnce += param.nTotParallelConv)
{
if (DebugOutput >= 1)
timer.ResetStart();
int iConvEndAtOnce =
std::min(param.nTotCTFs, iConvAtOnce + param.nTotParallelConv);
// Total number of convolutions that can be treated in this iteration in
// parallel
int maxParallelConv = iConvEndAtOnce - iConvAtOnce;
#pragma omp parallel for
for (int iConv = iConvAtOnce; iConv < iConvEndAtOnce; iConv++)
{
// *** Calculating convolutions of projection map and
// crosscorrelations ***
int i =
(iPipeline & 1) * param.nTotParallelConv + (iConv - iConvAtOnce);
mycomplex_t *localmultFFT = &conv_mapsFFT[i * param.FFTMapSize];
createConvolutedProjectionMap(iOrient, iConv, proj_mapFFT,
localmultFFT, comp_params[i].sumC,
comp_params[i].sumsquareC);
comp_params[i].amp = param.CtfParam[iConv].pos[0];
comp_params[i].pha = param.CtfParam[iConv].pos[1];
comp_params[i].env = param.CtfParam[iConv].pos[2];
}
if (DebugOutput >= 1)
{
ts.time = timer.GetCurrentElapsedTime();
ts.Add(TS_CONVOLUTION);
if (DebugOutput >= 2)
printf("\t\tTime Convolution %d %d-%d: %f (rank %d)\n", iOrient,
iConvAtOnce, iConvEndAtOnce - 1, ts.time, mpi_rank);
}
// ******************Internal loop over Reference images CUDA or
// OpenMP******************
// *** Comparing each calculated convoluted map with all experimental
// maps ***
ts.time = 0.;
if ((DebugOutput >= 1) || (Autotuning && aut.Needed(iConvAtOnce)))
timer.ResetStart();
compareRefMaps(iPipeline++, iOrient, iConvAtOnce, maxParallelConv,
conv_mapsFFT, comp_params);
if (DebugOutput >= 1)
{
ts.time = timer.GetCurrentElapsedTime();
ts.Add(TS_COMPARISON);
}
if (DebugOutput >= 2)
{
if (Autotuning)
printf("\t\tTime Comparison %d %d-%d: %f sec with GPU workload "
"%d%% (rank %d)\n",
iOrient, iConvAtOnce, iConvEndAtOnce - 1, ts.time,
aut.Workload(), mpi_rank);
else
printf("\t\tTime Comparison %d %d-%d: %f sec (rank %d)\n", iOrient,
iConvAtOnce, iConvEndAtOnce - 1, ts.time, mpi_rank);
}
if (Autotuning && aut.Needed(iConvAtOnce))
{
if (ts.time == 0.)
ts.time = timer.GetCurrentElapsedTime();
aut.Tune(ts.time);
if (aut.Finished() && DebugOutput >= 1)
printf("\tOptimal GPU workload %d%% (rank %d)\n", aut.Workload(),
mpi_rank);
rebalanceWrapper(aut.Workload());
}
}
if (DebugOutput >= 1)
{
ts.time = timer2.GetCurrentElapsedTime();
ts.Add(TS_TPROJECTION);
printf("\tTotal time for projection %d: %f (rank %d)\n", iOrient,
ts.time, mpi_rank);
timer2.ResetStart();
}
}
}
/* Statistical summary on different parts of the code */
if (DebugOutput >= 1)
{
ts.PrintTimeStat(mpi_rank);
ts.EmptyTimeStat();
}
// deallocating fftw_complex vector
myfftw_free(proj_mapsFFT);
myfftw_free(conv_mapsFFT);
deviceFinishRun();
// *******************************************************************************
// ************* Collecing all the probabilities from MPI replicas
// ***************
#ifdef WITH_MPI
if (mpi_size > 1)
{
if (DebugOutput >= 1 && mpi_rank == 0)
timer.ResetStart();
// Reduce Constant and summarize probabilities
{
myprob_t *tmp1 = new myprob_t[RefMap.ntotRefMap];
myprob_t *tmp2 = new myprob_t[RefMap.ntotRefMap];
myprob_t *tmp3 = new myprob_t[RefMap.ntotRefMap];
for (int i = 0; i < RefMap.ntotRefMap; i++)
{
tmp1[i] = pProb.getProbMap(i).Constoadd;
}
MPI_Allreduce(tmp1, tmp2, RefMap.ntotRefMap, MY_MPI_FLOAT, MPI_MAX,
MPI_COMM_WORLD);
for (int i = 0; i < RefMap.ntotRefMap; i++)
{
bioem_Probability_map &pProbMap = pProb.getProbMap(i);
#ifdef DEBUG
cout << "Reduction " << mpi_rank << " Map " << i << " Prob "
<< pProbMap.Total << " Const " << pProbMap.Constoadd << "\n";
#endif
tmp1[i] = pProbMap.Total * exp(pProbMap.Constoadd - tmp2[i]);
}
MPI_Reduce(tmp1, tmp3, RefMap.ntotRefMap, MY_MPI_FLOAT, MPI_SUM, 0,
MPI_COMM_WORLD);
// Find MaxProb
MPI_Status mpistatus;
{
int *tmpi1 = new int[RefMap.ntotRefMap];
int *tmpi2 = new int[RefMap.ntotRefMap];
for (int i = 0; i < RefMap.ntotRefMap; i++)
{
bioem_Probability_map &pProbMap = pProb.getProbMap(i);
tmpi1[i] = tmp2[i] <= pProbMap.Constoadd ? mpi_rank : -1;
// temporary array that has the mpirank for the highest pProb.constant
}
MPI_Allreduce(tmpi1, tmpi2, RefMap.ntotRefMap, MPI_INT, MPI_MAX,
MPI_COMM_WORLD);
for (int i = 0; i < RefMap.ntotRefMap; i++)
{
if (tmpi2[i] == -1)
{
if (mpi_rank == 0)
myWarning("Could not find highest probability");
}
else if (tmpi2[i] !=
0) // Skip if rank 0 already has highest probability
{
if (mpi_rank == 0)
{
MPI_Recv(&pProb.getProbMap(i).max,
sizeof(pProb.getProbMap(i).max), MPI_BYTE, tmpi2[i], i,
MPI_COMM_WORLD, &mpistatus);
}
else if (mpi_rank == tmpi2[i])
{
MPI_Send(&pProb.getProbMap(i).max,
sizeof(pProb.getProbMap(i).max), MPI_BYTE, 0, i,
MPI_COMM_WORLD);
}
}
}
delete[] tmpi1;
delete[] tmpi2;
}
if (mpi_rank == 0)
{
for (int i = 0; i < RefMap.ntotRefMap; i++)
{
bioem_Probability_map &pProbMap = pProb.getProbMap(i);
pProbMap.Total = tmp3[i];
pProbMap.Constoadd = tmp2[i];
}
}
delete[] tmp1;
delete[] tmp2;
delete[] tmp3;
if (DebugOutput >= 1 && mpi_rank == 0 && mpi_size > 1)
printf("Time MPI Reduction: %f\n", timer.GetCurrentElapsedTime());
}
// Angle Reduction and Probability summation for individual angles
if (param.param_device.writeAngles)
{
const int count = RefMap.ntotRefMap * param.nTotGridAngles;
myprob_t *tmp1 = new myprob_t[count];