facetron.c 12.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*
 * facetron.c
 *
 * Profile fitting for coherent nanocrystallography
 *
 * (c) 2006-2010 Thomas White <taw@physics.org>
 *
 * 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>
Thomas White's avatar
Thomas White committed
23
#include <assert.h>
Thomas White's avatar
Tidy up    
Thomas White committed
24
#include <pthread.h>
25

Thomas White's avatar
Thomas White committed
26
#include "utils.h"
27
#include "hdf5-file.h"
Thomas White's avatar
Thomas White committed
28
#include "symmetry.h"
Thomas White's avatar
Thomas White committed
29
30
#include "reflections.h"
#include "stream.h"
31
#include "geometry.h"
32
#include "peaks.h"
Thomas White's avatar
Thomas White committed
33
#include "thread-pool.h"
Thomas White's avatar
Thomas White committed
34
#include "beam-parameters.h"
35
#include "post-refinement.h"
36
37


38
39
/* Maximum number of iterations of NLSq to do for each image per macrocycle. */
#define MAX_CYCLES (100)
40

41

42
43
44
45
static void show_help(const char *s)
{
	printf("Syntax: %s [options]\n\n", s);
	printf(
Thomas White's avatar
Thomas White committed
46
"Post-refinement and profile fitting for coherent nanocrystallography.\n"
47
48
49
"\n"
"  -h, --help                 Display this help message.\n"
"\n"
Thomas White's avatar
Thomas White committed
50
51
"  -i, --input=<filename>     Specify the name of the input 'stream'.\n"
"                              (must be a file, not e.g. stdin)\n"
Thomas White's avatar
Thomas White committed
52
"  -o, --output=<filename>    Output filename.  Default: facetron.hkl.\n"
Thomas White's avatar
Thomas White committed
53
"  -g. --geometry=<file>      Get detector geometry from file.\n"
Thomas White's avatar
Thomas White committed
54
55
56
"  -b, --beam=<file>          Get beam parameters from file (provides initial\n"
"                              values for parameters, and nominal wavelengths\n"
"                              if no per-shot value is found in an HDF5 file.\n"
Thomas White's avatar
Thomas White committed
57
58
59
"  -x, --prefix=<p>           Prefix filenames from input file with <p>.\n"
"      --basename             Remove the directory parts of the filenames.\n"
"      --no-check-prefix      Don't attempt to correct the --prefix.\n"
60
61
62
"  -y, --symmetry=<sym>       Merge according to symmetry <sym>.\n"
"  -n, --iterations=<n>       Run <n> cycles of post-refinement.\n"
"\n"
Thomas White's avatar
Thomas White committed
63
64
65
66
"  -j <n>                     Run <n> analyses in parallel.\n");
}


Thomas White's avatar
Thomas White committed
67
struct refine_args
Thomas White's avatar
Thomas White committed
68
{
Thomas White's avatar
Thomas White committed
69
70
71
72
	const char *sym;
	ReflItemList *obs;
	double *i_full;
	struct image *image;
73
	FILE *graph;
74
	FILE *pgraph;
Thomas White's avatar
Thomas White committed
75
76
77
78
79
80
81
};


static void refine_image(int mytask, void *tasks)
{
	struct refine_args *all_args = tasks;
	struct refine_args *pargs = &all_args[mytask];
82
83
84
85
	struct image *image = pargs->image;
	double nominal_photon_energy = pargs->image->beam->photon_energy;
	struct hdfile *hdfile;
	struct cpeak *spots;
86
	int n, i;
87
	double dev, last_dev;
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104

	hdfile = hdfile_open(image->filename);
	if ( hdfile == NULL ) {
		ERROR("Couldn't open '%s'\n", image->filename);
		return;
	} else if ( hdfile_set_image(hdfile, "/data/data0") ) {
		ERROR("Couldn't select path\n");
		hdfile_close(hdfile);
		return;
	}

	if ( hdf5_read(hdfile, pargs->image, 0, nominal_photon_energy) ) {
		ERROR("Couldn't read '%s'\n", image->filename);
		hdfile_close(hdfile);
		return;
	}

Thomas White's avatar
Thomas White committed
105
106
107
108
109
110
	double a, b, c, al, be, ga;
	cell_get_parameters(image->indexed_cell, &a, &b, &c, &al, &be, &ga);
	STATUS("Initial cell: %5.2f %5.2f %5.2f nm %5.2f %5.2f %5.2f deg\n",
	       a/1.0e-9, b/1.0e-9, c/1.0e-9,
	       rad2deg(al), rad2deg(be), rad2deg(ga));

111
	spots = find_intersections(image, image->indexed_cell, &n, 0);
112
113
114
115
	dev = +INFINITY;
	i = 0;
	do {
		last_dev = dev;
116
		dev = pr_iterate(image, pargs->i_full, pargs->sym, &spots, &n);
117
		STATUS("Iteration %2i: mean dev = %5.2f\n", i, dev);
118
		i++;
119
	} while ( (fabs(last_dev - dev) > 1.0) && (i < MAX_CYCLES) );
120
121
	mean_partial_dev(image, spots, n, pargs->sym,
	                 pargs->i_full, pargs->graph);
122
123
124
	if ( pargs->pgraph ) {
		fprintf(pargs->pgraph, "%5i %5.2f\n", mytask, dev);
	}
125
126
127
128

	free(image->data);
	if ( image->flags != NULL ) free(image->flags);
	hdfile_close(hdfile);
129
	free(spots);
130
131
132
133

	/* Muppet proofing */
	image->data = NULL;
	image->flags = NULL;
134
135
136
}


