process_hkl.c 14.8 KB
Newer Older
1
2
3
4
5
/*
 * process_hkl.c
 *
 * Assemble and process FEL Bragg intensities
 *
6
 * (c) 2006-2011 Thomas White <taw@physics.org>
7
 * (c) 2011      Andrew Martin <andrew.martin@desy.de>
Thomas White's avatar
Thomas White committed
8
 * (c) 2011      Lorenzo Galli <lorenzo.galli@desy.de>
9
 *
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 * Part of CrystFEL - crystallography with a FEL
 *
 */


#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>

#include "utils.h"
#include "statistics.h"
28
#include "reflist-utils.h"
29
#include "symmetry.h"
30
#include "stream.h"
31
#include "beam-parameters.h"
32
33
#include "reflist.h"
#include "image.h"
34
35
36
37
38


static void show_help(const char *s)
{
	printf("Syntax: %s [options]\n\n", s);
Thomas White's avatar
Thomas White committed
39
40
41
	printf(
"Assemble and process FEL Bragg intensities.\n"
"\n"
42
43
44
"  -h, --help                Display this help message.\n"
"  -i, --input=<filename>    Specify input filename (\"-\" for stdin).\n"
"  -o, --output=<filename>   Specify output filename for merged intensities\n"
45
"                             Default: processed.hkl).\n"
46
"  -p, --pdb=<filename>      PDB file to use (default: molecule.pdb).\n"
47
"  -b, --beam=<file>         Get beam parameters from file (used for sigmas).\n"
Thomas White's avatar
Thomas White committed
48
"\n"
49
50
51
52
53
54
55
56
"      --max-only            Take the integrated intensity to be equal to the\n"
"                             maximum intensity measured for that reflection.\n"
"                             The default is to use the mean value from all\n"
"                             measurements.\n"
"      --sum                 Sum (rather than average) the intensities for the\n"
"                             final output list.  This is useful for comparing\n"
"                             results to radially summed powder patterns, but\n"
"                             will break R-factor analysis.\n"
57
"      --start-after=<n>     Skip n patterns at the start of the stream.\n"
58
59
60
"      --stop-after=<n>      Stop after processing n patterns.  Zero means\n"
"                             keep going until the end of the input, and is\n"
"                             the default.\n"
61
62
"  -g, --histogram=<h,k,l>   Calculate the histogram of measurements for this\n"
"                             reflection.\n"
63
"  -z, --hist-parameters     Set the range for the histogram and the number of\n"
Thomas White's avatar
Thomas White committed
64
"          =<min,max,nbins>   bins. \n"
65
"\n"
66
67
"      --scale               Scale each pattern for best fit with the current\n"
"                             model.\n"
Thomas White's avatar
Thomas White committed
68
"  -y, --symmetry=<sym>      Merge according to point group <sym>.\n"
69
70
"      --reference=<file>    Compare against intensities from <file> when\n"
"                             scaling or resolving ambiguities.\n"
71
72
"                             The symmetry of the reference list must be the\n"
"                             same as that given with '-y'.\n"
73
);
74
75
76
}


77
static void plot_histogram(double *vals, int n, float hist_min, float hist_max, int nbins)
78
79
80
81
82
{
	int i;
	double max = -INFINITY;
	double min = +INFINITY;
	double step;
83
	int histo[nbins];
84
85
86
87
88
89
90
91
	FILE *fh;

	fh = fopen("histogram.dat", "w");
	if ( fh == NULL ) {
		ERROR("Couldn't open 'histogram.dat'\n");
		return;
	}

92
93
94
95
96
97
98
99
	if ( hist_min == hist_max ) {
		for ( i=0; i<n; i++ ) {
			if ( vals[i] > max ) max = vals[i];
			if ( vals[i] < min ) min = vals[i];
		}
	} else {
		min = hist_min;
		max = hist_max;
100
	}
Thomas White's avatar
Thomas White committed
101
	STATUS("min max nbins: %f %f %i\n", min, max, nbins);
102
	min--;  max++;
103

104
	for ( i=0; i<nbins; i++ ) {
105
106
107
		histo[i] = 0;
	}

108
	step = (max-min)/nbins;
109
110
111

	for ( i=0; i<n; i++ ) {
		int bin;
112
113
114
115
		if ( (vals[i] > min) && (vals[i] < max) ) {
			bin = (vals[i]-min)/step;
			histo[bin]++;
		}
116
117
	}

118
	for ( i=0; i<nbins; i++ ) {
119
120
121
122
123
124
125
		fprintf(fh, "%f %i\n", min+step*i, histo[i]);
	}

	fclose(fh);
}


