process_hkl.c 14.6 KB
Newer Older
1
2
3
4
5
/*
 * process_hkl.c
 *
 * Assemble and process FEL Bragg intensities
 *
Thomas White's avatar
Thomas White committed
6
7
8
 * Copyright © 2012 Thomas White <taw@physics.org>
 * Copyright © 2012 Andrew Martin <andrew.martin@desy.de>
 * Copyright © 2012 Lorenzo Galli <lorenzo.galli@desy.de>
9
 *
Thomas White's avatar
Thomas White committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 * This file is part of CrystFEL.
 *
 * CrystFEL is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * CrystFEL is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with CrystFEL.  If not, see <http://www.gnu.org/licenses/>.
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
 *
 */


#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"
41
#include "reflist-utils.h"
42
#include "symmetry.h"
43
#include "stream.h"
44
45
#include "reflist.h"
#include "image.h"
46
47
48
49
50


static void show_help(const char *s)
{
	printf("Syntax: %s [options]\n\n", s);
Thomas White's avatar
Thomas White committed
51
52
53
	printf(
"Assemble and process FEL Bragg intensities.\n"
"\n"
54
55
56
"  -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"
57
"                             Default: processed.hkl).\n"
Thomas White's avatar
Thomas White committed
58
"  -y, --symmetry=<sym>      Merge according to point group <sym>.\n"
Thomas White's avatar
Thomas White committed
59
"\n"
60
61
62
63
64
65
66
67
"      --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"
68
"      --start-after=<n>     Skip n patterns at the start of the stream.\n"
69
70
71
"      --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"
72
73
"  -g, --histogram=<h,k,l>   Calculate the histogram of measurements for this\n"
"                             reflection.\n"
74
"  -z, --hist-parameters     Set the range for the histogram and the number of\n"
Thomas White's avatar
Thomas White committed
75
"          =<min,max,nbins>   bins. \n"
76
"\n"
77
78
"      --scale               Scale each pattern for best fit with the current\n"
"                             model.\n"
79
"      --reference=<file>    Compare against intensities from <file> when\n"
Thomas White's avatar
Thomas White committed
80
"                             scaling. \n"
81
);
82
83
84
}


Thomas White's avatar
Thomas White committed
85
86
static void plot_histogram(double *vals, int n, float hist_min, float hist_max,
                           int nbins)
87
88
89
90
91
{
	int i;
	double max = -INFINITY;
	double min = +INFINITY;
	double step;
92
	int histo[nbins];
93
94
95
96
97
98
99
100
	FILE *fh;

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

101
102
103
104
105
106
107
108
	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;
109
	}
Thomas White's avatar
Thomas White committed
110
	STATUS("min max nbins: %f %f %i\n", min, max, nbins);
111
	min--;  max++;
112

113
	for ( i=0; i<nbins; i++ ) {
114
115
116
		histo[i] = 0;
	}

117
	step = (max-min)/nbins;
118
119
120

	for ( i=0; i<n; i++ ) {
		int bin;
121
122
123
124
		if ( (vals[i] > min) && (vals[i] < max) ) {
			bin = (vals[i]-min)/step;
			histo[bin]++;
		}
125
126
	}

127
	for ( i=0; i<nbins; i++ ) {
128
129
130
131
132
133
134
		fprintf(fh, "%f %i\n", min+step*i, histo[i]);
	}

	fclose(fh);
}


135
static void merge_pattern(RefList *model, RefList *new, int max_only,
Thomas White's avatar
Thomas White committed
136
                          const SymOpList *sym,
137
                          double *hist_vals, signed int hist_h,
138
139
                          signed int hist_k, signed int hist_l, int *hist_n,
                          int pass)
140
{
141
142
	Reflection *refl;
	RefListIterator *iter;
143

144
145
146
	for ( refl = first_refl(new, &iter);
	      refl != NULL;
	      refl = next_refl(refl, iter) ) {
147
148

		double intensity;
149
		signed int h, k, l;
150
151
		Reflection *model_version;
		double model_int;
152

153
		get_indices(refl, &h, &k, &l);
Thomas White's avatar
Thomas White committed
154
155

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

158
159
160
161
		model_version = find_refl(model, h, k, l);
		if ( model_version == NULL ) {
			model_version = add_refl(model, h, k, l);
		}
162

163
164
		/* Read the intensity from the original location
		 * (i.e. before screwing around with symmetry) */
165
166
167
168
		intensity = get_intensity(refl);

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

170
171
172
173
174
175
176
177
178
		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);
				}
