facetron.c 12.2 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;
Thomas White's avatar
Thomas White committed
74
75
76
77
78
79
80
};


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

	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;
	}

104
	spots = find_intersections(image, image->indexed_cell, &n, 0, NULL);
105
106
107
108
	dev = +INFINITY;
	i = 0;
	do {
		last_dev = dev;
109
		dev = pr_iterate(image, pargs->i_full, pargs->sym, &spots, &n);
110
		STATUS("Iteration %2i: mean dev = %5.2f\n", i, dev);
111
		i++;
112
	} while ( (fabs(last_dev - dev) > 1.0) && (i < MAX_CYCLES) );
113
114
	mean_partial_dev(image, spots, n, pargs->sym,
	                 pargs->i_full, pargs->graph);
115
116
117
118

	free(image->data);
	if ( image->flags != NULL ) free(image->flags);
	hdfile_close(hdfile);
119
	free(spots);
120
121
122
123

	/* Muppet proofing */
	image->data = NULL;
	image->flags = NULL;
124
125
126
}


Thomas White's avatar
Thomas White committed
127
struct integrate_args
128
{
Thomas White's avatar
Thomas White committed
129
130
131
132
133
134
135
136
137
138
139
140
141
	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
142
	struct cpeak *spots;
143
144
145
	int j, n;
	struct hdfile *hdfile;
	struct image *image = pargs->image;
Thomas White's avatar
Thomas White committed
146
	double nominal_photon_energy = pargs->image->beam->photon_energy;
147

148
149
150
151
152
153
154
155
156
157
	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
158
	if ( hdf5_read(hdfile, pargs->image, 0, nominal_photon_energy) ) {
159
160
161
162
163
		ERROR("Couldn't read '%s'\n", image->filename);
		hdfile_close(hdfile);
		return;
	}

Thomas White's avatar
Thomas White committed
164
	/* Figure out which spots should appear in this pattern */
165
	spots = find_intersections(image, image->indexed_cell, &n, 0, NULL);
166
167
168
169
170

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

		signed int h, k, l;
171
		signed int ha, ka, la;
172
173
		float i_partial;
		float xc, yc;
Thomas White's avatar
Thomas White committed
174
		float i_full_est;
175
176
177
178
179
180
181

		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
182
		if ( spots[j].p < 0.1 ) continue;
183
184
185
186
187

		/* 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
188
189
190
		                    &xc, &yc, &i_partial, NULL, NULL, 1, 1) ) {
			continue;
		}
191
		i_partial *= image->osf;
192

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

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

197
		pthread_mutex_lock(pargs->list_lock);
198
199
200
201
		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);
202
203
204
205
206
		}
		pthread_mutex_unlock(pargs->list_lock);

	}

207
208
	free(image->data);
	if ( image->flags != NULL ) free(image->flags);
209
	hdfile_close(hdfile);
Thomas White's avatar
Thomas White committed
210
211
212
213
214
	free(spots);

	/* Muppet proofing */
	image->data = NULL;
	image->flags = NULL;
Thomas White's avatar
Thomas White committed
215
216
217
}


Thomas White's avatar
Thomas White committed
218
219
static void refine_all(struct image *images, int n_total_patterns,
                       struct detector *det, const char *sym,
220
221
                       ReflItemList *obs, double *i_full, int nthreads,
                       FILE *graph)
Thomas White's avatar
Thomas White committed
222
{
Thomas White's avatar
Thomas White committed
223
	struct refine_args *tasks;
Thomas White's avatar
Thomas White committed
224
	int i;
225

Thomas White's avatar
Thomas White committed
226
227
	tasks = malloc(n_total_patterns * sizeof(struct refine_args));
	for ( i=0; i<n_total_patterns; i++ ) {
Thomas White's avatar
Thomas White committed
228

Thomas White's avatar
Thomas White committed
229
230
231
232
		tasks[i].sym = sym;
		tasks[i].obs = obs;
		tasks[i].i_full = i_full;
		tasks[i].image = &images[i];
233
		tasks[i].graph = graph;
Thomas White's avatar
Thomas White committed
234
235
236

	}

237
238
	run_thread_range(n_total_patterns, nthreads, "Refining",
	                 refine_image, tasks);
Thomas White's avatar
Thomas White committed
239

Thomas White's avatar
Thomas White committed
240
	free(tasks);
241
242
243
244
245
}