Thomas White's avatar
Thomas White committed
137
struct integrate_args
138
{
Thomas White's avatar
Thomas White committed
139
140
141
142
143
144
145
146
147
148
149
150
151
	const char *sym;
	ReflItemList *obs;
	double *i_full;
	unsigned int *cts;
	pthread_mutex_t *list_lock;
	struct image *image;
};


static void integrate_image(int mytask, void *tasks)
{
	struct integrate_args *all_args = tasks;
	struct integrate_args *pargs = &all_args[mytask];
Thomas White's avatar
Thomas White committed
152
	struct cpeak *spots;
153
154
155
	int j, n;
	struct hdfile *hdfile;
	struct image *image = pargs->image;
Thomas White's avatar
Thomas White committed
156
	double nominal_photon_energy = pargs->image->beam->photon_energy;
157

158
159
160
161
162
163
164
165
166
167
	hdfile = hdfile_open(image->filename);
	if ( hdfile == NULL ) {
		ERROR("Couldn't open '%s'\n", image->filename);
		return;
	} else if ( hdfile_set_image(hdfile, "/data/data0") ) {
		ERROR("Couldn't select path\n");
		hdfile_close(hdfile);
		return;
	}

Thomas White's avatar
Thomas White committed
168
	if ( hdf5_read(hdfile, pargs->image, 0, nominal_photon_energy) ) {
169
170
171
172
173
		ERROR("Couldn't read '%s'\n", image->filename);
		hdfile_close(hdfile);
		return;
	}

Thomas White's avatar
Thomas White committed
174
	/* Figure out which spots should appear in this pattern */
175
	spots = find_intersections(image, image->indexed_cell, &n, 0);
176
177
178
179
180

	/* For each reflection, estimate the partiality */
	for ( j=0; j<n; j++ ) {

		signed int h, k, l;
181
		signed int ha, ka, la;
182
183
		float i_partial;
		float xc, yc;
Thomas White's avatar
Thomas White committed
184
		float i_full_est;
185
186
187
188
189
190
191

		h = spots[j].h;
		k = spots[j].k;
		l = spots[j].l;

		/* Don't attempt to use spots with very small
		 * partialities, since it won't be accurate. */
Thomas White's avatar
Thomas White committed
192
		if ( spots[j].p < 0.1 ) continue;
193
194
195
196
197

		/* Actual measurement of this reflection from this
		 * pattern? */
		/* FIXME: Coordinates aren't whole numbers */
		if ( integrate_peak(image, spots[j].x, spots[j].y,
Thomas White's avatar
Thomas White committed
198
199
200
		                    &xc, &yc, &i_partial, NULL, NULL, 1, 1) ) {
			continue;
		}
201
		i_partial *= image->osf;
202

Thomas White's avatar
Thomas White committed
203
		i_full_est = i_partial / spots[j].p;
Thomas White's avatar
Thomas White committed
204

205
206
		get_asymm(h, k, l, &ha, &ka, &la, pargs->sym);

207
		pthread_mutex_lock(pargs->list_lock);
208
209
210
211
		integrate_intensity(pargs->i_full, ha, ka, la, i_full_est);
		integrate_count(pargs->cts, ha, ka, la, 1);
		if ( !find_item(pargs->obs, ha, ka, la) ) {
			add_item(pargs->obs, ha, ka, la);
212
213
214
215
216
		}
		pthread_mutex_unlock(pargs->list_lock);

	}

217
218
	free(image->data);
	if ( image->flags != NULL ) free(image->flags);
219
	hdfile_close(hdfile);
Thomas White's avatar
Thomas White committed
220
221
222
223
224
	free(spots);

	/* Muppet proofing */
	image->data = NULL;
	image->flags = NULL;
Thomas White's avatar
Thomas White committed
225
226
227
}


