partialator.c 12.5 KB
Newer Older
1
/*
2
 * partialator.c
3
 *
4
 * Scaling and post refinement for coherent nanocrystallography
5
 *
Thomas White's avatar
Thomas White committed
6
 * (c) 2006-2011 Thomas White <taw@physics.org>
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 *
 * 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
#include <gsl/gsl_errno.h>
26

Thomas White's avatar
Thomas White committed
27
#include "utils.h"
28
#include "hdf5-file.h"
Thomas White's avatar
Thomas White committed
29
#include "symmetry.h"
Thomas White's avatar
Thomas White committed
30
#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
#include "hrs-scaling.h"
Thomas White's avatar
Thomas White committed
37
#include "reflist.h"
Thomas White's avatar
Thomas White committed
38
#include "reflist-utils.h"
39
40
41
42
43
44


static void show_help(const char *s)
{
	printf("Syntax: %s [options]\n\n", s);
	printf(
45
"Scaling and post refinement for coherent nanocrystallography.\n"
46
47
48
"\n"
"  -h, --help                 Display this help message.\n"
"\n"
Thomas White's avatar
Thomas White committed
49
50
"  -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
51
"  -o, --output=<filename>    Output filename.  Default: facetron.hkl.\n"
Thomas White's avatar
Thomas White committed
52
"  -g. --geometry=<file>      Get detector geometry from file.\n"
53
54
55
56
"  -b, --beam=<file>          Get beam parameters from file, which provides\n"
"                              initial values for parameters, and nominal\n"
"                              wavelengths if no per-shot value is found in \n"
"                              an HDF5 file.\n"
57
"  -y, --symmetry=<sym>       Merge according to symmetry <sym>.\n"
58
"  -n, --iterations=<n>       Run <n> cycles of scaling and post-refinement.\n"
59
60
61
"      --reference=<file>     Refine images against reflections in <file>,\n"
"                              instead of taking the mean of the intensity\n"
"                              estimates.\n"
62
"\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
{
69
	RefList *full;
Thomas White's avatar
Thomas White committed
70
	struct image *image;
71
	FILE *graph;
72
	FILE *pgraph;
Thomas White's avatar
Thomas White committed
73
74
75
};


Thomas White's avatar
Thomas White committed
76
struct queue_args
Thomas White's avatar
Thomas White committed
77
{
Thomas White's avatar
Thomas White committed
78
79
80
81
82
83
84
85
86
87
88
	int n;
	int n_done;
	int n_total_patterns;
	struct image *images;
	struct refine_args task_defaults;
};


static void refine_image(void *task, int id)
{
	struct refine_args *pargs = task;
89
	struct image *image = pargs->image;
Thomas White's avatar
Thomas White committed
90
	image->id = id;
91

92
	pr_refine(image, pargs->full);
93
94
95
}


Thomas White's avatar
Thomas White committed
96
static void *get_image(void *vqargs)
97
{
Thomas White's avatar
Thomas White committed
98
99
	struct refine_args *task;
	struct queue_args *qargs = vqargs;
Thomas White's avatar
Thomas White committed
100

Thomas White's avatar
Thomas White committed
101
102
	task = malloc(sizeof(struct refine_args));
	memcpy(task, &qargs->task_defaults, sizeof(struct refine_args));
103

Thomas White's avatar
Thomas White committed
104
	task->image = &qargs->images[qargs->n];
105

Thomas White's avatar
Thomas White committed
106
107
108
109
	qargs->n++;

	return task;
}
Thomas White's avatar
Thomas White committed
110

111

Thomas White's avatar
Thomas White committed
112
113
114
115
116
117
static void done_image(void *vqargs, void *task)
{
	struct queue_args *qargs = vqargs;

	qargs->n_done++;

Thomas White's avatar
Thomas White committed
118
	progress_bar(qargs->n_done, qargs->n_total_patterns, "Refining");
Thomas White's avatar
Thomas White committed
119
120
121
122
123
	free(task);
}


static void refine_all(struct image *images, int n_total_patterns,
124
125
                       struct detector *det,
                       RefList *full, int nthreads,
Thomas White's avatar
Thomas White committed
126
127
128
129
130
131
132
133
134
135
136
137
138
                       FILE *graph, FILE *pgraph)
{
	struct refine_args task_defaults;
	struct queue_args qargs;

	task_defaults.full = full;
	task_defaults.image = NULL;
	task_defaults.graph = graph;
	task_defaults.pgraph = pgraph;

	qargs.task_defaults = task_defaults;
	qargs.n = 0;
	qargs.n_done = 0;
Thomas White's avatar
Thomas White committed
139
140
	qargs.n_total_patterns = n_total_patterns;
	qargs.images = images;
Thomas White's avatar
Thomas White committed
141

Thomas White's avatar
Thomas White committed
142
	/* Don't have threads which are doing nothing */