static void estimate_full(struct image *images, int n_total_patterns,
                          struct detector *det, const char *sym,
Thomas White's avatar
Thomas White committed
246
247
                          ReflItemList *obs, double *i_full, unsigned int *cts,
                          int nthreads)
248
249
{
	int i;
Thomas White's avatar
Thomas White committed
250
251
	struct integrate_args *tasks;
	pthread_mutex_t list_lock = PTHREAD_MUTEX_INITIALIZER;
252

253
	clear_items(obs);
254
	memset(i_full, 0, LIST_SIZE*sizeof(double));
255

Thomas White's avatar
Thomas White committed
256
257
258
259
260
261
262
263
264
265
266
267
	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];

	}

268
269
	run_thread_range(n_total_patterns, nthreads, "Integrating",
	                 integrate_image, tasks);
Thomas White's avatar
Thomas White committed
270
271

	free(tasks);
272

273
274
	/* Divide the totals to get the means */
	for ( i=0; i<num_items(obs); i++ ) {
275

276
277
		struct refl_item *it;
		double total;
278

279
280
281
282
		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);
283

284
	}
Thomas White's avatar
Thomas White committed
285
}
286

Thomas White's avatar
Thomas White committed
287

Thomas White's avatar
Thomas White committed
288
289
290
291
int main(int argc, char *argv[])
{
	int c;
	char *infile = NULL;
Thomas White's avatar
Thomas White committed
292
	char *outfile = NULL;
Thomas White's avatar
Thomas White committed
293
294
	char *geomfile = NULL;
	char *prefix = NULL;
Thomas White's avatar
Thomas White committed
295
296
	char *sym = NULL;
	FILE *fh;
Thomas White's avatar
Thomas White committed
297
298
299
300
	int nthreads = 1;
	int config_basename = 0;
	int config_checkprefix = 1;
	struct detector *det;
Thomas White's avatar
Thomas White committed
301
	double *i_full;
Thomas White's avatar
Thomas White committed
302
	unsigned int *cts;
Thomas White's avatar
Thomas White committed
303
304
305
	ReflItemList *obs;
	int i;
	int n_total_patterns;
306
307
	struct image *images;
	int n_iter = 10;
Thomas White's avatar
Thomas White committed
308
	struct beam_params *beam = NULL;
Thomas White's avatar
Thomas White committed
309
310
311
312
313

	/* Long options */
	const struct option longopts[] = {
		{"help",               0, NULL,               'h'},
		{"input",              1, NULL,               'i'},
Thomas White's avatar
Thomas White committed
314
		{"output",             1, NULL,               'o'},
Thomas White's avatar
Thomas White committed
315
		{"geometry",           1, NULL,               'g'},
Thomas White's avatar
Thomas White committed
316
		{"beam",               1, NULL,               'b'},
Thomas White's avatar
Thomas White committed
317
318
319
		{"prefix",             1, NULL,               'x'},
		{"basename",           0, &config_basename,    1},
		{"no-check-prefix",    0, &config_checkprefix, 0},
320
		{"symmetry",           1, NULL,               'y'},
321
		{"iterations",         1, NULL,               'n'},
Thomas White's avatar
Thomas White committed
322
323
324
325
		{0, 0, NULL, 0}
	};

	/* Short options */
Thomas White's avatar
Thomas White committed
326
	while ((c = getopt_long(argc, argv, "hi:g:x:j:y:o:b:",
327
328
	                        longopts, NULL)) != -1)
	{
Thomas White's avatar
Thomas White committed
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350

		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;

351
352
353
354
		case 'y' :
			sym = strdup(optarg);
			break;

Thomas White's avatar
Thomas White committed
355
356
357
358
		case 'o' :
			outfile = strdup(optarg);
			break;

359
360
361
362
		case 'n' :
			n_iter = atoi(optarg);
			break;

Thomas White's avatar
Thomas White committed
363
364
365
366
367
368
369
370
371
		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
372
373
374
375
376
377
378
379
380
		case 0 :
			break;

		default :
			return 1;
		}

	}