Thomas White's avatar
Thomas White committed
228
229
static void refine_all(struct image *images, int n_total_patterns,
                       struct detector *det, const char *sym,
230
                       ReflItemList *obs, double *i_full, int nthreads,
231
                       FILE *graph, FILE *pgraph)
Thomas White's avatar
Thomas White committed
232
{
Thomas White's avatar
Thomas White committed
233
	struct refine_args *tasks;
Thomas White's avatar
Thomas White committed
234
	int i;
235

Thomas White's avatar
Thomas White committed
236
237
	tasks = malloc(n_total_patterns * sizeof(struct refine_args));
	for ( i=0; i<n_total_patterns; i++ ) {
Thomas White's avatar
Thomas White committed
238

Thomas White's avatar
Thomas White committed
239
240
241
242
		tasks[i].sym = sym;
		tasks[i].obs = obs;
		tasks[i].i_full = i_full;
		tasks[i].image = &images[i];
243
		tasks[i].graph = graph;
244
		tasks[i].pgraph = pgraph;
Thomas White's avatar
Thomas White committed
245
246
247

	}

248
249
	run_thread_range(n_total_patterns, nthreads, "Refining",
	                 refine_image, tasks);
Thomas White's avatar
Thomas White committed
250

Thomas White's avatar
Thomas White committed
251
	free(tasks);
252
253
254
255
256
}


static void estimate_full(struct image *images, int n_total_patterns,
                          struct detector *det, const char *sym,
Thomas White's avatar
Thomas White committed
257
258
                          ReflItemList *obs, double *i_full, unsigned int *cts,
                          int nthreads)
259
260
{
	int i;
Thomas White's avatar
Thomas White committed
261
262
	struct integrate_args *tasks;
	pthread_mutex_t list_lock = PTHREAD_MUTEX_INITIALIZER;
263

264
	clear_items(obs);
265
	memset(i_full, 0, LIST_SIZE*sizeof(double));
266
	memset(cts, 0, LIST_SIZE*sizeof(unsigned int));
267

Thomas White's avatar
Thomas White committed
268
269
270
271
272
273
274
275
276
277
278
279
	tasks = malloc(n_total_patterns * sizeof(struct integrate_args));
	for ( i=0; i<n_total_patterns; i++ ) {

		tasks[i].sym = sym;
		tasks[i].obs = obs;
		tasks[i].i_full = i_full;
		tasks[i].cts = cts;
		tasks[i].list_lock = &list_lock;
		tasks[i].image = &images[i];

	}

280
281
	run_thread_range(n_total_patterns, nthreads, "Integrating",
	                 integrate_image, tasks);
Thomas White's avatar
Thomas White committed
282
283

	free(tasks);
284

285
286
	/* Divide the totals to get the means */
	for ( i=0; i<num_items(obs); i++ ) {
287

288
289
		struct refl_item *it;
		double total;
290

291
292
293
294
		it = get_item(obs, i);
		total = lookup_intensity(i_full, it->h, it->k, it->l);
		total /= lookup_count(cts, it->h, it->k, it->l);
		set_intensity(i_full, it->h, it->k, it->l, total);
295

296
	}
Thomas White's avatar
Thomas White committed
297
}
298

Thomas White's avatar
Thomas White committed
299