179
180
			}

181
182
183
184
			/* Increase redundancy */
			int cur_redundancy = get_redundancy(model_version);
			set_redundancy(model_version, cur_redundancy+1);

185

186
187
		} else if ( pass == 2 ) {

188
			double dev = get_temp1(model_version);
189
190
191
192
193
194
195
196
197

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

198
			set_temp1(model_version, dev);
199
200
201
202
203
204
205
206
207

			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
208

209
			}
210

211
212
		}

213
	}
214
215


216
217
218
}


219
220
221
enum {
	SCALE_NONE,
	SCALE_CONSTINT,
222
223
	SCALE_INTPERBRAGG,
	SCALE_TWOPASS,
224
225
226
};


Thomas White's avatar
Thomas White committed
227
static void scale_intensities(RefList *model, RefList *new, const SymOpList *sym)
228
229
{
	double s;
230
231
	double top = 0.0;
	double bot = 0.0;
232
	const int scaling = SCALE_INTPERBRAGG;
233
234
235
	Reflection *refl;
	RefListIterator *iter;
	Reflection *model_version;
236

237
238
239
	for ( refl = first_refl(new, &iter);
	      refl != NULL;
	      refl = next_refl(refl, iter) ) {
240
241
242

		double i1, i2;
		signed int hu, ku, lu;
243
		signed int h, k, l;
244

245
		get_indices(refl, &h, &k, &l);
246

247
248
249
		switch ( scaling ) {
		case SCALE_TWOPASS :

250
251
252
			model_version = find_refl(model, h, k, l);
			if ( model_version == NULL ) continue;

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

255
256
			i1 = get_intensity(model_version);
			i2 = get_intensity(refl);
257
258
259
260

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

262
			break;
263

264
265
266
		case SCALE_CONSTINT :

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

			break;

272
273
274
		case SCALE_INTPERBRAGG :

			/* Sum up the intensity in the pattern */
275
			i2 = get_intensity(refl);
276
277
278
279
280
			top += i2;
			bot += 1.0;

			break;

281
		}
282
283
284

	}

285
286
287
288
289
290
291
	switch ( scaling ) {
	case SCALE_TWOPASS :
		s = top / bot;
		break;
	case SCALE_CONSTINT :
		s = 1000.0 / top;
		break;
292
293
294
	case SCALE_INTPERBRAGG :
		s = 1000.0 / (top/bot);
		break;
295
	}
296
297

	/* Multiply the new pattern up by "s" */
298
299
300
301
302
303
304
	for ( refl = first_refl(new, &iter);
	      refl != NULL;
	      refl = next_refl(refl, iter) ) {

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

305
306
307
308
	}
}


309
static void merge_all(FILE *fh, RefList *model,
310
                      int config_maxonly, int config_scale, int config_sum,
311
                      int config_startafter, int config_stopafter,
Thomas White's avatar
Thomas White committed
312
                      const SymOpList *sym,
313
                      int n_total_patterns,
314
315
                      double *hist_vals, signed int hist_h,
                      signed int hist_k, signed int hist_l,
316
                      int *hist_i, int pass)