126
static void merge_pattern(RefList *model, RefList *new, int max_only,
Thomas White's avatar
Thomas White committed
127
                          const SymOpList *sym,
128
                          double *hist_vals, signed int hist_h,
129
130
                          signed int hist_k, signed int hist_l, int *hist_n,
                          int pass)
131
{
132
133
	Reflection *refl;
	RefListIterator *iter;
134

135
136
137
	for ( refl = first_refl(new, &iter);
	      refl != NULL;
	      refl = next_refl(refl, iter) ) {
138
139

		double intensity;
140
		signed int h, k, l;
141
142
		Reflection *model_version;
		double model_int;
143

144
		get_indices(refl, &h, &k, &l);
Thomas White's avatar
Thomas White committed
145
146

		/* Put into the asymmetric unit for the target group */
Thomas White's avatar
Thomas White committed
147
		get_asymm(sym, h, k, l, &h, &k, &l);
Thomas White's avatar
Thomas White committed
148

149
150
151
152
		model_version = find_refl(model, h, k, l);
		if ( model_version == NULL ) {
			model_version = add_refl(model, h, k, l);
		}
153

154
155
		/* Read the intensity from the original location
		 * (i.e. before screwing around with symmetry) */
156
157
158
159
		intensity = get_intensity(refl);

		/* Get the current model intensity */
		model_int = get_intensity(model_version);
160

161
162
163
164
165
166
167
168
169
		if ( pass == 1 ) {

			/* User asked for max only? */
			if ( !max_only ) {
				set_int(model_version, model_int + intensity);
			} else {
				if ( intensity>get_intensity(model_version) ) {
					set_int(model_version, intensity);
				}
170
171
			}

172
173
174
175
			/* Increase redundancy */
			int cur_redundancy = get_redundancy(model_version);
			set_redundancy(model_version, cur_redundancy+1);

176

177
178
		} else if ( pass == 2 ) {

179
			double dev = get_temp1(model_version);
180
181
182
183
184
185
186
187
188

			/* Other ways of estimating the sigma are possible,
			 * choose from:
			 *    dev += pow(get_esd_intensity(refl), 2.0);
			 *    dev += pow(intensity, 2.0);
			 * But alter the other part of the calculation below
			 * as well. */
			dev += pow(intensity - model_int, 2.0);

189
			set_temp1(model_version, dev);
190
191
192
193
194
195
196
197
198

			if ( hist_vals != NULL ) {
				int p = *hist_n;
				if ( (h==hist_h) && (k==hist_k)
				  && (l==hist_l) )
				{
					hist_vals[p] = intensity;
					*hist_n = p+1;
				}
Thomas White's avatar
Thomas White committed
199

200
			}
201

202
203
		}

204
	}
205
206


207
208
209
}


210
211
212
enum {
	SCALE_NONE,
	SCALE_CONSTINT,
213
214
	SCALE_INTPERBRAGG,
	SCALE_TWOPASS,
215
216
217
};


Thomas White's avatar
Thomas White committed
218
static void scale_intensities(RefList *model, RefList *new, const SymOpList *sym)
219
220
{
	double s;
221
222
	double top = 0.0;
	double bot = 0.0;
223
	const int scaling = SCALE_INTPERBRAGG;
224
225
226
	Reflection *refl;
	RefListIterator *iter;
	Reflection *model_version;
227

228
229
230
	for ( refl = first_refl(new, &iter);
	      refl != NULL;
	      refl = next_refl(refl, iter) ) {
231
232
233

		double i1, i2;
		signed int hu, ku, lu;
234
		signed int h, k, l;
235

236
		get_indices(refl, &h, &k, &l);
237

238
239
240
		switch ( scaling ) {
		case SCALE_TWOPASS :

241
242
243
			model_version = find_refl(model, h, k, l);
			if ( model_version == NULL ) continue;

Thomas White's avatar
Thomas White committed
244
			get_asymm(sym, h, k, l, &hu, &ku, &lu);
245

246
247
			i1 = get_intensity(model_version);
			i2 = get_intensity(refl);
248
249
250
251

			/* Calculate LSQ estimate of scaling factor */
			top += i1 * i2;
			bot += i2 * i2;
252

253
			break;
254

255
256
257
		case SCALE_CONSTINT :

			/* Sum up the intensity in the pattern */
258
			i2 = get_intensity(refl);
259
260
261
262
			top += i2;

			break;

263
264
265
		case SCALE_INTPERBRAGG :

			/* Sum up the intensity in the pattern */
266
			i2 = get_intensity(refl);
267
268
269
270
271
			top += i2;
			bot += 1.0;

			break;

272
		}
273
274
275

	}

276
277
278
279
280
281
282
	switch ( scaling ) {
	case SCALE_TWOPASS :
		s = top / bot;
		break;
	case SCALE_CONSTINT :
		s = 1000.0 / top;
		break;
283
284
285
	case SCALE_INTPERBRAGG :
		s = 1000.0 / (top/bot);
		break;
286
	}
287
288

	/* Multiply the new pattern up by "s" */
289
290
291
292
293
294
295
	for ( refl = first_refl(new, &iter);
	      refl != NULL;
	      refl = next_refl(refl, iter) ) {

		double intensity = get_intensity(refl);
		set_int(refl, intensity*s);

296
297
298
299
	}
}


