process_hkl.c 12.7 KB
Newer Older
1
2
3
4
5
/*
 * process_hkl.c
 *
 * Assemble and process FEL Bragg intensities
 *
6
7
 * Copyright © 2012 Deutsches Elektronen-Synchrotron DESY,
 *                  a research centre of the Helmholtz Association.
8
 * Copyright © 2012 Lorenzo Galli
9
10
11
 *
 * Authors:
 *   2009-2012 Thomas White <taw@physics.org>
12
13
 *   2011      Andrew Martin <andrew.martin@desy.de>
 *   2012      Lorenzo Galli <lorenzo.galli@desy.de>
14
 *
Thomas White's avatar
Thomas White committed
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 * 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/>.
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
 *
 */


#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"
46
#include "reflist-utils.h"
47
#include "symmetry.h"
48
#include "stream.h"
49
50
#include "reflist.h"
#include "image.h"
51
52
53
54
55


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


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

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

96
97
98
99
100
101
102
103
	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;
104
	}
Thomas White's avatar
Thomas White committed
105
	STATUS("min max nbins: %f %f %i\n", min, max, nbins);
106
	min--;  max++;
107

108
	for ( i=0; i<nbins; i++ ) {
109
110
111
		histo[i] = 0;
	}

112
	step = (max-min)/nbins;
113
114
115

	for ( i=0; i<n; i++ ) {
		int bin;
116
117
118
119
		if ( (vals[i] > min) && (vals[i] < max) ) {
			bin = (vals[i]-min)/step;
			histo[bin]++;
		}
120
121
	}

122
	for ( i=0; i<nbins; i++ ) {
123
124
125
126
127
128
129
		fprintf(fh, "%f %i\n", min+step*i, histo[i]);
	}

	fclose(fh);
}


130
131
static double scale_intensities(RefList *reference, RefList *new,
                              const SymOpList *sym)
132
{
133
134
135
	double s;
	double top = 0.0;
	double bot = 0.0;
136
137
	Reflection *refl;
	RefListIterator *iter;
138

139
140
	for ( refl = first_refl(new, &iter);
	      refl != NULL;
141
142
	      refl = next_refl(refl, iter) )
	{
143

144
145
		double i1, i2;
		signed int hu, ku, lu;
146
		signed int h, k, l;
147
		Reflection *reference_version;
148

149
		get_indices(refl, &h, &k, &l);
150
		get_asymm(sym, h, k, l, &hu, &ku, &lu);
Thomas White's avatar
Thomas White committed
151

152
153
		reference_version = find_refl(reference, hu, ku, lu);
		if ( reference_version == NULL ) continue;
154

155
156
		i1 = get_intensity(reference_version);
		i2 = get_intensity(refl);
157

158
159
160
		/* Calculate LSQ estimate of scaling factor */
		top += i1 * i2;
		bot += i2 * i2;
161

162
	}
163

164
	s = top / bot;
165

166
	return s;
167
168
169
}


170
171
172
173
static int merge_pattern(RefList *model, struct image *new, RefList *reference,
                         const SymOpList *sym,
                         double *hist_vals, signed int hist_h,
                         signed int hist_k, signed int hist_l, int *hist_n)