317
{
318
	int rval;
Thomas White's avatar
Thomas White committed
319
	int n_patterns = 0;
320
321
322
	int n_used = 0;
	Reflection *refl;
	RefListIterator *iter;
323

324
325
326
	if ( skip_some_files(fh, config_startafter) ) {
		ERROR("Failed to skip first %i files.\n", config_startafter);
		return;
327
328
	}

329
330
	do {

331
		struct image image;
332

333
334
		image.det = NULL;

335
336
		/* Get data from next chunk */
		rval = read_chunk(fh, &image);
Thomas White's avatar
Thomas White committed
337
		if ( rval ) break;
338

339
340
341
		n_patterns++;

		if ( (image.reflections != NULL) && (image.indexed_cell) ) {
342
343
344

			/* Scale if requested */
			if ( config_scale ) {
345
346
				scale_intensities(model, image.reflections,
				                  sym);
347
348
			}

349
350
			merge_pattern(model, image.reflections, config_maxonly,
			              sym, hist_vals, hist_h, hist_k, hist_l,
351
			              hist_i, pass);
352

353
			n_used++;
354
355
356

		}

Thomas White's avatar
Thomas White committed
357
		free(image.filename);
358
359
360
		reflist_free(image.reflections);
		image_feature_list_free(image.features);
		cell_free(image.indexed_cell);
361

362
363
		progress_bar(n_patterns, n_total_patterns-config_startafter,
		             "Merging");
364

365
	} while ( rval == 0 );
366

367
	/* Divide by counts to get mean intensity if necessary */
368
	if ( (pass == 1) && !config_sum && !config_maxonly ) {
369

370
371
		Reflection *refl;
		RefListIterator *iter;
372

373
374
375
		for ( refl = first_refl(model, &iter);
		      refl != NULL;
		      refl = next_refl(refl, iter) ) {
376

377
378
			double intensity = get_intensity(refl);
			int red = get_redundancy(refl);
379

380
			set_int(refl, intensity / (double)red);
381

Thomas White's avatar
Thomas White committed
382
		}
383

Thomas White's avatar
Thomas White committed
384
385
	}

386
	/* Calculate ESDs */
387
388
389
390
	if ( pass == 2 ) {
		for ( refl = first_refl(model, &iter);
		      refl != NULL;
		      refl = next_refl(refl, iter) ) {
391

392
			double sum_squared_dev = get_temp1(refl);
393
			int red = get_redundancy(refl);
394
			int h, k, l;
395
			double esd;
396
			get_indices(refl,&h,&k,&l);
397
398
399
400
401
402
403
404
405
406
407
408
409
410

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

411
		}
412
	}
Thomas White's avatar
Thomas White committed
413

414
415
416
	if ( pass == 1 ) {
		STATUS("%i of the patterns could be used.\n", n_used);
	}
417
418
419
}