Thomas White's avatar
Whoops    
Thomas White committed
143
	if ( n_total_patterns < nthreads ) nthreads = n_total_patterns;
Thomas White's avatar
Thomas White committed
144

Thomas White's avatar
Thomas White committed
145
	run_threads(nthreads, refine_image, get_image, done_image,
Thomas White's avatar
Thomas White committed
146
	            &qargs, n_total_patterns, 0, 0, 0);
147
148
149
}


150
/* Decide which reflections can be scaled */
151
static int select_scalable_reflections(RefList *list, RefList *reference)
152
153
154
155
156
157
158
159
160
{
	Reflection *refl;
	RefListIterator *iter;
	int nobs = 0;

	for ( refl = first_refl(list, &iter);
	      refl != NULL;
	      refl = next_refl(refl, iter) ) {

161
		int sc = 1;
162
163
		double v;

164
		if ( get_partiality(refl) < 0.1 ) sc = 0;
165
		v = fabs(get_intensity(refl));
166
		if ( v < 0.1 ) sc = 0;
167

168
169
170
		/* If we are scaling against a reference set, we additionally
		 * require that this reflection is in the reference list. */
		if ( reference != NULL ) {
171
172
			signed int h, k, l;
			get_indices(refl, &h, &k, &l);
173
			if ( find_refl(reference, h, k, l) == NULL ) sc = 0;
174
175
		}

176
177
178
		set_scalable(refl, sc);

		if ( sc ) nobs++;
179
180
181
182
183
184
	}

	return nobs;
}


185
static void select_reflections_for_refinement(struct image *images, int n,
186
                                              RefList *full, int have_reference)
187
188
189
190
191
192
193
{
	int i;

	for ( i=0; i<n; i++ ) {

		Reflection *refl;
		RefListIterator *iter;
194
195
196
197
198
		int n_acc = 0;
		int n_nomatch = 0;
		int n_noscale = 0;
		int n_fewmatch = 0;
		int n_ref = 0;
199
200
201
202
203
204
205
206

		for ( refl = first_refl(images[i].reflections, &iter);
		      refl != NULL;
		      refl = next_refl(refl, iter) )
		{
			signed int h, k, l;
			int sc;

207
208
209
210
211
212
			n_ref++;

			/* We require that the reflection itself is scalable
			 * (i.e. sensible partiality and intensity) and that
			 * the "full" estimate of this reflection is made from
			 * at least two parts. */
213
214
			get_indices(refl, &h, &k, &l);
			sc = get_scalable(refl);
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
			if ( !sc ) {

				n_noscale++;

			} else {

				Reflection *f = find_refl(full, h, k, l);

				if ( f != NULL ) {

					int r = get_redundancy(f);
					if ( (r >= 2) || have_reference ) {
						set_refinable(refl, 1);
						n_acc++;
					} else {
						n_fewmatch++;
					}

				} else {
					n_nomatch++;
				}
236
237
238
239

			}
		}

240
241
242
243
244
245
246
247
		STATUS("Image %4i: %i guide reflections accepted "
		       "(%i not scalable, %i few matches, %i total)\n",
		       i, n_acc, n_noscale, n_fewmatch, n_ref);

		/* This would be a silly situation, since there must be a match
		 * if THIS pattern has a scalable part of the reflection! */
		assert(n_nomatch == 0);

248
249
250
251
	}
}