300
static void merge_all(FILE *fh, RefList *model,
301
                      int config_maxonly, int config_scale, int config_sum,
302
                      int config_startafter, int config_stopafter,
Thomas White's avatar
Thomas White committed
303
                      const SymOpList *sym,
304
                      int n_total_patterns,
305
306
                      double *hist_vals, signed int hist_h,
                      signed int hist_k, signed int hist_l,
307
                      int *hist_i, int pass)
308
{
309
	int rval;
Thomas White's avatar
Thomas White committed
310
	int n_patterns = 0;
311
312
313
	int n_used = 0;
	Reflection *refl;
	RefListIterator *iter;
314

315
316
317
	if ( skip_some_files(fh, config_startafter) ) {
		ERROR("Failed to skip first %i files.\n", config_startafter);
		return;
318
319
	}

320
321
	do {

322
		struct image image;
323

324
325
		image.det = NULL;

326
327
		/* Get data from next chunk */
		rval = read_chunk(fh, &image);
Thomas White's avatar
Thomas White committed
328
		if ( rval ) break;
329

330
331
332
		n_patterns++;

		if ( (image.reflections != NULL) && (image.indexed_cell) ) {
333
334
335

			/* Scale if requested */
			if ( config_scale ) {
336
337
				scale_intensities(model, image.reflections,
				                  sym);
338
339
			}

340
341
			merge_pattern(model, image.reflections, config_maxonly,
			              sym, hist_vals, hist_h, hist_k, hist_l,
342
			              hist_i, pass);
343

344
			n_used++;
345
346
347

		}

Thomas White's avatar
Thomas White committed
348
		free(image.filename);
349
350
351
		reflist_free(image.reflections);
		image_feature_list_free(image.features);
		cell_free(image.indexed_cell);
352

353
354
		progress_bar(n_patterns, n_total_patterns-config_startafter,
		             "Merging");
355

356
	} while ( rval == 0 );
357

358
	/* Divide by counts to get mean intensity if necessary */
359
	if ( (pass == 1) && !config_sum && !config_maxonly ) {
360

361
362
		Reflection *refl;
		RefListIterator *iter;
363

364
365
366
		for ( refl = first_refl(model, &iter);
		      refl != NULL;
		      refl = next_refl(refl, iter) ) {
367

368
369
			double intensity = get_intensity(refl);
			int red = get_redundancy(refl);
370

371
			set_int(refl, intensity / (double)red);
372

Thomas White's avatar
Thomas White committed
373
		}
374

Thomas White's avatar
Thomas White committed
375
376
	}

377
	/* Calculate ESDs */
378
379
380
381
	if ( pass == 2 ) {
		for ( refl = first_refl(model, &iter);
		      refl != NULL;
		      refl = next_refl(refl, iter) ) {
382

383
			double sum_squared_dev = get_temp1(refl);
384
			int red = get_redundancy(refl);
385
			int h, k, l;
386
			double esd;
387
			get_indices(refl,&h,&k,&l);
388
389
390
391
392
393
394
395
396
397
398
399
400
401

			/* Other ways of estimating the sigma are possible,
			 * such as:
			 *
			 *    double intensity = get_intensity(refl);
			 *    esd = sqrt( (sum_squared_dev/(double)red)
			 *              - pow(intensity,2.0) ) );
			 *
			 * But alter the other part of the calculation above
			 * as well. */
			esd = sqrt(sum_squared_dev)/(double)red;

			set_esd_intensity(refl, esd);

402
		}
403
	}
Thomas White's avatar
Thomas White committed
404

405
406
407
	if ( pass == 1 ) {
		STATUS("%i of the patterns could be used.\n", n_used);
	}
408
409
410
}


