process_hkl.c 13.9 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
/* Number of divisions for intensity histograms */
36
#define NBINS (50)
Thomas White's avatar
Thomas White committed
37
38


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


78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
static void plot_histogram(double *vals, int n)
{
	int i;
	double max = -INFINITY;
	double min = +INFINITY;
	double step;
	int histo[NBINS];
	FILE *fh;

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

	for ( i=0; i<n; i++ ) {
		if ( vals[i] > max ) max = vals[i];
		if ( vals[i] < min ) min = vals[i];
	}
	STATUS("%f %f\n", min, max);
98
	min--;  max++;
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119

	for ( i=0; i<NBINS; i++ ) {
		histo[i] = 0;
	}

	step = (max-min)/NBINS;

	for ( i=0; i<n; i++ ) {
		int bin;
		bin = (vals[i]-min)/step;
		histo[bin]++;
	}

	for ( i=0; i<NBINS; i++ ) {
		fprintf(fh, "%f %i\n", min+step*i, histo[i]);
	}

	fclose(fh);
}


120
static void merge_pattern(RefList *model, RefList *new, int max_only,
Thomas White's avatar
Thomas White committed
121
                          const SymOpList *sym,
122
                          double *hist_vals, signed int hist_h,
123
124
                          signed int hist_k, signed int hist_l, int *hist_n,
                          int pass)
125
{
126
127
	Reflection *refl;
	RefListIterator *iter;
128

129
130
131
	for ( refl = first_refl(new, &iter);
	      refl != NULL;
	      refl = next_refl(refl, iter) ) {
132
133

		double intensity;
134
		signed int h, k, l;
135
136
		Reflection *model_version;
		double model_int;
137

138
		get_indices(refl, &h, &k, &l);
Thomas White's avatar
Thomas White committed
139
140

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

143
144
145
146
		model_version = find_refl(model, h, k, l);
		if ( model_version == NULL ) {
			model_version = add_refl(model, h, k, l);
		}
147

148
149
		/* Read the intensity from the original location
		 * (i.e. before screwing around with symmetry) */
150
151
152
153
		intensity = get_intensity(refl);

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

155
156
157
158
159
160
161
162
163
		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);
				}
164
165
			}

166
167
168
169
170
171
			/* Increase redundancy */
			int cur_redundancy = get_redundancy(model_version);
			set_redundancy(model_version, cur_redundancy+1);

		} else if ( pass == 2 ) {

172
			double dev = get_temp1(model_version);
173
174
175
176
177
178
179
180
181

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

182
			set_temp1(model_version, dev);
183
184
185
186
187
188
189
190
191

			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
192

193
			}
194

195
196
		}

197
	}
198
199


200
201
202
}


203
204
205
enum {
	SCALE_NONE,
	SCALE_CONSTINT,
206
207
	SCALE_INTPERBRAGG,
	SCALE_TWOPASS,
208
209
210
};


Thomas White's avatar
Thomas White committed
211
static void scale_intensities(RefList *model, RefList *new, const SymOpList *sym)
212
213
{
	double s;
214
215
	double top = 0.0;
	double bot = 0.0;
216
	const int scaling = SCALE_INTPERBRAGG;
217
218
219
	Reflection *refl;
	RefListIterator *iter;
	Reflection *model_version;
220

221
222
223
	for ( refl = first_refl(new, &iter);
	      refl != NULL;
	      refl = next_refl(refl, iter) ) {
224
225
226

		double i1, i2;
		signed int hu, ku, lu;
227
		signed int h, k, l;
228

229
		get_indices(refl, &h, &k, &l);
230

231
232
233
		switch ( scaling ) {
		case SCALE_TWOPASS :

234
235
236
			model_version = find_refl(model, h, k, l);
			if ( model_version == NULL ) continue;

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

239
240
			i1 = get_intensity(model_version);
			i2 = get_intensity(refl);
241
242
243
244

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

246
			break;
247

248
249
250
		case SCALE_CONSTINT :

			/* Sum up the intensity in the pattern */
251
			i2 = get_intensity(refl);
252
253
254
255
			top += i2;

			break;

256
257
258
		case SCALE_INTPERBRAGG :

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

			break;

265
		}
266
267
268

	}

269
270
271
272
273
274
275
	switch ( scaling ) {
	case SCALE_TWOPASS :
		s = top / bot;
		break;
	case SCALE_CONSTINT :
		s = 1000.0 / top;
		break;
276
277
278
	case SCALE_INTPERBRAGG :
		s = 1000.0 / (top/bot);
		break;
279
	}
280
281

	/* Multiply the new pattern up by "s" */
282
283
284
285
286
287
288
	for ( refl = first_refl(new, &iter);
	      refl != NULL;
	      refl = next_refl(refl, iter) ) {

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

289
290
291
292
	}
}


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