Thomas White's avatar
Thomas White committed
252
253
254
255
int main(int argc, char *argv[])
{
	int c;
	char *infile = NULL;
Thomas White's avatar
Thomas White committed
256
	char *outfile = NULL;
Thomas White's avatar
Thomas White committed
257
	char *geomfile = NULL;
Thomas White's avatar
Thomas White committed
258
259
	char *sym = NULL;
	FILE *fh;
Thomas White's avatar
Thomas White committed
260
261
	int nthreads = 1;
	struct detector *det;
Thomas White's avatar
Thomas White committed
262
263
	int i;
	int n_total_patterns;
264
265
	struct image *images;
	int n_iter = 10;
Thomas White's avatar
Thomas White committed
266
	struct beam_params *beam = NULL;
267
	RefList *full;
268
269
270
	int n_found = 0;
	int n_expected = 0;
	int n_notfound = 0;
Thomas White's avatar
Thomas White committed
271
	int n_usable_patterns = 0;
272
	int nobs;
273
	char *reference_file = NULL;
274
	RefList *reference = NULL;
275
	int n_dud;
276
	int have_reference = 0;
Thomas White's avatar
Thomas White committed
277
278
279
280
281

	/* Long options */
	const struct option longopts[] = {
		{"help",               0, NULL,               'h'},
		{"input",              1, NULL,               'i'},
Thomas White's avatar
Thomas White committed
282
		{"output",             1, NULL,               'o'},
Thomas White's avatar
Thomas White committed
283
		{"geometry",           1, NULL,               'g'},
Thomas White's avatar
Thomas White committed
284
		{"beam",               1, NULL,               'b'},
285
		{"symmetry",           1, NULL,               'y'},
286
		{"iterations",         1, NULL,               'n'},
287
		{"reference",          1, NULL,                1},
Thomas White's avatar
Thomas White committed
288
289
290
291
		{0, 0, NULL, 0}
	};

	/* Short options */
Thomas White's avatar
Thomas White committed
292
	while ((c = getopt_long(argc, argv, "hi:g:x:j:y:o:b:",
293
294
	                        longopts, NULL)) != -1)
	{
Thomas White's avatar
Thomas White committed
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312

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

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

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

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

313
314
315
316
		case 'y' :
			sym = strdup(optarg);
			break;

Thomas White's avatar
Thomas White committed
317
318
319
320
		case 'o' :
			outfile = strdup(optarg);
			break;

321
322
323
324
		case 'n' :
			n_iter = atoi(optarg);
			break;

Thomas White's avatar
Thomas White committed
325
326
327
328
329
330
331
332
333
		case 'b' :
			beam = get_beam_parameters(optarg);
			if ( beam == NULL ) {
				ERROR("Failed to load beam parameters"
				      " from '%s'\n", optarg);
				return 1;
			}
			break;

334
		case 1 :
335
			reference_file = strdup(optarg);
336
337
			break;

Thomas White's avatar
Thomas White committed
338
339
340
341
342
343
344
345
346
		case 0 :
			break;

		default :
			return 1;
		}

	}

Thomas White's avatar
Thomas White committed
347
	/* Sanitise input filename and open */
Thomas White's avatar
Thomas White committed
348
349
350
351
352
353
354
355
356
357
358
359
360
361
	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
362
363
	/* Sanitise output filename */
	if ( outfile == NULL ) {
Thomas White's avatar
Whoops    
Thomas White committed
364
		outfile = strdup("partialator.hkl");
Thomas White's avatar
Thomas White committed
365
366
	}

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