420
421
422
423
int main(int argc, char *argv[])
{
	int c;
	char *filename = NULL;
424
	char *output = NULL;
425
	FILE *fh;
426
	RefList *model;
Thomas White's avatar
Thomas White committed
427
	int config_maxonly = 0;
428
	int config_startafter = 0;
Thomas White's avatar
Thomas White committed
429
	int config_stopafter = 0;
430
	int config_sum = 0;
431
	int config_scale = 0;
432
	unsigned int n_total_patterns;
Thomas White's avatar
Thomas White committed
433
434
	char *sym_str = NULL;
	SymOpList *sym;
435
	char *pdb = NULL;
436
437
	char *histo = NULL;
	signed int hist_h, hist_k, hist_l;
438
439
	signed int hist_nbins=50;
	float hist_min=0.0, hist_max=0.0;
440
441
	double *hist_vals = NULL;
	int hist_i;
442
	int space_for_hist = 0;
443
	char *histo_params = NULL;
444
445
446
447
448

	/* Long options */
	const struct option longopts[] = {
		{"help",               0, NULL,               'h'},
		{"input",              1, NULL,               'i'},
Thomas White's avatar
Thomas White committed
449
		{"output",             1, NULL,               'o'},
Thomas White's avatar
Thomas White committed
450
		{"max-only",           0, &config_maxonly,     1},
Thomas White's avatar
Thomas White committed
451
		{"output-every",       1, NULL,               'e'},
Thomas White's avatar
Thomas White committed
452
		{"stop-after",         1, NULL,               's'},
453
		{"start-after",        1, NULL,               'f'},
454
		{"sum",                0, &config_sum,         1},
455
		{"scale",              0, &config_scale,       1},
456
		{"symmetry",           1, NULL,               'y'},
457
		{"histogram",          1, NULL,               'g'},
458
		{"hist-parameters",    1, NULL,               'z'},
459
460
461
462
		{0, 0, NULL, 0}
	};

	/* Short options */
463
	while ((c = getopt_long(argc, argv, "hi:e:o:p:y:g:f:b:z:",
464
	                        longopts, NULL)) != -1) {
465
466

		switch (c) {
Thomas White's avatar
Thomas White committed
467
		case 'h' :
468
469
470
			show_help(argv[0]);
			return 0;

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

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

Thomas White's avatar
Thomas White committed
479
		case 's' :
Thomas White's avatar
Thomas White committed
480
481
482
			config_stopafter = atoi(optarg);
			break;

483
484
485
486
		case 'f' :
			config_startafter = atoi(optarg);
			break;

Thomas White's avatar
Thomas White committed
487
		case 'p' :
488
489
490
			pdb = strdup(optarg);
			break;

491
		case 'y' :
Thomas White's avatar
Thomas White committed
492
			sym_str = strdup(optarg);
493
494
			break;

495
496
497
498
		case 'g' :
			histo = strdup(optarg);
			break;

499
500
501
502
		case 'z' :
			histo_params = strdup(optarg);
			break;

Thomas White's avatar
Thomas White committed
503
		case 0 :
504
505
			break;

Thomas White's avatar
Thomas White committed
506
		default :
507
508
509
510
511
512
513
514
515
516
			return 1;
		}

	}

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

517
518
519
520
	if ( output == NULL ) {
		output = strdup("processed.hkl");
	}

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
	if ( histo != NULL ) {
Thomas White's avatar
Thomas White committed
549

550
		int r;
Thomas White's avatar
Thomas White committed
551

552
553
554
555
556
		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
557

Thomas White's avatar
Thomas White committed
558
		space_for_hist = n_total_patterns * num_equivs(sym, NULL);
559
560
561
		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
562

563
		/* Put into the asymmetric cell for the target group */
Thomas White's avatar
Thomas White committed
564
565
		get_asymm(sym, hist_h, hist_k, hist_l,
		          &hist_h, &hist_k, &hist_l);
566
		STATUS("%i %i %i\n", hist_h, hist_k, hist_l);
Thomas White's avatar
Thomas White committed
567

568
569
	}

570
	if ( histo_params != NULL ) {
Thomas White's avatar
Thomas White committed
571

572
		int rr;
Thomas White's avatar
Thomas White committed
573
574
575

		rr = sscanf(histo_params, "%f,%f,%i", &hist_min, &hist_max,
		                                      &hist_nbins);
576
577
578
579
580
		if ( rr != 3 ) {
			ERROR("Invalid parameters for '--hist-parameters'\n");
			return 1;
		}
		free(histo_params);
Thomas White's avatar
Thomas White committed
581
582
583
		if ( hist_max <= hist_min ) {
			ERROR("Invalid range for '--hist-parameters'. "
			      "Make sure that 'max' is greater than 'min'.\n");
584
585
			return 1;
		}
Thomas White's avatar
Thomas White committed
586

587
588
	}

589
	hist_i = 0;
590
	merge_all(fh, model, config_maxonly, config_scale, config_sum,
591
	          config_startafter, config_stopafter,
592
                  sym, n_total_patterns,
593
                  NULL, 0, 0, 0, NULL, 1);
Thomas White's avatar
Thomas White committed
594
595
596
597
	if ( ferror(fh) ) {
		ERROR("Stream read error.\n");
		return 1;
	}
598
	rewind(fh);
599

600
601
	STATUS("Extra pass to calculate ESDs...\n");
	rewind(fh);
602
603
	merge_all(fh, model, config_maxonly, config_scale, 0,
	          config_startafter, config_stopafter, sym, n_total_patterns,
604
	          hist_vals, hist_h, hist_k, hist_l, &hist_i, 2);
Thomas White's avatar
Thomas White committed
605
606
607
608
	if ( ferror(fh) ) {
		ERROR("Stream read error.\n");
		return 1;
	}
609

610
611
612
613
614
615
616
617
618
619
620
	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);
	}

621
	write_reflist(output, model, NULL);
622
623

	fclose(fh);
624

625
	free(sym);
626
	reflist_free(model);
Thomas White's avatar
Thomas White committed
627
	free(output);
628

629
630
	return 0;
}