308
309
310
	if ( skip_some_files(fh, config_startafter) ) {
		ERROR("Failed to skip first %i files.\n", config_startafter);
		return;
311
312
	}

313
314
	do {

315
		struct image image;
316

317
318
		image.det = NULL;

319
320
		/* Get data from next chunk */
		rval = read_chunk(fh, &image);
Thomas White's avatar
Thomas White committed
321
		if ( rval ) break;
322

323
324
325
		n_patterns++;

		if ( (image.reflections != NULL) && (image.indexed_cell) ) {
326
327
328

			/* Scale if requested */
			if ( config_scale ) {
329
330
				scale_intensities(model, image.reflections,
				                  sym);
331
332
			}

333
334
			merge_pattern(model, image.reflections, config_maxonly,
			              sym, hist_vals, hist_h, hist_k, hist_l,
335
			              hist_i, pass);
336

337
			n_used++;
338
339
340

		}

Thomas White's avatar
Thomas White committed
341
		free(image.filename);
342
343
344
		reflist_free(image.reflections);
		image_feature_list_free(image.features);
		cell_free(image.indexed_cell);
345

346
347
		progress_bar(n_patterns, n_total_patterns-config_startafter,
		             "Merging");
348

349
	} while ( rval == 0 );
350

351
	/* Divide by counts to get mean intensity if necessary */
352
	if ( (pass == 1) && !config_sum && !config_maxonly ) {
353

354
355
		Reflection *refl;
		RefListIterator *iter;
356

357
358
359
		for ( refl = first_refl(model, &iter);
		      refl != NULL;
		      refl = next_refl(refl, iter) ) {
360

361
362
			double intensity = get_intensity(refl);
			int red = get_redundancy(refl);
363

364
			set_int(refl, intensity / (double)red);
365

Thomas White's avatar
Thomas White committed
366
		}
367

Thomas White's avatar
Thomas White committed
368
369
	}

370
	/* Calculate ESDs */
371
372
373
374
	if ( pass == 2 ) {
		for ( refl = first_refl(model, &iter);
		      refl != NULL;
		      refl = next_refl(refl, iter) ) {
375

376
			double sum_squared_dev = get_temp1(refl);
377
			int red = get_redundancy(refl);
378
			int h, k, l;
379
			double esd;
380
			get_indices(refl,&h,&k,&l);
381
382
383
384
385
386
387
388
389
390
391
392
393
394

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

395
		}
396
	}
Thomas White's avatar
Thomas White committed
397

398
399
400
	if ( pass == 1 ) {
		STATUS("%i of the patterns could be used.\n", n_used);
	}
401
402
403
}


404
405
406
407
int main(int argc, char *argv[])
{
	int c;
	char *filename = NULL;
408
	char *output = NULL;
409
	FILE *fh;
410
	RefList *model;
411
	UnitCell *cell = NULL;
Thomas White's avatar
Thomas White committed
412
	int config_maxonly = 0;
413
	int config_startafter = 0;
Thomas White's avatar
Thomas White committed
414
	int config_stopafter = 0;
415
	int config_sum = 0;
416
	int config_scale = 0;
417
	unsigned int n_total_patterns;
Thomas White's avatar
Thomas White committed
418
419
	char *sym_str = NULL;
	SymOpList *sym;
420
	char *pdb = NULL;
421
422
423
424
	char *histo = NULL;
	signed int hist_h, hist_k, hist_l;
	double *hist_vals = NULL;
	int hist_i;
425
	struct beam_params *beam = NULL;
426
	int space_for_hist = 0;
427
428
429
430
431

	/* Long options */
	const struct option longopts[] = {
		{"help",               0, NULL,               'h'},
		{"input",              1, NULL,               'i'},
Thomas White's avatar
Thomas White committed
432
		{"output",             1, NULL,               'o'},
Thomas White's avatar
Thomas White committed
433
		{"max-only",           0, &config_maxonly,     1},
Thomas White's avatar
Thomas White committed
434
		{"output-every",       1, NULL,               'e'},
Thomas White's avatar
Thomas White committed
435
		{"stop-after",         1, NULL,               's'},
436
		{"start-after",        1, NULL,               'f'},
437
		{"sum",                0, &config_sum,         1},
438
		{"scale",              0, &config_scale,       1},
439
		{"symmetry",           1, NULL,               'y'},
440
		{"pdb",                1, NULL,               'p'},
441
		{"histogram",          1, NULL,               'g'},
442
		{"beam",               1, NULL,               'b'},
443
444
445
446
		{0, 0, NULL, 0}
	};

	/* Short options */
447
	while ((c = getopt_long(argc, argv, "hi:e:o:p:y:g:f:b:",
448
	                        longopts, NULL)) != -1) {
449
450

		switch (c) {
Thomas White's avatar
Thomas White committed
451
		case 'h' :
452
453
454
			show_help(argv[0]);
			return 0;

Thomas White's avatar
Thomas White committed
455
		case 'i' :
456
457
458
			filename = strdup(optarg);
			break;

Thomas White's avatar
Thomas White committed
459
		case 'o' :
460
461
462
			output = strdup(optarg);
			break;

Thomas White's avatar
Thomas White committed
463
		case 's' :
Thomas White's avatar
Thomas White committed
464
465
466
			config_stopafter = atoi(optarg);
			break;

467
468
469
470
		case 'f' :
			config_startafter = atoi(optarg);
			break;

Thomas White's avatar
Thomas White committed
471
		case 'p' :
472
473
474
			pdb = strdup(optarg);
			break;

475
		case 'y' :
Thomas White's avatar
Thomas White committed
476
			sym_str = strdup(optarg);
477
478
			break;

479
480
481
482
		case 'g' :
			histo = strdup(optarg);
			break;

483
484
485
486
487
488
489
490
491
		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
492
		case 0 :
493
494
			break;

Thomas White's avatar
Thomas White committed
495
		default :
496
497
498
499
500
501
502
503
504
505
			return 1;
		}

	}

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

506
507
508
509
	if ( output == NULL ) {
		output = strdup("processed.hkl");
	}

510
511
512
513
514
515
516
517
518
	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
519
	}