Thomas White's avatar
Thomas White committed
369
	/* Get detector geometry */
Thomas White's avatar
Thomas White committed
370
371
372
373
374
375
376
	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
377
378
379
380
381
	if ( beam == NULL ) {
		ERROR("You must provide a beam parameters file.\n");
		return 1;
	}

382
	if ( reference_file != NULL ) {
Thomas White's avatar
Thomas White committed
383

384
		RefList *list;
385

386
		list = read_reflections(reference_file);
387
		free(reference_file);
388
		if ( list == NULL ) return 1;
389
		reference = asymmetric_indices(list, sym);
390
		reflist_free(list);
391
		have_reference = 1;
392

393
394
	}

Thomas White's avatar
Thomas White committed
395
	n_total_patterns = count_patterns(fh);
Thomas White's avatar
Thomas White committed
396
397
398
399
	if ( n_total_patterns == 0 ) {
		ERROR("No patterns to process.\n");
		return 1;
	}
Thomas White's avatar
Thomas White committed
400
401
	STATUS("There are %i patterns to process\n", n_total_patterns);

402
403
	gsl_set_error_handler_off();

404
405
406
407
408
409
410
411
	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);
412
	nobs = 0;
413
414
	for ( i=0; i<n_total_patterns; i++ ) {

415
		RefList *as;
Thomas White's avatar
Thomas White committed
416
		struct image *cur;
417

Thomas White's avatar
Thomas White committed
418
		cur = &images[n_usable_patterns];
419

Thomas White's avatar
Thomas White committed
420
421
422
		cur->det = det;

		if ( read_chunk(fh, cur) != 0 ) {
Thomas White's avatar
Thomas White committed
423
424
			/* Should not happen, because we counted the patterns
			 * earlier. */
Thomas White's avatar
Thomas White committed
425
			ERROR("Failed to read chunk from the input stream.\n");
426
427
428
			return 1;
		}

429
		/* Won't be needing this, if it exists */
Thomas White's avatar
Thomas White committed
430
431
		image_feature_list_free(cur->features);
		cur->features = NULL;
432

Thomas White's avatar
Thomas White committed
433
		/* "n_usable_patterns" will not be incremented in this case */
Thomas White's avatar
Thomas White committed
434
		if ( cur->indexed_cell == NULL ) continue;
435

Thomas White's avatar
Thomas White committed
436
		/* Fill in initial estimates of stuff */
Thomas White's avatar
Thomas White committed
437
438
439
440
441
		cur->div = beam->divergence;
		cur->bw = beam->bandwidth;
		cur->width = det->max_fs;
		cur->height = det->max_ss;
		cur->osf = 1.0;
Thomas White's avatar
Thomas White committed
442
		cur->profile_radius = 0.003e9;
Thomas White's avatar
Thomas White committed
443
		cur->pr_dud = 0;
444

Thomas White's avatar
Thomas White committed
445
		/* Muppet proofing */
Thomas White's avatar
Thomas White committed
446
447
448
		cur->data = NULL;
		cur->flags = NULL;
		cur->beam = NULL;
449

Thomas White's avatar
Thomas White committed
450
		/* This is the raw list of reflections */
Thomas White's avatar
Thomas White committed
451
452
453
		as = asymmetric_indices(cur->reflections, sym);
		reflist_free(cur->reflections);
		cur->reflections = as;
454

455
		update_partialities(cur, &n_expected, &n_found, &n_notfound);
456

457
458
		nobs += select_scalable_reflections(cur->reflections,
		                                    reference);
459

460
		progress_bar(i, n_total_patterns-1, "Loading pattern data");
Thomas White's avatar
Thomas White committed
461
		n_usable_patterns++;
462
463
464

	}
	fclose(fh);
Thomas White's avatar
Thomas White committed
465
466
	STATUS("Found %5.2f%% of the expected peaks (missed %i of %i).\n",
	       100.0 * (double)n_found / n_expected, n_notfound, n_expected);