174
{
175
176
	Reflection *refl;
	RefListIterator *iter;
177
178
179
180
	double scale;
	double asx, asy, asz;
	double bsx, bsy, bsz;
	double csx, csy, csz;
181

182
183
184
185
186
187
	if ( reference != NULL ) {
		scale = scale_intensities(reference, new->reflections, sym);
	} else {
		scale = 1.0;
	}
	if ( isnan(scale) ) return 1;
188

189
190
191
192
193
194
195
196
197
198
199
	cell_get_reciprocal(new->indexed_cell, &asx, &asy, &asz,
	                                       &bsx, &bsy, &bsz,
	                                       &csx, &csy, &csz);

	for ( refl = first_refl(new->reflections, &iter);
	      refl != NULL;
	      refl = next_refl(refl, iter) )
	{
		double intensity;
		double xl, yl, zl;
		double pol, pa, pb, phi, tt, ool;
200
		signed int h, k, l;
201
202
203
		int cur_redundancy;
		double cur_intensity, cur_sumsq;
		Reflection *model_version;
204

205
		get_indices(refl, &h, &k, &l);
206

207
208
		/* Put into the asymmetric unit for the target group */
		get_asymm(sym, h, k, l, &h, &k, &l);
209

210
211
212
213
		model_version = find_refl(model, h, k, l);
		if ( model_version == NULL ) {
			model_version = add_refl(model, h, k, l);
		}
214

215
		intensity = scale * get_intensity(refl);
216

217
218
219
220
221
		/* Polarisation correction assuming 100% polarisation along the
		 * x direction */
		xl = h*asx + k*bsx + l*csx;
		yl = h*asy + k*bsy + l*csy;
		zl = h*asz + k*bsz + l*csz;
222

223
224
225
226
227
228
229
		ool = 1.0 / new->lambda;
		tt = angle_between(0.0, 0.0, 1.0,  xl, yl, zl+ool);
		phi = atan2(yl, xl);
		pa = pow(sin(phi)*sin(tt), 2.0);
		pb = pow(cos(tt), 2.0);
		pol = 1.0 - 2.0*(1.0-pa) + (1.0+pb);
		intensity /= pol;
230

231
232
		cur_intensity = get_intensity(model_version);
		set_intensity(model_version, cur_intensity + intensity);
233

234
235
		cur_redundancy = get_redundancy(model_version);
		set_redundancy(model_version, cur_redundancy+1);
236

237
238
		cur_sumsq = get_temp1(model_version);
		set_temp1(model_version, cur_sumsq + pow(intensity, 2.0));
Thomas White's avatar
Thomas White committed
239

240
		if ( hist_vals != NULL ) {
Thomas White's avatar
Thomas White committed
241

242
243
244
245
			if ( (h==hist_h) && (k==hist_k) && (l==hist_l) ) {
				hist_vals[*hist_n] = intensity;
				*hist_n += 1;
			}
Thomas White's avatar
Thomas White committed
246

247
		}
Thomas White's avatar
Thomas White committed
248

249
	}
250

251
	return 0;
252
253
254
}


255
static void merge_all(FILE *fh, RefList *model, RefList *reference,
256
                      int config_startafter, int config_stopafter,
Thomas White's avatar
Thomas White committed
257
                      const SymOpList *sym,
258
                      int n_total_patterns,
259
260
                      double *hist_vals, signed int hist_h,
                      signed int hist_k, signed int hist_l,
261
                      int *hist_i)
262
{
263
	int rval;
Thomas White's avatar
Thomas White committed
264
	int n_patterns = 0;
265
266
267
	int n_used = 0;
	Reflection *refl;
	RefListIterator *iter;
268

269
270
271
	if ( skip_some_files(fh, config_startafter) ) {
		ERROR("Failed to skip first %i files.\n", config_startafter);
		return;
272
273
	}

274
275
	do {

276
		struct image image;
277

278
279
		image.det = NULL;

280
281
		/* Get data from next chunk */
		rval = read_chunk(fh, &image);
Thomas White's avatar
Thomas White committed
282
		if ( rval ) break;
283

284
285
286
		n_patterns++;

		if ( (image.reflections != NULL) && (image.indexed_cell) ) {
287

288
			int r;
289

290
291
292
			r = merge_pattern(model, &image, reference, sym,
			                  hist_vals, hist_h, hist_k, hist_l,
			                  hist_i);
293

294
			if ( r == 0 ) n_used++;
295
296
297

		}

Thomas White's avatar
Thomas White committed
298
		free(image.filename);
299
300
301
		reflist_free(image.reflections);
		image_feature_list_free(image.features);
		cell_free(image.indexed_cell);
302

303
304
		progress_bar(n_patterns, n_total_patterns-config_startafter,
		             "Merging");
305

306
	} while ( rval == 0 );
307

308
309
310
311
312
313
314
315
316
317
318
	for ( refl = first_refl(model, &iter);
	      refl != NULL;
	      refl = next_refl(refl, iter) )
	{
		double intensity, sumsq, esd;
		int red;

		red = get_redundancy(refl);
		if ( red == 1 ) {
			set_redundancy(refl, 0);
			continue;
Thomas White's avatar
Thomas White committed
319
		}
320

321
322
		intensity = get_intensity(refl) / red;
		set_intensity(refl, intensity);
Thomas White's avatar
Thomas White committed
323

324
325
326
		sumsq = get_temp1(refl) / red;
		esd = sqrt(sumsq - pow(intensity, 2.0)) / sqrt(red);
		set_esd_intensity(refl, esd);
327

328
	}
Thomas White's avatar
Thomas White committed
329

330
	STATUS("%i of the patterns could be used.\n", n_used);
331
332
333
}