Thomas White's avatar
Thomas White committed
520

Thomas White's avatar
Thomas White committed
521
522
523
	if ( sym_str == NULL ) sym_str = strdup("1");
	sym = get_pointgroup(sym_str);
	free(sym_str);
524

525
526
527
528
529
530
531
532
533
534
535
	/* 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
536

537
538
	/* Count the number of patterns in the file */
	n_total_patterns = count_patterns(fh);
Thomas White's avatar
Thomas White committed
539
540
541
542
	if ( n_total_patterns == 0 ) {
		ERROR("No patterns to process.\n");
		return 1;
	}
543
544
	STATUS("There are %i patterns to process\n", n_total_patterns);
	rewind(fh);
545

546
547
	model = reflist_new();

548
549
550
551
552
553
554
	if ( histo != NULL ) {
		int r;
		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
555
		space_for_hist = n_total_patterns * num_equivs(sym, NULL);
556
557
558
559
		hist_vals = malloc(space_for_hist * sizeof(double));
		free(histo);
		STATUS("Histogramming %i %i %i -> ", hist_h, hist_k, hist_l);
		/* Put into the asymmetric cell for the target group */
Thomas White's avatar
Thomas White committed
560
561
		get_asymm(sym, hist_h, hist_k, hist_l,
		          &hist_h, &hist_k, &hist_l);
562
563
564
		STATUS("%i %i %i\n", hist_h, hist_k, hist_l);
	}

565
	hist_i = 0;
566
	merge_all(fh, model, config_maxonly, config_scale, config_sum,
567
	          config_startafter, config_stopafter,
568
                  sym, n_total_patterns,
569
                  hist_vals, hist_h, hist_k, hist_l, &hist_i, 1);
Thomas White's avatar
Thomas White committed
570
571
572
573
	if ( ferror(fh) ) {
		ERROR("Stream read error.\n");
		return 1;
	}
574
	rewind(fh);
575
576
577
	if ( space_for_hist && (hist_i >= space_for_hist) ) {
		ERROR("Histogram array was too small!\n");
	}
578

579
580
581
582
583
584
	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);
	}

585
586
	STATUS("Extra pass to calculate ESDs...\n");
	rewind(fh);
587
588
	merge_all(fh, model, config_maxonly, config_scale, 0,
	          config_startafter, config_stopafter, sym, n_total_patterns,
589
	          NULL, 0, 0, 0, NULL, 2);
Thomas White's avatar
Thomas White committed
590
591
592
593
	if ( ferror(fh) ) {
		ERROR("Stream read error.\n");
		return 1;
	}
594

595
	write_reflist(output, model, cell);
596
597

	fclose(fh);
598
	free(sym);
599
	reflist_free(model);
Thomas White's avatar
Thomas White committed
600
	free(output);
601
	if ( cell != NULL ) cell_free(cell);
602

603
604
	return 0;
}