Thomas White's avatar
Thomas White committed
467

468
	/* Make initial estimates */
469
	STATUS("Performing initial scaling.\n");
470
	full = scale_intensities(images, n_usable_patterns, reference);
Thomas White's avatar
Thomas White committed
471

472
473
	select_reflections_for_refinement(images, n_usable_patterns, full,
	                                  have_reference);
Thomas White's avatar
Thomas White committed
474

Thomas White's avatar
Thomas White committed
475
	/* Iterate */
476
	for ( i=0; i<n_iter; i++ ) {
Thomas White's avatar
Thomas White committed
477

478
479
		FILE *fhg;
		FILE *fhp;
480
		char filename[1024];
481
		int j;
482
		RefList *comp;
483

484
		STATUS("Post refinement cycle %i of %i\n", i+1, n_iter);
Thomas White's avatar
Thomas White committed
485

486
487
488
489
490
491
492
493
494
495
		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 ) {
496
497
498
499
			ERROR("Failed to open '%s'\n", filename);
			/* Nothing will be written later */
		}

500
501
502
503
504
		if ( reference == NULL ) {
			comp = full;
		} else {
			comp = reference;
		}
505

Thomas White's avatar
Thomas White committed
506
		/* Refine the geometry of all patterns to get the best fit */
507
508
		refine_all(images, n_usable_patterns, det,
		           comp, nthreads, fhg, fhp);
Thomas White's avatar
Thomas White committed
509

510
		nobs = 0;
511
512
513
514
		for ( j=0; j<n_usable_patterns; j++ ) {

			struct image *cur = &images[j];

515
516
			update_partialities(cur, &n_expected,
			                    &n_found, &n_notfound);
517
518

			nobs += select_scalable_reflections(cur->reflections,
519
			                                    reference);
520
521
522

		}

Thomas White's avatar
Thomas White committed
523
		/* Re-estimate all the full intensities */
524
		reflist_free(full);
Thomas White's avatar
Thomas White committed
525
		full = scale_intensities(images, n_usable_patterns,
526
527
528
529
		                         reference);

		select_reflections_for_refinement(images, n_usable_patterns,
		                                  full, have_reference);
Thomas White's avatar
Thomas White committed
530

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

	}

	STATUS("Final scale factors:\n");
537
	n_dud = 0;
Thomas White's avatar
Thomas White committed
538
	for ( i=0; i<n_usable_patterns; i++ ) {
539
		if ( images[i].pr_dud ) n_dud++;
Thomas White's avatar
Thomas White committed
540
		STATUS("%4i : %5.2f\n", i, images[i].osf);
Thomas White's avatar
Thomas White committed
541
	}
542
	STATUS("%i images could not be refined on the last cycle.\n", n_dud);
Thomas White's avatar
Thomas White committed
543
544

	/* Output results */
545
	write_reflist(outfile, full, images[0].indexed_cell);
Thomas White's avatar
Thomas White committed
546

Thomas White's avatar
Thomas White committed
547
	/* Clean up */
Thomas White's avatar
Thomas White committed
548
	for ( i=0; i<n_usable_patterns; i++ ) {
Thomas White's avatar
Thomas White committed
549
		reflist_free(images[i].reflections);
Thomas White's avatar
Thomas White committed
550
	}
551
	reflist_free(full);
Thomas White's avatar
Thomas White committed
552
	free(sym);
Thomas White's avatar
Thomas White committed
553
	free(outfile);
Thomas White's avatar
Thomas White committed
554
	free_detector_geometry(det);
555
	free(beam);
556
	if ( reference != NULL ) {
557
		reflist_free(reference);
558
	}
Thomas White's avatar
Thomas White committed
559
	for ( i=0; i<n_usable_patterns; i++ ) {
560
561
562
563
		cell_free(images[i].indexed_cell);
		free(images[i].filename);
	}
	free(images);
564
565
566

	return 0;
}