Thomas White's avatar
Thomas White committed
300
301
302
303
int main(int argc, char *argv[])
{
	int c;
	char *infile = NULL;
Thomas White's avatar
Thomas White committed
304
	char *outfile = NULL;
Thomas White's avatar
Thomas White committed
305
306
	char *geomfile = NULL;
	char *prefix = NULL;
Thomas White's avatar
Thomas White committed
307
308
	char *sym = NULL;
	FILE *fh;
Thomas White's avatar
Thomas White committed
309
310
311
312
	int nthreads = 1;
	int config_basename = 0;
	int config_checkprefix = 1;
	struct detector *det;
Thomas White's avatar
Thomas White committed
313
	double *i_full;
Thomas White's avatar
Thomas White committed
314
	unsigned int *cts;
Thomas White's avatar
Thomas White committed
315
316
317
	ReflItemList *obs;
	int i;
	int n_total_patterns;
318
319
	struct image *images;
	int n_iter = 10;
Thomas White's avatar
Thomas White committed
320
	struct beam_params *beam = NULL;
Thomas White's avatar
Thomas White committed
321
322
323
324
325

	/* Long options */
	const struct option longopts[] = {
		{"help",               0, NULL,               'h'},
		{"input",              1, NULL,               'i'},
Thomas White's avatar
Thomas White committed
326
		{"output",             1, NULL,               'o'},
Thomas White's avatar
Thomas White committed
327
		{"geometry",           1, NULL,               'g'},
Thomas White's avatar
Thomas White committed
328
		{"beam",               1, NULL,               'b'},
Thomas White's avatar
Thomas White committed
329
330
331
		{"prefix",             1, NULL,               'x'},
		{"basename",           0, &config_basename,    1},
		{"no-check-prefix",    0, &config_checkprefix, 0},
332
		{"symmetry",           1, NULL,               'y'},
333
		{"iterations",         1, NULL,               'n'},
Thomas White's avatar
Thomas White committed
334
335
336
337
		{0, 0, NULL, 0}
	};

	/* Short options */
Thomas White's avatar
Thomas White committed
338
	while ((c = getopt_long(argc, argv, "hi:g:x:j:y:o:b:",
339
340
	                        longopts, NULL)) != -1)
	{
Thomas White's avatar
Thomas White committed
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362

		switch (c) {
		case 'h' :
			show_help(argv[0]);
			return 0;

		case 'i' :
			infile = strdup(optarg);
			break;

		case 'g' :
			geomfile = strdup(optarg);
			break;

		case 'x' :
			prefix = strdup(optarg);
			break;

		case 'j' :
			nthreads = atoi(optarg);
			break;

363
364
365
366
		case 'y' :
			sym = strdup(optarg);
			break;

Thomas White's avatar
Thomas White committed
367
368
369
370
		case 'o' :
			outfile = strdup(optarg);
			break;

371
372
373
374
		case 'n' :
			n_iter = atoi(optarg);
			break;

Thomas White's avatar
Thomas White committed
375
376
377
378
379
380
381
382
383
		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
384
385
386
387
388
389
390
391
392
		case 0 :
			break;

		default :
			return 1;
		}

	}

Thomas White's avatar
Thomas White committed
393
	/* Sanitise input filename and open */
Thomas White's avatar
Thomas White committed
394
395
396
397
398
399
400
401
402
403
404
405
406
407
	if ( infile == NULL ) {
		infile = strdup("-");
	}
	if ( strcmp(infile, "-") == 0 ) {
		fh = stdin;
	} else {
		fh = fopen(infile, "r");
	}
	if ( fh == NULL ) {
		ERROR("Failed to open input file '%s'\n", infile);
		return 1;
	}
	free(infile);

Thomas White's avatar
Thomas White committed
408
409
410
411
412
413
	/* Sanitise output filename */
	if ( outfile == NULL ) {
		outfile = strdup("facetron.hkl");
	}

	/* Sanitise prefix */
Thomas White's avatar
Thomas White committed
414
415
416
417
418
419
420
421
	if ( prefix == NULL ) {
		prefix = strdup("");
	} else {
		if ( config_checkprefix ) {
			prefix = check_prefix(prefix);
		}
	}

Thomas White's avatar
Thomas White committed
422
423
	if ( sym == NULL ) sym = strdup("1");

Thomas White's avatar
Thomas White committed
424
	/* Get detector geometry */
Thomas White's avatar
Thomas White committed
425
426
427
428
429
430
431
	det = get_detector_geometry(geomfile);
	if ( det == NULL ) {
		ERROR("Failed to read detector geometry from '%s'\n", geomfile);
		return 1;
	}
	free(geomfile);

Thomas White's avatar
Thomas White committed
432
433
434
435
436
	if ( beam == NULL ) {
		ERROR("You must provide a beam parameters file.\n");
		return 1;
	}

Thomas White's avatar
Thomas White committed
437
438
439
440
441
442
443
	/* Prepare for iteration */
	i_full = new_list_intensity();
	obs = new_items();

	n_total_patterns = count_patterns(fh);
	STATUS("There are %i patterns to process\n", n_total_patterns);

444
445
446
447
448
449
450
451
452
453
454
455
	images = malloc(n_total_patterns * sizeof(struct image));
	if ( images == NULL ) {
		ERROR("Couldn't allocate memory for images.\n");
		return 1;
	}

	/* Fill in what we know about the images so far */
	rewind(fh);
	for ( i=0; i<n_total_patterns; i++ ) {

		UnitCell *cell;
		char *filename;
456
		char *fnamereal;
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472

		if ( find_chunk(fh, &cell, &filename) == 1 ) {
			ERROR("Couldn't get all of the filenames and cells"
			      " from the input stream.\n");
			return 1;
		}

		images[i].indexed_cell = cell;

		/* Mangle the filename now */
		if ( config_basename ) {
			char *tmp;
			tmp = strdup(basename(filename));
			free(filename);
			filename = tmp;
		}
473
		fnamereal = malloc(1024);
474
475
476
		snprintf(fnamereal, 1023, "%s%s", prefix, filename);

		images[i].filename = fnamereal;
Thomas White's avatar
Thomas White committed
477
478
		images[i].div = beam->divergence;
		images[i].bw = beam->bandwidth;
479
		images[i].det = det;
Thomas White's avatar
Thomas White committed
480
		images[i].beam = beam;
481
		images[i].osf = 1.0;
482
		images[i].profile_radius = 0.005e9;
483

Thomas White's avatar
Thomas White committed
484
485
486
487
		/* Muppet proofing */
		images[i].data = NULL;
		images[i].flags = NULL;

488
489
490
491
492
493
494
495
		free(filename);

		progress_bar(i, n_total_patterns-1, "Loading pattern data");

	}
	fclose(fh);
	free(prefix);

Thomas White's avatar
Thomas White committed
496
497
	cts = new_list_count();

498
	/* Make initial estimates */
Thomas White's avatar
Thomas White committed
499
	estimate_full(images, n_total_patterns, det, sym, obs, i_full, cts,
500
	              nthreads);
501

Thomas White's avatar
Thomas White committed
502
	/* Iterate */
503
	for ( i=0; i<n_iter; i++ ) {
Thomas White's avatar
Thomas White committed
504

505
506
		FILE *fhg;
		FILE *fhp;
507
508
		char filename[1024];

509
		STATUS("Post refinement iteration %i of %i\n", i+1, n_iter);
Thomas White's avatar
Thomas White committed
510

511
512
513
514
515
516
517
518
519
520
		snprintf(filename, 1023, "p-iteration-%i.dat", i+1);
		fhg = fopen(filename, "w");
		if ( fhg == NULL ) {
			ERROR("Failed to open '%s'\n", filename);
			/* Nothing will be written later */
		}

		snprintf(filename, 1023, "g-iteration-%i.dat", i+1);
		fhp = fopen(filename, "w");
		if ( fhp == NULL ) {
521
522
523
524
			ERROR("Failed to open '%s'\n", filename);
			/* Nothing will be written later */
		}

Thomas White's avatar
Thomas White committed
525
		/* Refine the geometry of all patterns to get the best fit */
526
		refine_all(images, n_total_patterns, det, sym, obs, i_full,
527
		           nthreads, fhg, fhp);
Thomas White's avatar
Thomas White committed
528
529

		/* Re-estimate all the full intensities */
530
		estimate_full(images, n_total_patterns, det, sym, obs, i_full,
Thomas White's avatar
Thomas White committed
531
		              cts, nthreads);
Thomas White's avatar
Thomas White committed
532

533
534
		fclose(fhg);
		fclose(fhp);
Thomas White's avatar
Thomas White committed
535
536
537
	}

	/* Output results */
538
	write_reflections(outfile, obs, i_full, NULL, NULL, cts, NULL);
Thomas White's avatar
Thomas White committed
539

Thomas White's avatar
Thomas White committed
540
541
542
	/* Clean up */
	free(i_full);
	delete_items(obs);
Thomas White's avatar
Thomas White committed
543
	free(sym);
Thomas White's avatar
Thomas White committed
544
	free(outfile);
545
546
	free(det->panels);
	free(det);
547
	free(beam);
Thomas White's avatar
Thomas White committed
548
	free(cts);
549
550
551
552
553
	for ( i=0; i<n_total_patterns; i++ ) {
		cell_free(images[i].indexed_cell);
		free(images[i].filename);
	}
	free(images);
554
555
556

	return 0;
}