411
412
413
414
int main(int argc, char *argv[])
{
	int c;
	char *filename = NULL;
415
	char *output = NULL;
416
	FILE *fh;
417
	RefList *model;
418
	UnitCell *cell = NULL;
Thomas White's avatar
Thomas White committed
419
	int config_maxonly = 0;
420
	int config_startafter = 0;
Thomas White's avatar
Thomas White committed
421
	int config_stopafter = 0;
422
	int config_sum = 0;
423
	int config_scale = 0;
424
	unsigned int n_total_patterns;
Thomas White's avatar
Thomas White committed
425
426
	char *sym_str = NULL;
	SymOpList *sym;
427
	char *pdb = NULL;
428
429
	char *histo = NULL;
	signed int hist_h, hist_k, hist_l;
430
431
	signed int hist_nbins=50;
	float hist_min=0.0, hist_max=0.0;
432
433
	double *hist_vals = NULL;
	int hist_i;
434
	struct beam_params *beam = NULL;
435
	int space_for_hist = 0;
436
	char *histo_params = NULL;
437
438
439
440
441

	/* Long options */
	const struct option longopts[] = {
		{"help",               0, NULL,               'h'},
		{"input",              1, NULL,               'i'},
Thomas White's avatar
Thomas White committed
442
		{"output",             1, NULL,               'o'},
Thomas White's avatar
Thomas White committed
443
		{"max-only",           0, &config_maxonly,     1},
Thomas White's avatar
Thomas White committed
444
		{"output-every",       1, NULL,               'e'},
Thomas White's avatar
Thomas White committed
445
		{"stop-after",         1, NULL,               's'},
446
		{"start-after",        1, NULL,               'f'},
447
		{"sum",                0, &config_sum,         1},
448
		{"scale",              0, &config_scale,       1},
449
		{"symmetry",           1, NULL,               'y'},
450
		{"pdb",                1, NULL,               'p'},
451
		{"histogram",          1, NULL,               'g'},
452
		{"hist-parameters",    1, NULL,               'z'},
453
		{"beam",               1, NULL,               'b'},
454
455
456
457
		{0, 0, NULL, 0}
	};

	/* Short options */
458
	while ((c = getopt_long(argc, argv, "hi:e:o:p:y:g:f:b:z:",
459
	                        longopts, NULL)) != -1) {
460
461

		switch (c) {
Thomas White's avatar
Thomas White committed
462
		case 'h' :
463
464
465
			show_help(argv[0]);
			return 0;

Thomas White's avatar
Thomas White committed
466
		case 'i' :
467
468
469
			filename = strdup(optarg);
			break;

Thomas White's avatar
Thomas White committed
470
		case 'o' :
471
472
473
			output = strdup(optarg);
			break;

Thomas White's avatar
Thomas White committed
474
		case 's' :
Thomas White's avatar
Thomas White committed
475
476
477
			config_stopafter = atoi(optarg);
			break;

478
479
480
481
		case 'f' :
			config_startafter = atoi(optarg);
			break;

Thomas White's avatar
Thomas White committed
482
		case 'p' :
483
484
485
			pdb = strdup(optarg);
			break;

486
		case 'y' :
Thomas White's avatar
Thomas White committed
487
			sym_str = strdup(optarg);
488
489
			break;

490
491
492
493
		case 'g' :
			histo = strdup(optarg);
			break;

494
495
496
497
		case 'z' :
			histo_params = strdup(optarg);
			break;

498
499
500
501
502
503
504
505
506
		case 'b' :
			beam = get_beam_parameters(optarg);
			if ( beam == NULL ) {
				ERROR("Failed to load beam parameters"
				      " from '%s'\n", optarg);
				return 1;
			}
			break;

Thomas White's avatar
Thomas White committed
507
		case 0 :
508
509
			break;

Thomas White's avatar
Thomas White committed
510
		default :
511
512
513
514
515
516
517
518
519
520
			return 1;
		}

	}

	if ( filename == NULL ) {
		ERROR("Please specify filename using the -i option\n");
		return 1;
	}

521
522
523
524
	if ( output == NULL ) {
		output = strdup("processed.hkl");
	}

525
526
527
528
529
530
531
532
533
	if ( pdb != NULL ) {
		cell = load_cell_from_pdb(pdb);
		if ( cell == NULL ) {
			ERROR("Failed to load cell from '%s'\n", pdb);
			return 1;
		}
		free(pdb);
	} else {
		cell = NULL;
Thomas White's avatar
Thomas White committed
534
	}
Thomas White's avatar
Thomas White committed
535

Thomas White's avatar
Thomas White committed
536
537
538
	if ( sym_str == NULL ) sym_str = strdup("1");
	sym = get_pointgroup(sym_str);
	free(sym_str);
539

540
541
542
543
544
545
546
547
548
549
550
	/* Open the data stream */
	if ( strcmp(filename, "-") == 0 ) {
		fh = stdin;
	} else {
		fh = fopen(filename, "r");
	}
	free(filename);
	if ( fh == NULL ) {
		ERROR("Failed to open input file\n");
		return 1;
	}
Thomas White's avatar
Tidy-up    
Thomas White committed
551

552
553
	/* Count the number of patterns in the file */
	n_total_patterns = count_patterns(fh);
Thomas White's avatar
Thomas White committed
554
555
556
557
	if ( n_total_patterns == 0 ) {
		ERROR("No patterns to process.\n");
		return 1;
	}
558
559
	STATUS("There are %i patterns to process\n", n_total_patterns);
	rewind(fh);
560

561
562
	model = reflist_new();

563
	if ( histo != NULL ) {
Thomas White's avatar
Thomas White committed
564

565
		int r;
Thomas White's avatar
Thomas White committed
566

567
568
569
570
571
		r = sscanf(histo, "%i,%i,%i", &hist_h, &hist_k, &hist_l);
		if ( r != 3 ) {
			ERROR("Invalid indices for '--histogram'\n");
			return 1;
		}
Thomas White's avatar
Thomas White committed
572

Thomas White's avatar
Thomas White committed
573
		space_for_hist = n_total_patterns * num_equivs(sym, NULL);
574
575
576
		hist_vals = malloc(space_for_hist * sizeof(double));
		free(histo);
		STATUS("Histogramming %i %i %i -> ", hist_h, hist_k, hist_l);
Thomas White's avatar
Thomas White committed
577

578
		/* Put into the asymmetric cell for the target group */
Thomas White's avatar
Thomas White committed
579
580
		get_asymm(sym, hist_h, hist_k, hist_l,
		          &hist_h, &hist_k, &hist_l);
581
		STATUS("%i %i %i\n", hist_h, hist_k, hist_l);
Thomas White's avatar
Thomas White committed
582

583
584
	}

585
	if ( histo_params != NULL ) {
Thomas White's avatar
Thomas White committed
586

587
		int rr;
Thomas White's avatar
Thomas White committed
588
589
590

		rr = sscanf(histo_params, "%f,%f,%i", &hist_min, &hist_max,
		                                      &hist_nbins);
591
592
593
594
595
		if ( rr != 3 ) {
			ERROR("Invalid parameters for '--hist-parameters'\n");
			return 1;
		}
		free(histo_params);
Thomas White's avatar
Thomas White committed
596
597
598
		if ( hist_max <= hist_min ) {
			ERROR("Invalid range for '--hist-parameters'. "
			      "Make sure that 'max' is greater than 'min'.\n");
599
600
			return 1;
		}
Thomas White's avatar
Thomas White committed
601

602
603
	}

604
	hist_i = 0;
605
	merge_all(fh, model, config_maxonly, config_scale, config_sum,
606
	          config_startafter, config_stopafter,
607
                  sym, n_total_patterns,
608
                  NULL, 0, 0, 0, NULL, 1);
Thomas White's avatar
Thomas White committed
609
610
611
612
	if ( ferror(fh) ) {
		ERROR("Stream read error.\n");
		return 1;
	}
613
	rewind(fh);
614

615
616
	STATUS("Extra pass to calculate ESDs...\n");
	rewind(fh);
617
618
	merge_all(fh, model, config_maxonly, config_scale, 0,
	          config_startafter, config_stopafter, sym, n_total_patterns,
619
	          hist_vals, hist_h, hist_k, hist_l, &hist_i, 2);
Thomas White's avatar
Thomas White committed
620
621
622
623
	if ( ferror(fh) ) {
		ERROR("Stream read error.\n");
		return 1;
	}
624

625
626
627
628
629
630
631
632
633
634
635
	if ( space_for_hist && (hist_i >= space_for_hist) ) {
		ERROR("Histogram array was too small!\n");
	}

	if ( hist_vals != NULL ) {
		STATUS("%i %i %i was seen %i times.\n", hist_h, hist_k, hist_l,
		                                        hist_i);
		plot_histogram(hist_vals, hist_i, hist_min, hist_max,
		               hist_nbins);
	}

636
	write_reflist(output, model, cell);
637
638

	fclose(fh);
639

640
	free(sym);
641
	reflist_free(model);
Thomas White's avatar
Thomas White committed
642
	free(output);
643
	if ( cell != NULL ) cell_free(cell);
644

645
646
	return 0;
}