-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathProgram.cs
2001 lines (1572 loc) · 101 KB
/
Program.cs
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Accord.Math.Optimization;
using CommandLine;
using Warp;
using Warp.Tools;
namespace Warp.Craft
{
class Program
{
static void Main(string[] args)
{
int NIterations = 40;
int NSteps = 20;
int BatchSize = 128;
int ThreadsPerGPU = 1;
int MaxGPUs = 4;
float ParticleDiameter = 350;
float PixelSize = 2.5f;
int OutputBFactor = -100;
int FilterWindowSize = 30;
float FSCThreshold = 0.7f;
int DilateMask = 2;
int BodyOverlap = 6;
string InitCoarsePath = "it000_atomscoarse.mrc";// "NMA_15k_100.mrc";
int NCoarseAtoms = 15000;
int OversampleFineAtoms = 4;
bool DoUpdateModes = false;
int NModes = 15;
int NMaxSegments = 15;
int NSegmentsOptimization = 15;
int NSegmentsReconstruction = 15;
int NSamplesMC = 1;
int NSamplesMCSignificant = 1;
float Sigma2NMA = 1f;
float Sigma2Params = 1f;
bool PrereadParticles = true;
string ProjDir = !Debugger.IsAttached ? Environment.CurrentDirectory : "";
if (ProjDir[ProjDir.Length - 1] != '\\' && ProjDir[ProjDir.Length - 1] != '/')
ProjDir = ProjDir + "\\";
string ModelStarPath = ProjDir + "";
string ForcedBodiesPath = "";
if (!Debugger.IsAttached)
{
Options Options = new Options();
if (Parser.Default.ParseArguments(args, Options))
{
ModelStarPath = ProjDir + Options.ModelStarPath;
ParticleDiameter = Options.ParticleDiameter;
PixelSize = Options.PixelSize;
NIterations = Options.NIterations;
NSteps = Options.NSteps;
BatchSize = Options.BatchSize;
ThreadsPerGPU = Options.ThreadsPerGPU;
OutputBFactor = Options.BFactor;
FilterWindowSize = Options.WindowSize;
FSCThreshold = Options.FSCThreshold;
DilateMask = Options.DilateMask;
BodyOverlap = Options.BodyOverlap;
InitCoarsePath = Options.InitCoarsePath;
NCoarseAtoms = Options.NCoarseAtoms;
OversampleFineAtoms = Options.OversampleFine;
DoUpdateModes = Options.UpdateModes;
NModes = Options.NModes;
PrereadParticles = Options.PrereadParticles;
}
else
{
return;
}
}
Console.WriteLine("Executing with the following parameters:");
Console.WriteLine($" Input model: {ModelStarPath}");
Console.WriteLine($" Particle diameter: {ParticleDiameter} A");
Console.WriteLine($" Pixel size: {PixelSize} A");
Console.WriteLine($" Iterations: {NIterations}");
Console.WriteLine($" Steps per iteration: {NSteps}");
Console.WriteLine($" Batch size: {BatchSize}");
Console.WriteLine($" Threads per GPU: {ThreadsPerGPU}\n");
Console.WriteLine($" Pre-read particles: {PrereadParticles}\n");
Console.WriteLine($" Output B-factor: {OutputBFactor} A^2");
Console.WriteLine($" Local resolution window size: {FilterWindowSize} px");
Console.WriteLine($" Local resolution FSC threshold: {FSCThreshold}\n");
Console.WriteLine($" Dilate mask for fine model: {DilateMask} px");
Console.WriteLine($" Body overlap region: {BodyOverlap} px\n");
Console.WriteLine($" Init coarse atom model with: {InitCoarsePath}");
Console.WriteLine($" Number of coarse atoms: {NCoarseAtoms}");
Console.WriteLine($" Oversample fine atoms by: {OversampleFineAtoms}x");
Console.WriteLine($" Update modes after each iteration: {DoUpdateModes}");
Console.WriteLine($" Normal modes: {NModes}\n");
if (!File.Exists(ModelStarPath))
{
Console.WriteLine("Could not find input model STAR file.");
return;
}
Star TableMap = new Star(ModelStarPath, "map");
Star TableBodies = new Star(ModelStarPath, "bodies");
Star TableAtoms = Star.ContainsTable(ModelStarPath, "atoms") ? new Star(ModelStarPath, "atoms") : null; // Atoms are not necessarily defined for first iteration
// If bodies are specified as a wildcard, find them
{
if (TableBodies.RowCount == 1 && TableBodies.GetRowValue(0, "wrpBodyMaskHard").Contains("*"))
{
string Wildcard = TableBodies.GetRowValue(0, "wrpBodyMaskHard");
TableBodies = new Star(new [] {"wrpBodyMaskHard", "wrpBodyResolution"});
string WildcardFolder = Wildcard.Contains("/") ? Wildcard.Substring(0, Wildcard.LastIndexOf("/")) : "";
Wildcard = Wildcard.Substring(Wildcard.LastIndexOf("/") + 1);
foreach (var file in Directory.EnumerateFiles(ProjDir + WildcardFolder, Wildcard))
{
string MaskPath = file.Substring(ProjDir.Length).Replace("\\", "/");
TableBodies.AddRow(new List<string> { MaskPath, "100" });
}
}
}
int NBodies = TableBodies.RowCount;
int Size; // Get box size from one of the reference maps
{
string MapPath = TableMap.GetRowValue(0, "wrpMapHalf1");
Image Map = Image.FromFile(ProjDir + MapPath, new int2(1, 1), 0, typeof(float));
Size = Map.Dims.X;
Map.Dispose();
}
Console.WriteLine("Calculating masks.\n");
#region Create global mask from the sum of all wide local masks
Image MaskGlobal, MaskGlobalDilated;
int MaskGlobalVoxels, MaskGlobalDilatedVoxels;
//Projector ProjectorMask;
{
MaskGlobal = new Image(new int3(Size, Size, Size));
Parallel.For(0, NBodies, new ParallelOptions { MaxDegreeOfParallelism = 2 }, r =>
{
Image MaskLocal = Image.FromFile(ProjDir + TableBodies.GetRowValue(r, "wrpBodyMaskHard"), new int2(1, 1), 0, typeof (float));
lock (MaskGlobal)
MaskGlobal.Add(MaskLocal);
MaskLocal.Dispose();
});
MaskGlobal.Binarize(1e-5f);
MaskGlobalDilated = MaskGlobal.AsDilatedMask(DilateMask);
MaskGlobalVoxels = (int)(MaskGlobal.GetHostContinuousCopy().Sum() + 0.5f);
MaskGlobalDilatedVoxels = (int)(MaskGlobalDilated.GetHostContinuousCopy().Sum() + 0.5f);
MaskGlobal.FreeDevice();
MaskGlobalDilated.FreeDevice();
MaskGlobal.WriteMRC("d_maskglobal.mrc");
MaskGlobalDilated.WriteMRC("d_maskglobaldilated.mrc");
//Image MaskForParticles = MaskGlobal.AsDilatedMask(10);
//ProjectorMask = new Projector(MaskForParticles, 2);
//MaskForParticles.Dispose();
}
#endregion
#region Calculate masks to insert each body into the frankenmap
float[] BodySegmentation = new float[Size * Size * Size];
{
for (int i = 0; i < BodySegmentation.Length; i++)
BodySegmentation[i] = -1f;
Parallel.For(0, NBodies, new ParallelOptions { MaxDegreeOfParallelism = 2 }, b =>
{
Image HardMask = Image.FromFile(ProjDir + TableBodies.GetRowValue(b, "wrpBodyMaskHard"));
HardMask.Binarize(1e-6f);
float[] HardMaskData = HardMask.GetHostContinuousCopy();
lock (BodySegmentation)
{
Parallel.For(0, HardMaskData.Length, i =>
{
if (HardMaskData[i] > 0)
BodySegmentation[i] = b;
});
}
HardMask.Dispose();
});
}
// If forced body masks are provided:
float[] ForcedSegmentation = null;
if (ForcedBodiesPath != "")
{
ForcedSegmentation = new float[Size * Size * Size];
string Wildcard = ForcedBodiesPath;
string WildcardFolder = Wildcard.Contains("/") ? Wildcard.Substring(0, Wildcard.LastIndexOf("/")) : "";
Wildcard = Wildcard.Substring(Wildcard.LastIndexOf("/") + 1);
int b = 0;
foreach (var file in Directory.EnumerateFiles(ProjDir + WildcardFolder, Wildcard))
{
Image HardMask = Image.FromFile(file);
HardMask.Binarize(1e-6f);
float[] HardMaskData = HardMask.GetHostContinuousCopy();
Parallel.For(0, HardMaskData.Length, i =>
{
if (HardMaskData[i] > 0)
ForcedSegmentation[i] = b;
});
HardMask.Dispose();
b++;
}
NSegmentsOptimization = b;
NSegmentsReconstruction = b;
NMaxSegments = b;
}
#endregion
NMAMap AtomsCoarse;
NMAMap[][] AtomsFineHalves = new NMAMap[GPU.GetDeviceCount()][];
for (int i = 0; i < AtomsFineHalves.Length; i++)
AtomsFineHalves[i] = new NMAMap[2];
#region Pre-read particles into memory if needed
Dictionary<string, float[]> ParticleStorage = new Dictionary<string, float[]>();
if (PrereadParticles)
{
Console.WriteLine("Pre-reading particles:");
#region Load particle parameters
Star TableData = new Star(ProjDir + TableMap.GetRowValue(0, "wrpParticles"));
List<int>[] SubsetRows = { new List<int>(), new List<int>() };
for (int r = 0; r < TableData.RowCount; r++)
SubsetRows[(int)float.Parse(TableData.GetRowValue(r, "rlnRandomSubset")) - 1].Add(r);
#endregion
for (int h = 0, completed = 0; h < 2; h++)
{
Parallel.For(0, SubsetRows[h].Count, r =>
{
int R = SubsetRows[h][r];
string ImageName = TableData.GetRowValue(R, "rlnImageName");
string[] AddressParts = ImageName.Split(new[] { "@" }, StringSplitOptions.RemoveEmptyEntries);
int Layer = int.Parse(AddressParts[0]) - 1;
string FileName = ProjDir + AddressParts[1];
// Get particle
Image Particle = Image.FromFile(FileName, new int2(Size, Size), 0, typeof (float), Layer);
lock (TableMap)
{
ParticleStorage.Add(ImageName, Particle.GetHostContinuousCopy());
completed++;
if (completed % 100 == 0 || completed == SubsetRows.Select(v => v.Count).Sum())
{
ClearCurrentConsoleLine();
Console.Write($" {completed}/{SubsetRows.Select(v => v.Count).Sum()}");
}
}
});
}
Console.Write("\n\n");
}
#endregion
for (int iter = 0; iter < NIterations; iter++)
{
Console.WriteLine($"Started iteration {iter + 1}:\n");
if (iter > 0) // In first iteration, tables are already loaded and possibly modified
{
TableMap = new Star(ModelStarPath, "map");
TableBodies = new Star(ModelStarPath, "bodies");
TableAtoms = Star.ContainsTable(ModelStarPath, "atoms") ? new Star(ModelStarPath, "atoms") : null; // Atoms are not necessarily defined for first iteration
}
#region Load or make atom model
{
if (InitCoarsePath == "" && (iter == 0 || DoUpdateModes)) // Initialize from scratch in first iteration, or update every iteration
{
Console.WriteLine(" Calculating normal modes – this can take a while.");
Image Frankenmap = Image.FromFile(ProjDir + TableMap.GetRowValue(0, "wrpFrankenmap"));
AtomsCoarse = NMAMap.FromScratch(Frankenmap, MaskGlobal, NCoarseAtoms, 100, 2.5f);
Frankenmap.Dispose();
AtomsCoarse.WriteToMRC(ProjDir + $"it000_atomscoarse.mrc");
if (NModes < AtomsCoarse.NModes)
AtomsCoarse.LimitModesTo(NModes);
AtomsCoarse.SmoothModes(128);
}
else if (InitCoarsePath != "" && iter == 0) // Initialize with precalculated model
{
Console.WriteLine($" Initializing normal modes with {InitCoarsePath}.");
AtomsCoarse = new NMAMap(ProjDir + InitCoarsePath);
if (NModes < AtomsCoarse.NModes)
AtomsCoarse.LimitModesTo(NModes);
NModes = AtomsCoarse.NModes;
NCoarseAtoms = AtomsCoarse.NAtoms;
AtomsCoarse.SmoothModes(128);
}
else if (TableAtoms != null) // Take model from previous iteration
{
Console.WriteLine(" Using normal modes from previous iteration.");
AtomsCoarse = new NMAMap(ProjDir + TableAtoms.GetRowValue(0, "wrpAtomsCoarse"));
}
else
{
Console.WriteLine(" Atom model initialization went wrong: after first iteration, model.star should contain a path to the coarse model.");
return;
}
AtomsCoarse.AddSegmentation(new Image(BodySegmentation, new int3(Size, Size, Size)));
// Store coarse atoms for this iteration in a new file, regardless of whether the model is new or old
AtomsCoarse.WriteToMRC(ProjDir + $"it{iter + 1:D3}_atomscoarse.mrc");
if (TableAtoms == null)
{
TableAtoms = new Star(new[] { "wrpAtomsCoarse" });
TableAtoms.AddRow(new List<string> { $"it{(iter + 1):D3}_atomscoarse.mrc" });
}
else
{
if (!TableAtoms.HasColumn("wrpAtomsCoarse"))
TableAtoms.AddColumn("wrpAtomsCoarse");
TableAtoms.SetRowValue(0, "wrpAtomsCoarse", $"it{(iter + 1):D3}_atomscoarse.mrc");
}
AtomsCoarse.RasterizeInVolume(new int3(Size, Size, Size)).WriteMRC("d_atomscoarse_groundmode.mrc");
for (int m = 0; m < AtomsCoarse.NModes; m++)
{
float[] Weights = new float[AtomsCoarse.NModes];
Weights[m] = 2;
AtomsCoarse.RasterizeDeformedInVolume(new int3(Size, Size, Size), Weights).WriteMRC($"d_atomscoarse_mode{m:D2}.mrc");
}
AtomsCoarse.AddSegmentation(new Image(BodySegmentation, new int3(Size, Size, Size)));
Console.WriteLine("");
}
#endregion
//AtomsCoarse.ReduceToNSegments(20);
//Image[] TestMasks = AtomsCoarse.GetSoftSegmentMasks(BodyOverlap, BodyOverlap * 1.5f);
//for (int i = 0; i < TestMasks.Length; i++)
//{
// TestMasks[i].WriteMRC($"d_testmask{i:D2}.mrc");
//}
//float[][] TestMasksData = TestMasks.Select(v => v.GetHostContinuousCopy()).ToArray();
//float[] TestMaskSum = new float[TestMasksData[0].Length];
//for (int i = 0; i < TestMaskSum.Length; i++)
// for (int j = 0; j < AtomsCoarse.NSegments; j++)
// TestMaskSum[i] += TestMasksData[j][i];
//new Image(TestMaskSum, AtomsCoarse.DimsVolume).WriteMRC("d_testmasksum.mrc");
int SizeCoarse;
float ScaleFactor;
#region Estimate current per-body resolution, construct fine atom models from locally filtered maps
int BestResolutionShell = 0;
float[] InitialResolution = new float[NBodies];
int[] BodyMaxShell = new int[NBodies];
float3[] BodyCenter = new float3[NBodies];
Projector[] DebugProjectors = new Projector[2];
{
Console.WriteLine(" Estimating per-body resolution:");
Image Map1 = Image.FromFile(ProjDir + TableMap.GetRowValue(0, "wrpMapHalf1"), new int2(1, 1), 0, typeof (float));
Image Map2 = Image.FromFile(ProjDir + TableMap.GetRowValue(0, "wrpMapHalf2"), new int2(1, 1), 0, typeof (float));
#region Estimate local resolution
{
Image LocalRes = new Image(IntPtr.Zero, new int3(Size, Size, Size));
Image Map1Pristine = Map1;
Image Map2Pristine = Map2;
if (iter > 0)
{
Map1Pristine = Image.FromFile(ProjDir + TableMap.GetRowValue(0, "wrpMapHalfPristine1"), new int2(1, 1), 0, typeof(float));
Map2Pristine = Image.FromFile(ProjDir + TableMap.GetRowValue(0, "wrpMapHalfPristine2"), new int2(1, 1), 0, typeof(float));
}
GPU.LocalRes(Map1Pristine.GetDevice(Intent.Read),
Map2Pristine.GetDevice(Intent.Read),
new int3(Size, Size, Size),
PixelSize,
IntPtr.Zero,
IntPtr.Zero,
LocalRes.GetDevice(Intent.Write),
IntPtr.Zero,
FilterWindowSize,
FSCThreshold,
false,
10,
0,
0,
false,
false);
if (iter > 0)
{
Map1Pristine.Dispose();
Map2Pristine.Dispose();
}
float[] LocalResData = LocalRes.GetHostContinuousCopy().Select(v => Size * PixelSize / Math.Max(1, v)).ToArray(); // LocalResData now as frequencies
float GlobalAverageShell = MathHelper.MeanWeighted(LocalResData, MaskGlobal.GetHostContinuousCopy());
BestResolutionShell = (int)GlobalAverageShell;
LocalRes.WriteMRC("d_localres.mrc");
//Image LocalRes = Image.FromFile("d_localres.mrc");
Image[] MasksHard = AtomsCoarse.GetSegmentMasks();
int Done = 0;
Parallel.For(0, NBodies, b =>
{
Image MaskHard = MasksHard[b];
BodyCenter[b] = MaskHard.AsCenterOfMass();
float[] MaskHardData = MaskHard.GetHostContinuousCopy();
float AverageShell = MathHelper.MeanWeighted(LocalResData, MaskHardData);
BodyMaxShell[b] = (int)AverageShell;
InitialResolution[b] = AverageShell; // Frequency in global volume frame
MaskHard.Dispose();
lock (TableAtoms)
{
//BestResolutionShell = Math.Max((int)AverageShell, BestResolutionShell);
ClearCurrentConsoleLine();
Console.Write($" {++Done}/{NBodies}");
}
});
LocalRes.Dispose();
}
#endregion
Console.Write("\n");
#region Use the Frankenmaps to calculate per-voxel resolution based on the estimated per-body resolutions
Image[] MasksSmooth = AtomsCoarse.GetSoftSegmentMasks(BodyOverlap, BodyOverlap * 1.5f);
Image BodyResolution, BodyBFactor;
{
float[] BodyResolutionData = new float[Size * Size * Size];
for (int b = 0; b < MasksSmooth.Length; b++)
{
float ResVal = InitialResolution[b];
float[] FrankenMaskData = MasksSmooth[b].GetHostContinuousCopy();
for (int i = 0; i < BodyResolutionData.Length; i++)
BodyResolutionData[i] += ResVal * FrankenMaskData[i];
}
for (int i = 0; i < BodyResolutionData.Length; i++)
BodyResolutionData[i] = Math.Min(Size * PixelSize / Math.Max(Math.Min(BestResolutionShell, BodyResolutionData[i]), 1f), FilterWindowSize / 2 * PixelSize);
BodyResolution = new Image(BodyResolutionData, new int3(Size, Size, Size));
BodyBFactor = new Image(new int3(Size, Size, Size));
BodyResolution.WriteMRC("d_bodyresolution.mrc");
}
foreach (var mask in MasksSmooth)
mask.Dispose();
#endregion
#region Filter both half-maps to per-voxel resolution derived from bodies
GPU.LocalFilter(Map1.GetDevice(Intent.Read),
Map1.GetDevice(Intent.Write),
new int3(Size, Size, Size),
PixelSize,
BodyResolution.GetDevice(Intent.Read),
BodyBFactor.GetDevice(Intent.Read),
FilterWindowSize,
0f);
GPU.LocalFilter(Map2.GetDevice(Intent.Read),
Map2.GetDevice(Intent.Write),
new int3(Size, Size, Size),
PixelSize,
BodyResolution.GetDevice(Intent.Read),
BodyBFactor.GetDevice(Intent.Read),
FilterWindowSize,
0f);
//Map1 = Image.FromFile("d_map1.mrc");
//Map2 = Image.FromFile("d_map2.mrc");
Map1.WriteMRC("d_map1.mrc");
Map2.WriteMRC("d_map2.mrc");
BodyResolution.Dispose();
BodyBFactor.Dispose();
#endregion
//Image SoftMask = Image.FromFile(ProjDir + TableMap.GetRowValue(0, "wrpSoftMask"));
//Map1.Multiply(SoftMask);
//Map2.Multiply(SoftMask);
//SoftMask.Dispose();
Map1.FreeDevice();
Map2.FreeDevice();
//DebugProjectors[0] = new Projector(Map1, 2);
//DebugProjectors[1] = new Projector(Map2, 2);
// Set maximum image size and scale factor to match current average resolution
SizeCoarse = BestResolutionShell * 2;
ScaleFactor = (float)SizeCoarse / Size;
Console.WriteLine($" Considering data until {Size * PixelSize / BestResolutionShell:F2} A.");
if (BestResolutionShell < 3)
{
Console.WriteLine(" ERROR: At least one of the bodies cannot be resolved at all. Aborting.");
return;
}
if (iter == 0)
{
Console.WriteLine($" Initial resolution for individual bodies at {FSCThreshold:F3} cutoff is:");
for (int b = 0; b < NBodies; b++)
Console.WriteLine($" {b + 1}: {Size * PixelSize / InitialResolution[b]:F2} A");
Console.Write("\n");
}
#region Construct fine atom models
Console.WriteLine(" Calculating fine NMA models.");
NMAMap AtomsForFine = AtomsCoarse.GetCopy();
if (ForcedSegmentation == null)
AtomsForFine.ReduceToNSegments(NSegmentsOptimization);
else
AtomsForFine.AddSegmentation(new Image(ForcedSegmentation, new int3(Size, Size, Size)));
//int gpuID = 0;
Helper.ForEachGPUOnce(gpuID =>
{
float SigmaFine, CorrFine;
Image Map1Copy = new Image(Map1.GetHost(Intent.Read), Map1.Dims);
Image Map2Copy = new Image(Map2.GetHost(Intent.Read), Map2.Dims);
AtomsFineHalves[gpuID][0] = AtomsForFine.GetCopy();
AtomsFineHalves[gpuID][0].InitializeBodyProjectors(BodyOverlap, BodyOverlap * 1.5f, Map1Copy, SizeCoarse, 2);
AtomsFineHalves[gpuID][0].FreeOnDevice();
AtomsFineHalves[gpuID][1] = AtomsForFine.GetCopy();
AtomsFineHalves[gpuID][1].InitializeBodyProjectors(BodyOverlap, BodyOverlap * 1.5f, Map2Copy, SizeCoarse, 2);
AtomsFineHalves[gpuID][1].FreeOnDevice();
if (gpuID == 0)
{
AtomsFineHalves[0][0].WriteToMRC("d_atomsfine1.mrc");
AtomsFineHalves[0][1].WriteToMRC("d_atomsfine2.mrc");
AtomsFineHalves[0][0].RasterizeInVolume(new int3(Size, Size, Size)).WriteMRC("d_atomsfine.mrc");
for (int m = 0; m < AtomsFineHalves[0][0].NModes; m++)
{
float[] Weights = new float[AtomsFineHalves[0][0].NModes];
Weights[m] = 2;
AtomsFineHalves[0][0].RasterizeDeformedInVolume(new int3(Size, Size, Size), Weights).WriteMRC($"d_atomsfine_mode{m:D2}.mrc");
}
}
}, MaxGPUs);
Map1.Dispose();
Map2.Dispose();
#endregion
}
#endregion
#region Load particle parameters
Star TableData = new Star(ProjDir + TableMap.GetRowValue(0, "wrpParticles"));
int NParticles = TableData.RowCount;
List<int>[] SubsetRows = { new List<int>(), new List<int>() };
for (int r = 0; r < TableData.RowCount; r++)
SubsetRows[(int)float.Parse(TableData.GetRowValue(r, "rlnRandomSubset")) - 1].Add(r);
Dictionary<string, int> GroupMapping = new Dictionary<string, int>();
float3[][] ParticleAngles = { new float3[SubsetRows[0].Count], new float3[SubsetRows[1].Count] };
float2[][] ParticleShifts = { new float2[SubsetRows[0].Count], new float2[SubsetRows[1].Count] };
float[][] ParticleNMAWeights = { new float[SubsetRows[0].Count * NModes], new float[SubsetRows[1].Count * NModes] };
CTFStruct[][] ParticleCTFParams = { new CTFStruct[SubsetRows[0].Count], new CTFStruct[SubsetRows[1].Count] };
int[][] ParticleGroups = { new int[SubsetRows[0].Count], new int[SubsetRows[1].Count] };
float3[][][] MCAngles = { new float3[SubsetRows[0].Count][], new float3[SubsetRows[1].Count][] };
float2[][][] MCShifts = { new float2[SubsetRows[0].Count][], new float2[SubsetRows[1].Count][] };
float[][][] MCNMAWeights = { new float[SubsetRows[0].Count][], new float[SubsetRows[1].Count][] };
float[][][] MCScores = { new float[SubsetRows[0].Count][], new float[SubsetRows[1].Count][] };
for (int h = 0; h < 2; h++)
{
// Get CTF parameters
for (int r = 0; r < SubsetRows[h].Count; r++)
{
int R = SubsetRows[h][r];
float Voltage = TableData.GetRowValueFloat(R, "rlnVoltage");
float DefocusU = TableData.GetRowValueFloat(R, "rlnDefocusU") / 1e4f;
float DefocusV = TableData.GetRowValueFloat(R, "rlnDefocusV") / 1e4f;
float DefocusAngle = TableData.GetRowValueFloat(R, "rlnDefocusAngle");
float Cs = TableData.GetRowValueFloat(R, "rlnSphericalAberration");
//float Phase = TableData[0].GetRowValueFloat(R, "rlnPhaseShift");
float Contrast = TableData.GetRowValueFloat(R, "rlnAmplitudeContrast");
CTF ParticleCTF = new CTF
{
PixelSize = (decimal)PixelSize,
Voltage = (decimal)Voltage,
Defocus = (decimal)(DefocusU + DefocusV) * 0.5M,
DefocusDelta = (decimal)(DefocusU - DefocusV),
DefocusAngle = (decimal)DefocusAngle,
Cs = (decimal)Cs,
//PhaseShift = (decimal)Phase / 180M,
Amplitude = (decimal)Contrast
};
ParticleCTFParams[h][r] = ParticleCTF.ToStruct();
}
// Get rotations and shifts
for (int r = 0; r < SubsetRows[h].Count; r++)
{
int R = SubsetRows[h][r];
ParticleAngles[h][r] = new float3(TableData.GetRowValueFloat(R, "rlnAngleRot"),
TableData.GetRowValueFloat(R, "rlnAngleTilt"),
TableData.GetRowValueFloat(R, "rlnAnglePsi"));
ParticleShifts[h][r] = new float2(TableData.GetRowValueFloat(R, "rlnOriginX"),
TableData.GetRowValueFloat(R, "rlnOriginY"));
}
// Get NMA weights if there are any
{
string[] NMAColumns = TableData.GetColumnNames().Where(v => v.Contains("wrpNMAWeight")).ToArray();
bool AllColumnsPresent = true;
for (int i = 1; i <= NModes; i++)
if (!NMAColumns.Contains($"wrpNMAWeight{i}"))
AllColumnsPresent = false;
if (AllColumnsPresent)
{
for (int m = 0; m < NModes; m++)
for (int r = 0; r < SubsetRows[h].Count; r++)
{
int R = SubsetRows[h][r];
ParticleNMAWeights[h][r * NModes + m] = TableData.GetRowValueFloat(SubsetRows[h][r], $"wrpNMAWeight{m + 1}");
}
}
}
// Figure out groups
for (int r = 0; r < SubsetRows[h].Count; r++)
{
int R = SubsetRows[h][r];
string MicName = TableData.HasColumn("rlnGroupName") ? TableData.GetRowValue(R, "rlnGroupName") :
TableData.GetRowValue(R, "rlnMicrographName");
MicName = MicName.Substring(MicName.LastIndexOf("/") + 1);
if (!GroupMapping.ContainsKey(MicName))
GroupMapping.Add(MicName, GroupMapping.Count);
ParticleGroups[h][r] = GroupMapping[MicName];
}
}
// Map particles to groups
int NGroups = GroupMapping.Count;
List<int>[][] GroupParticles = { new List<int>[NGroups], new List<int>[NGroups] };
for (int h = 0; h < 2; h++)
for (int g = 0; g < NGroups; g++)
GroupParticles[h][g] = new List<int>();
for (int h = 0; h < 2; h++)
for (int p = 0; p < SubsetRows[h].Count; p++)
GroupParticles[h][ParticleGroups[h][p]].Add(p);
#endregion
#region Noise and scale estimation
Console.WriteLine(" Estimating noise spectra for each micrograph:");
//Image Dummy = Image.FromFile("E:\\multibody2\\tf2h\\it040_frankenmap_half1.mrc");
//Projector DummyProj = new Projector(Dummy, 2);
float[][] GroupInvNoise = new float[NGroups][];
float[] GroupScale = new float[NGroups].Select(v => 1f).ToArray();
float[] ParticleNormalization = new float[NParticles].Select(v => 1f).ToArray();
{
int[] PixelShell = new int[(SizeCoarse / 2 + 1) * SizeCoarse];
for (int y = 0; y < SizeCoarse; y++)
for (int x = 0; x < SizeCoarse / 2 + 1; x++)
{
int xx = x;
int yy = y < SizeCoarse / 2 + 1 ? y : y - SizeCoarse;
int R = (int)Math.Round(Math.Sqrt(xx * xx + yy * yy));
PixelShell[y * (SizeCoarse / 2 + 1) + x] = R < SizeCoarse / 2 ? R : -1;
}
#region Iterate over groups
if (true)
{
int GroupsDone = 0;
Helper.ForGPU(0, NGroups, (g, gpuID) =>
{
float[] Noise1D = new float[SizeCoarse / 2];
int[] Samples1D = new int[SizeCoarse / 2];
float SumPart = 0, SumProj = 0;
Image CTFCoordsCoarse = CTF.GetCTFCoords(SizeCoarse, Size);
#region Create mask
Image ParticleMask = new Image(new int3(SizeCoarse, SizeCoarse, 1));
{
float[] ParticleMaskData = ParticleMask.GetHost(Intent.Write)[0];
float Radius2 = ParticleDiameter / 2 / PixelSize * ScaleFactor;
for (int y = 0; y < SizeCoarse; y++)
{
int yy = y - SizeCoarse / 2;
yy *= yy;
for (int x = 0; x < SizeCoarse; x++)
{
int xx = x - SizeCoarse / 2;
xx *= xx;
float R = (float)Math.Sqrt(xx + yy);
float V = R <= Radius2 ? 1f : (float)(Math.Cos(Math.Min(1, (R - Radius2) / 10) * Math.PI) * 0.5 + 0.5);
ParticleMaskData[y * SizeCoarse + x] = V;
}
}
}
#endregion
float2[][][] ParticleData = new float2[2][][];
float2[][][] ProjData = new float2[2][][];
for (int h = 0; h < 2; h++)
{
int NParts = GroupParticles[h][g].Count;
if (NParts == 0)
continue;
#region Get particle parameters
float3[] GroupAngles = new float3[NParts];
float2[] GroupShifts = new float2[NParts];
CTFStruct[] GroupCTFParams = new CTFStruct[NParts];
float[][] GroupNMAWeights = Helper.ArrayOfFunction(() => new float[NModes], NParts);
for (int p = 0; p < NParts; p++)
{
int pi = GroupParticles[h][g][p];
GroupAngles[p] = ParticleAngles[h][pi];
GroupShifts[p] = ParticleShifts[h][pi];
GroupCTFParams[p] = ParticleCTFParams[h][pi];
for (int m = 0; m < NModes; m++)
GroupNMAWeights[p][m] = ParticleNMAWeights[h][pi * NModes + m];
}
#endregion
#region Create CTF
Image GroupCTF;
{
GroupCTF = new Image(new int3(SizeCoarse, SizeCoarse, NParts), true);
GPU.CreateCTF(GroupCTF.GetDevice(Intent.Write),
CTFCoordsCoarse.GetDevice(Intent.Read),
(uint)CTFCoordsCoarse.ElementsComplex,
GroupCTFParams,
false,
(uint)NParts);
//GroupCTF.WriteMRC("d_groupctf.mrc");
}
#endregion
#region Project reference
Image ProjectionsFT = AtomsFineHalves[gpuID][h].ProjectBodies(new int2(SizeCoarse, SizeCoarse),
GroupNMAWeights,
GroupAngles.Select(a => a * Helper.ToRad).ToArray(),
new float2[NParts],
Helper.ArrayOfFunction(() => Helper.ArrayOfConstant(1f, AtomsFineHalves[gpuID][h].NSegments), NParts),
NParts);
//Image ProjectionsFT = DebugProjectors[h].Project(new int2(SizeCoarse, SizeCoarse), GroupAngles.Select(a => a * Helper.ToRad).ToArray(), (int)(192 * 2.74f / 15f));
//Image ProjectionsFT = new Image(new int3(SizeCoarse, SizeCoarse, NParts), true, true);
AtomsFineHalves[gpuID][h].FreeOnDevice();
#endregion
ProjectionsFT.Multiply(GroupCTF);
//ProjectionsFT.Multiply(1f / Size);
#region Load particles
Image ParticlesCoarseFT;
{
Image ParticlesRaw = new Image(new int3(Size, Size, NParts));
float[][] ParticlesRawData = ParticlesRaw.GetHost(Intent.Write);
for (int p = 0; p < NParts; p++)
{
int pi = GroupParticles[h][g][p];
string ImageName = TableData.GetRowValue(SubsetRows[h][pi], "rlnImageName");
if (!PrereadParticles)
{
string[] AddressParts = ImageName.Split(new[] { "@" }, StringSplitOptions.RemoveEmptyEntries);
int Layer = int.Parse(AddressParts[0]) - 1;
string FileName = ProjDir + AddressParts[1];
Image Particle = Image.FromFile(FileName, new int2(Size, Size), 0, typeof (float), Layer);
ParticlesRawData[p] = Particle.GetHostContinuousCopy();
Particle.Dispose();
}
else
{
ParticlesRawData[p] = ParticleStorage[ImageName].ToArray();
}
}
ParticlesRaw.ShiftSlices(GroupShifts.Select(v => new float3(v.X, v.Y, 0)).ToArray());
Image ParticlesCoarse = ParticlesRaw.AsScaled(new int2(SizeCoarse, SizeCoarse));
ParticlesCoarse.Multiply(1f / (SizeCoarse * SizeCoarse));
ParticlesRaw.Dispose();
//ParticlesCoarse.WriteMRC("d_particlescoarse.mrc");
ParticlesCoarse.MultiplySlices(ParticleMask);
ParticlesCoarse.RemapToFT();
ParticlesCoarseFT = ParticlesCoarse.AsFFT();
ParticlesCoarse.Dispose();
}
#endregion
//ParticlesCoarseFT.Subtract(ProjectionsFT);
#region Calculate squared differences for variance estimation
ParticleData[h] = ParticlesCoarseFT.GetHostComplexCopy();
ProjData[h] = ProjectionsFT.GetHostComplexCopy();
for (int p = 0; p < NParts; p++)
{
float2[] PartSlice = ParticleData[h][p];
float2[] ProjSlice = ProjData[h][p];
for (int i = 0; i < PixelShell.Length; i++)
if (PixelShell[i] >= 0)
{
SumPart += PartSlice[i].X * ProjSlice[i].X + PartSlice[i].Y * ProjSlice[i].Y;
SumProj += ProjSlice[i].X * ProjSlice[i].X + ProjSlice[i].Y * ProjSlice[i].Y;
}
}
#endregion
ParticlesCoarseFT.Dispose();
ProjectionsFT.Dispose();
GroupCTF.Dispose();
}
ParticleMask.Dispose();
CTFCoordsCoarse.Dispose();
GroupScale[g] = SumPart / Math.Max(1e-20f, SumProj);
for (int h = 0; h < 2; h++)
{
int NParts = GroupParticles[h][g].Count;
if (NParts == 0)
continue;
for (int p = 0; p < NParts; p++)
{
int pi = SubsetRows[h][GroupParticles[h][g][p]];
float2[] PartSlice = ParticleData[h][p];
float2[] ProjSlice = ProjData[h][p];
for (int i = 0; i < PixelShell.Length; i++)
if (PixelShell[i] >= 0)
{
float2 Diff = PartSlice[i] - ProjSlice[i] * GroupScale[g];
Noise1D[PixelShell[i]] += Diff.X * Diff.X + Diff.Y * Diff.Y;
Samples1D[PixelShell[i]]++;
ParticleNormalization[pi] += Diff.X * Diff.X + Diff.Y * Diff.Y;
}
ParticleNormalization[pi] = (float)Math.Sqrt(ParticleNormalization[pi] * 2);
}
}
for (int r = 0; r < SizeCoarse / 2; r++)
Noise1D[r] /= Samples1D[r] * 2;
float[] InvNoise = new float[PixelShell.Length];
for (int i = 0; i < InvNoise.Length; i++)
if (PixelShell[i] >= 0)
InvNoise[i] = 1f / Noise1D[PixelShell[i]];
GroupInvNoise[g] = InvNoise;
lock (TableData)
{
ClearCurrentConsoleLine();
Console.Write($" {++GroupsDone}/{NGroups}");
}
}, 1, MaxGPUs);
}
#endregion
Console.Write("\n");
}
// Normalize particle norm factors to average to 1.0
{
float AverageNorm = MathHelper.Mean(ParticleNormalization);
ParticleNormalization = ParticleNormalization.Select(v => v / AverageNorm).ToArray();
}
// Normalize group scales to have average of 1.0
{
float AverageScale = MathHelper.Mean(GroupScale);
GroupScale = GroupScale.Select(v => v / AverageScale).ToArray();
}
new Image(GroupInvNoise, new int3(SizeCoarse, SizeCoarse, NGroups), true).WriteMRC("d_invsigma2.mrc");
//GroupInvNoise = Image.FromFile("d_invsigma2.mrc").GetHost(Intent.Read);