334
335
336
337
int main(int argc, char *argv[])
{
	int c;
	char *filename = NULL;
338
	char *output = NULL;
339
	FILE *fh;
340
	RefList *model;
Thomas White's avatar
Thomas White committed
341
	int config_maxonly = 0;
342
	int config_startafter = 0;
Thomas White's avatar
Thomas White committed
343
	int config_stopafter = 0;
344
	int config_sum = 0;
345
	int config_scale = 0;
346
	unsigned int n_total_patterns;
Thomas White's avatar
Thomas White committed
347
348
	char *sym_str = NULL;
	SymOpList *sym;
349
	char *pdb = NULL;
350
351
	char *histo = NULL;
	signed int hist_h, hist_k, hist_l;
352
353
	signed int hist_nbins=50;
	float hist_min=0.0, hist_max=0.0;
354
355
	double *hist_vals = NULL;
	int hist_i;
356
	int space_for_hist = 0;
357
	char *histo_params = NULL;
358
359
360
361
362

	/* Long options */
	const struct option longopts[] = {
		{"help",               0, NULL,               'h'},
		{"input",              1, NULL,               'i'},
Thomas White's avatar
Thomas White committed
363
		{"output",             1, NULL,               'o'},
Thomas White's avatar
Thomas White committed
364
		{"max-only",           0, &config_maxonly,     1},
Thomas White's avatar
Thomas White committed
365
		{"output-every",       1, NULL,               'e'},
Thomas White's avatar
Thomas White committed
366
		{"stop-after",         1, NULL,               's'},
367
		{"start-after",        1, NULL,               'f'},
368
		{"sum",                0, &config_sum,         1},
369
		{"scale",              0, &config_scale,       1},
370
		{"symmetry",           1, NULL,               'y'},
371
		{"histogram",          1, NULL,               'g'},
372
		{"hist-parameters",    1, NULL,               'z'},
373
374
375
376
		{0, 0, NULL, 0}
	};

	/* Short options */
377
	while ((c = getopt_long(argc, argv, "hi:e:o:p:y:g:f:b:z:",
378
	                        longopts, NULL)) != -1) {
379
380

		switch (c) {
Thomas White's avatar
Thomas White committed
381
		case 'h' :
382
383
384
			show_help(argv[0]);
			return 0;

Thomas White's avatar
Thomas White committed
385
		case 'i' :
386
387
388
			filename = strdup(optarg);
			break;

Thomas White's avatar
Thomas White committed
389
		case 'o' :
390
391
392
			output = strdup(optarg);
			break;

Thomas White's avatar
Thomas White committed
393
		case 's' :
Thomas White's avatar
Thomas White committed
394
395
396
			config_stopafter = atoi(optarg);
			break;

397
398
399
400
		case 'f' :
			config_startafter = atoi(optarg);
			break;

Thomas White's avatar
Thomas White committed
401
		case 'p' :
402
403
404
			pdb = strdup(optarg);
			break;

405
		case 'y' :
Thomas White's avatar
Thomas White committed
406
			sym_str = strdup(optarg);
407
408
			break;

409
410
411
412
		case 'g' :
			histo = strdup(optarg);
			break;

413
414
415
416
		case 'z' :
			histo_params = strdup(optarg);
			break;

Thomas White's avatar
Thomas White committed
417
		case 0 :
418
419
			break;

Thomas White's avatar
Thomas White committed
420
		default :
421
422
423
424
425
426
427
428
429
430
			return 1;
		}

	}

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

431
432
433
434
	if ( output == NULL ) {
		output = strdup("processed.hkl");
	}

Thomas White's avatar
Thomas White committed
435
436
437
	if ( sym_str == NULL ) sym_str = strdup("1");
	sym = get_pointgroup(sym_str);
	free(sym_str);
438

439
440
441
442
443
444
445
446
447
448
449
	/* 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
450

451
452
	/* Count the number of patterns in the file */
	n_total_patterns = count_patterns(fh);
Thomas White's avatar
Thomas White committed
453
454
455
456
	if ( n_total_patterns == 0 ) {
		ERROR("No patterns to process.\n");
		return 1;
	}
457
458
	STATUS("There are %i patterns to process\n", n_total_patterns);
	rewind(fh);
459

460
461
	model = reflist_new();

462
	if ( histo != NULL ) {
Thomas White's avatar
Thomas White committed
463

464
		int r;
Thomas White's avatar
Thomas White committed
465

466
467
468
469
470
		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
471

Thomas White's avatar
Thomas White committed
472
		space_for_hist = n_total_patterns * num_equivs(sym, NULL);
473
474
475
		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
476

477
		/* Put into the asymmetric cell for the target group */
Thomas White's avatar
Thomas White committed
478
479
		get_asymm(sym, hist_h, hist_k, hist_l,
		          &hist_h, &hist_k, &hist_l);
480
		STATUS("%i %i %i\n", hist_h, hist_k, hist_l);
Thomas White's avatar
Thomas White committed
481

482
483
	}

484
	if ( histo_params != NULL ) {
Thomas White's avatar
Thomas White committed
485

486
		int rr;
Thomas White's avatar
Thomas White committed
487
488
489

		rr = sscanf(histo_params, "%f,%f,%i", &hist_min, &hist_max,
		                                      &hist_nbins);
490
491
492
493
494
		if ( rr != 3 ) {
			ERROR("Invalid parameters for '--hist-parameters'\n");
			return 1;
		}
		free(histo_params);
Thomas White's avatar
Thomas White committed
495
496
497
		if ( hist_max <= hist_min ) {
			ERROR("Invalid range for '--hist-parameters'. "
			      "Make sure that 'max' is greater than 'min'.\n");
498
499
			return 1;
		}
Thomas White's avatar
Thomas White committed
500

501
502
	}

503
	hist_i = 0;
504
	merge_all(fh, model, NULL, config_startafter, config_stopafter,
505
506
		  sym, n_total_patterns, hist_vals, hist_h, hist_k, hist_l,
		  &hist_i);
Thomas White's avatar
Thomas White committed
507
508
509
510
	if ( ferror(fh) ) {
		ERROR("Stream read error.\n");
		return 1;
	}
511
	rewind(fh);
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
	if ( config_scale ) {

		RefList *reference;

		STATUS("Extra pass for scaling...\n");

		reference = copy_reflist(model);

		reflist_free(model);
		model = reflist_new();

		rewind(fh);

		merge_all(fh, model, reference,
			  config_startafter, config_stopafter, sym,
			  n_total_patterns,
			  hist_vals, hist_h, hist_k, hist_l, &hist_i);

		if ( ferror(fh) ) {
			ERROR("Stream read error.\n");
			return 1;
		}

		reflist_free(reference);

Thomas White's avatar
Thomas White committed
538
	}
539

540
541
542
543
544
545
546
547
548
549
550
	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);
	}

551
	write_reflist(output, model);
552
553

	fclose(fh);
554

555
	free(sym);
556
	reflist_free(model);
Thomas White's avatar
Thomas White committed
557
	free(output);
558

559
560
	return 0;
}