Thomas White's avatar
Thomas White committed
381
	/* Sanitise input filename and open */
Thomas White's avatar
Thomas White committed
382
383
384
385
386
387
388
389
390
391
392
393
394
395
	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
396
397
398
399
400
401
	/* Sanitise output filename */
	if ( outfile == NULL ) {
		outfile = strdup("facetron.hkl");
	}

	/* Sanitise prefix */
Thomas White's avatar
Thomas White committed
402
403
404
405
406
407
408
409
	if ( prefix == NULL ) {
		prefix = strdup("");
	} else {
		if ( config_checkprefix ) {
			prefix = check_prefix(prefix);
		}
	}

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

Thomas White's avatar
Thomas White committed
412
	/* Get detector geometry */
Thomas White's avatar
Thomas White committed
413
414
415
416
417
418
419
	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
420
421
422
423
424
	if ( beam == NULL ) {
		ERROR("You must provide a beam parameters file.\n");
		return 1;
	}

Thomas White's avatar
Thomas White committed
425
426
427
428
429
430
431
	/* 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);

432
433
434
435
436
437
438
439
440
441
442
443
	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;
444
		char *fnamereal;
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460

		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;
		}
461
		fnamereal = malloc(1024);
462
463
464
		snprintf(fnamereal, 1023, "%s%s", prefix, filename);

		images[i].filename = fnamereal;
Thomas White's avatar
Thomas White committed
465
466
		images[i].div = beam->divergence;
		images[i].bw = beam->bandwidth;
467
		images[i].det = det;
Thomas White's avatar
Thomas White committed
468
		images[i].beam = beam;
469
		images[i].osf = 1.0;
470
		images[i].profile_radius = 0.005e9;
471

Thomas White's avatar
Thomas White committed
472
473
474
475
		/* Muppet proofing */
		images[i].data = NULL;
		images[i].flags = NULL;

476
477
478
479
480
481
482
483
		free(filename);

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

	}
	fclose(fh);
	free(prefix);

Thomas White's avatar
Thomas White committed
484
485
	cts = new_list_count();

486
	/* Make initial estimates */
Thomas White's avatar
Thomas White committed
487
	estimate_full(images, n_total_patterns, det, sym, obs, i_full, cts,
488
	              nthreads);
489

Thomas White's avatar
Thomas White committed
490
	/* Iterate */
491
	for ( i=0; i<n_iter; i++ ) {
Thomas White's avatar
Thomas White committed
492

493
494
495
		FILE *fh;
		char filename[1024];

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

498
499
500
501
502
503
504
		snprintf(filename, 1023, "iteration-%i.dat", i+1);
		fh = fopen(filename, "w");
		if ( fh == NULL ) {
			ERROR("Failed to open '%s'\n", filename);
			/* Nothing will be written later */
		}

Thomas White's avatar
Thomas White committed
505
		/* Refine the geometry of all patterns to get the best fit */
506
		refine_all(images, n_total_patterns, det, sym, obs, i_full,
507
		           nthreads, fh);
Thomas White's avatar
Thomas White committed
508
509

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

513
		fclose(fh);
Thomas White's avatar
Thomas White committed
514
515
516
	}

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

Thomas White's avatar
Thomas White committed
519
520
521
	/* Clean up */
	free(i_full);
	delete_items(obs);
Thomas White's avatar
Thomas White committed
522
	free(sym);
Thomas White's avatar
Thomas White committed
523
	free(outfile);
524
525
	free(det->panels);
	free(det);
526
	free(beam);
Thomas White's avatar
Thomas White committed
527
	free(cts);
528
529
530
531
532
	for ( i=0; i<n_total_patterns; i++ ) {
		cell_free(images[i].indexed_cell);
		free(images[i].filename);
	}
	free(images);
533
534
535

	return 0;
}