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
8
 * (c) 2011      Andrew Martin <andrew.martin@desy.de>
 *
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 * 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"
27
#include "reflist-utils.h"
28
#include "symmetry.h"
29
#include "stream.h"
30
#include "beam-parameters.h"
31
32
#include "reflist.h"
#include "image.h"
33
34
35
36
37


static void show_help(const char *s)
{
	printf("Syntax: %s [options]\n\n", s);
Thomas White's avatar
Thomas White committed
38
39
40
	printf(
"Assemble and process FEL Bragg intensities.\n"
"\n"
41
42
43
"  -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"
44
"                             Default: processed.hkl).\n"
45
"  -p, --pdb=<filename>      PDB file to use (default: molecule.pdb).\n"
46
"  -b, --beam=<file>         Get beam parameters from file (used for sigmas).\n"
Thomas White's avatar
Thomas White committed
47
"\n"
48
49
50
51
52
53
54
55
"      --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"
56
"      --start-after=<n>     Skip n patterns at the start of the stream.\n"
57
58
59
"      --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"
60
61
"  -g, --histogram=<h,k,l>   Calculate the histogram of measurements for this\n"
"                             reflection.\n"
62
"  -z, --hist-parameters     Set the range for the histogram and the number of\n"
Thomas White's avatar
Thomas White committed
63
"          =<min,max,nbins>   bins. \n"
64
"\n"
65
66
"      --scale               Scale each pattern for best fit with the current\n"
"                             model.\n"
Thomas White's avatar
Thomas White committed
67
"  -y, --symmetry=<sym>      Merge according to point group <sym>.\n"
68
69
"      --reference=<file>    Compare against intensities from <file> when\n"
"                             scaling or resolving ambiguities.\n"
70
71
"                             The symmetry of the reference list must be the\n"
"                             same as that given with '-y'.\n"
72
);
73
74
75
}


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

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

91
92
93
94
95
96
97
98
	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;
99
	}
Thomas White's avatar
Thomas White committed
100
	STATUS("min max nbins: %f %f %i\n", min, max, nbins);
101
	min--;  max++;
102

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

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

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

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

	fclose(fh);
}


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

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

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

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

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

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

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

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

160
161
162
163
164
165
166
167
168
		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);
				}
169
170
			}

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

175

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

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

			/* 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);

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

			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
198

199
			}
200

201
202
		}

203
	}
204
205


206
207
208
}


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


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

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

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

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

237
238
239
		switch ( scaling ) {
		case SCALE_TWOPASS :

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

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

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

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

252
			break;
253

254
255
256
		case SCALE_CONSTINT :

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

			break;

262
263
264
		case SCALE_INTPERBRAGG :

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

			break;

271
		}
272
273
274

	}

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

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

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

295
296
297
298
	}
}


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

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

319
320
	do {

321
		struct image image;
322

323
324
		image.det = NULL;

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

329
330
331
		n_patterns++;

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

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

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

343
			n_used++;
344
345
346

		}

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

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

355
	} while ( rval == 0 );
356

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

360
361
		Reflection *refl;
		RefListIterator *iter;
362

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

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

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

Thomas White's avatar
Thomas White committed
372
		}
373

Thomas White's avatar
Thomas White committed
374
375
	}

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

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

			/* 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);

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

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


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

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

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

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

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

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

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

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

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

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

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

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

497
498
499
500
501
502
503
504
505
		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
506
		case 0 :
507
508
			break;

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

	}

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

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

524
525
526
527
528
529
530
531
532
	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
533
	}
Thomas White's avatar
Thomas White committed
534

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

539
540
541
542
543
544
545
546
547
548
549
	/* 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
550

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

560
561
	model = reflist_new();

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

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

566
567
568
569
570
		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
571

Thomas White's avatar
Thomas White committed
572
		space_for_hist = n_total_patterns * num_equivs(sym, NULL);
573
574
575
		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
576

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

582
583
	}

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

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

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

601
602
	}

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

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

624
625
626
627
628
629
630
631
632
633
634
	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);
	}

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

	fclose(fh);
638

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

644
645
	return 0;
}