partialator.c 12.3 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
28
29
30
31
32
33
34
35
36
37
#include <utils.h>
#include <hdf5-file.h>
#include <symmetry.h>
#include <stream.h>
#include <geometry.h>
#include <peaks.h>
#include <thread-pool.h>
#include <beam-parameters.h>
#include <reflist.h>
#include <reflist-utils.h>

38
#include "post-refinement.h"
39
#include "hrs-scaling.h"
Thomas White's avatar
Thomas White committed
40
#include "scaling-report.h"
41
42
43
44
45
46


static void show_help(const char *s)
{
	printf("Syntax: %s [options]\n\n", s);
	printf(
47
"Scaling and post refinement for coherent nanocrystallography.\n"
48
49
50
"\n"
"  -h, --help                 Display this help message.\n"
"\n"
Thomas White's avatar
Thomas White committed
51
52
"  -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
53
"  -o, --output=<filename>    Output filename.  Default: facetron.hkl.\n"
Thomas White's avatar
Thomas White committed
54
"  -g. --geometry=<file>      Get detector geometry from file.\n"
55
56
57
58
"  -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"
59
"  -y, --symmetry=<sym>       Merge according to symmetry <sym>.\n"
60
"  -n, --iterations=<n>       Run <n> cycles of scaling and post-refinement.\n"
61
"  -r, --reference=<file>     Refine images against reflections in <file>,\n"
62
63
"                              instead of taking the mean of the intensity\n"
"                              estimates.\n"
64
"\n"
Thomas White's avatar
Thomas White committed
65
66
67
68
"  -j <n>                     Run <n> analyses in parallel.\n");
}


Thomas White's avatar
Thomas White committed
69
struct refine_args
Thomas White's avatar
Thomas White committed
70
{
71
	RefList *full;
Thomas White's avatar
Thomas White committed
72
73
74
75
	struct image *image;
};


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
                       struct detector *det,
Thomas White's avatar
Thomas White committed
125
                       RefList *full, int nthreads)
Thomas White's avatar
Thomas White committed
126
127
128
129
130
131
132
133
134
135
{
	struct refine_args task_defaults;
	struct queue_args qargs;

	task_defaults.full = full;
	task_defaults.image = NULL;

	qargs.task_defaults = task_defaults;
	qargs.n = 0;
	qargs.n_done = 0;
Thomas White's avatar
Thomas White committed
136
137
	qargs.n_total_patterns = n_total_patterns;
	qargs.images = images;
Thomas White's avatar
Thomas White committed
138

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

Thomas White's avatar
Thomas White committed
142
	run_threads(nthreads, refine_image, get_image, done_image,
Thomas White's avatar
Thomas White committed
143
	            &qargs, n_total_patterns, 0, 0, 0);
144
145
146
}


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

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

158
		int sc = 1;
159
		double v, esd;
160

161
162
163
		/* This means the reflection was not found on the last check */
		if ( get_redundancy(refl) == 0 ) sc = 0;

164
		if ( get_partiality(refl) < 0.1 ) sc = 0;
165
		v = fabs(get_intensity(refl));
166
167
		esd = get_esd_intensity(refl);
		if ( v < 0.5*esd ) sc = 0;
168

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

177
178
179
		set_scalable(refl, sc);

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

	return nobs;
}


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

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

		Reflection *refl;
		RefListIterator *iter;
195
196
197
198
199
		int n_acc = 0;
		int n_nomatch = 0;
		int n_noscale = 0;
		int n_fewmatch = 0;
		int n_ref = 0;
200

201
202
		if ( images[i].pr_dud ) continue;

203
204
205
206
207
208
209
		for ( refl = first_refl(images[i].reflections, &iter);
		      refl != NULL;
		      refl = next_refl(refl, iter) )
		{
			signed int h, k, l;
			int sc;

210
211
212
213
214
215
			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. */
216
217
			get_indices(refl, &h, &k, &l);
			sc = get_scalable(refl);
218
219
220
			if ( !sc ) {

				n_noscale++;
221
				set_refinable(refl, 0);
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238

			} 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++;
239
					set_refinable(refl, 0);
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);
248
249
250
251
252

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

253
254
255
256
	}
}


Thomas White's avatar
Thomas White committed
257
258
259
260
int main(int argc, char *argv[])
{
	int c;
	char *infile = NULL;
Thomas White's avatar
Thomas White committed
261
	char *outfile = NULL;
Thomas White's avatar
Thomas White committed
262
	char *geomfile = NULL;
Thomas White's avatar
Thomas White committed
263
264
	char *sym_str = NULL;
	SymOpList *sym;
Thomas White's avatar
Thomas White committed
265
	FILE *fh;
Thomas White's avatar
Thomas White committed
266
267
	int nthreads = 1;
	struct detector *det;
Thomas White's avatar
Thomas White committed
268
269
	int i;
	int n_total_patterns;
270
271
	struct image *images;
	int n_iter = 10;
Thomas White's avatar
Thomas White committed
272
	struct beam_params *beam = NULL;
273
	RefList *full;
Thomas White's avatar
Thomas White committed
274
	int n_usable_patterns = 0;
275
	int nobs;
276
	char *reference_file = NULL;
277
	RefList *reference = NULL;
278
	int n_dud;
279
	int have_reference = 0;
Thomas White's avatar
Thomas White committed
280
281
	char cmdline[1024];
	SRContext *sr;
Thomas White's avatar
Thomas White committed
282
283
284
285
286

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

Thomas White's avatar
Thomas White committed
296
297
298
299
300
301
	cmdline[0] = '\0';
	for ( i=1; i<argc; i++ ) {
		strncat(cmdline, argv[i], 1023-strlen(cmdline));
		strncat(cmdline, " ", 1023-strlen(cmdline));
	}

Thomas White's avatar
Thomas White committed
302
	/* Short options */
303
	while ((c = getopt_long(argc, argv, "hi:g:x:j:y:o:b:r:",
304
305
	                        longopts, NULL)) != -1)
	{
Thomas White's avatar
Thomas White committed
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323

		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;

324
		case 'y' :
Thomas White's avatar
Thomas White committed
325
			sym_str = strdup(optarg);
326
327
			break;

Thomas White's avatar
Thomas White committed
328
329
330
331
		case 'o' :
			outfile = strdup(optarg);
			break;

332
333
334
335
		case 'n' :
			n_iter = atoi(optarg);
			break;

Thomas White's avatar
Thomas White committed
336
337
338
339
340
341
342
343
344
		case 'b' :
			beam = get_beam_parameters(optarg);
			if ( beam == NULL ) {
				ERROR("Failed to load beam parameters"
				      " from '%s'\n", optarg);
				return 1;
			}
			break;

345
		case 'r' :
346
			reference_file = strdup(optarg);
347
348
			break;

Thomas White's avatar
Thomas White committed
349
350
351
352
353
354
355
356
357
		case 0 :
			break;

		default :
			return 1;
		}

	}

Thomas White's avatar
Thomas White committed
358
359
360
361
362
	if ( nthreads < 1 ) {
		ERROR("Invalid number of threads.\n");
		return 1;
	}

Thomas White's avatar
Thomas White committed
363
	/* Sanitise input filename and open */
Thomas White's avatar
Thomas White committed
364
365
366
367
368
369
370
371
372
373
374
375
376
	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;
	}

Thomas White's avatar
Thomas White committed
377
378
	/* Sanitise output filename */
	if ( outfile == NULL ) {
Thomas White's avatar
Whoops    
Thomas White committed
379
		outfile = strdup("partialator.hkl");
Thomas White's avatar
Thomas White committed
380
381
	}

Thomas White's avatar
Thomas White committed
382
383
384
	if ( sym_str == NULL ) sym_str = strdup("1");
	sym = get_pointgroup(sym_str);
	free(sym_str);
Thomas White's avatar
Thomas White committed
385

Thomas White's avatar
Thomas White committed
386
	/* Get detector geometry */
Thomas White's avatar
Thomas White committed
387
388
389
390
391
392
393
	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
394
395
396
397
398
	if ( beam == NULL ) {
		ERROR("You must provide a beam parameters file.\n");
		return 1;
	}

399
	if ( reference_file != NULL ) {
Thomas White's avatar
Thomas White committed
400

401
		RefList *list;
402

403
		list = read_reflections(reference_file);
404
405
406
407
		if ( list == NULL ) {
			ERROR("Failed to read '%s'\n", reference_file);
			return 1;
		}
408
		free(reference_file);
409
		reference = asymmetric_indices(list, sym);
410
		reflist_free(list);
411
		have_reference = 1;
412

413
414
	}

Thomas White's avatar
Thomas White committed
415
	n_total_patterns = count_patterns(fh);
Thomas White's avatar
Thomas White committed
416
417
418
419
	if ( n_total_patterns == 0 ) {
		ERROR("No patterns to process.\n");
		return 1;
	}
Thomas White's avatar
Thomas White committed
420
421
	STATUS("There are %i patterns to process\n", n_total_patterns);

422
423
	gsl_set_error_handler_off();

424
425
426
427
428
429
430
431
	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);
432
	nobs = 0;
433
434
	for ( i=0; i<n_total_patterns; i++ ) {

435
		RefList *as;
Thomas White's avatar
Thomas White committed
436
		struct image *cur;
437

Thomas White's avatar
Thomas White committed
438
		cur = &images[n_usable_patterns];
439

Thomas White's avatar
Thomas White committed
440
441
442
		cur->det = det;

		if ( read_chunk(fh, cur) != 0 ) {
Thomas White's avatar
Thomas White committed
443
444
			/* Should not happen, because we counted the patterns
			 * earlier. */
Thomas White's avatar
Thomas White committed
445
			ERROR("Failed to read chunk from the input stream.\n");
446
447
448
			return 1;
		}

449
		/* Won't be needing this, if it exists */
Thomas White's avatar
Thomas White committed
450
451
		image_feature_list_free(cur->features);
		cur->features = NULL;
452

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

Thomas White's avatar
Thomas White committed
456
		/* Fill in initial estimates of stuff */
Thomas White's avatar
Thomas White committed
457
458
459
460
461
		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
462
		cur->profile_radius = 0.003e9;
Thomas White's avatar
Thomas White committed
463
		cur->pr_dud = 0;
464

Thomas White's avatar
Thomas White committed
465
		/* Muppet proofing */
Thomas White's avatar
Thomas White committed
466
467
468
		cur->data = NULL;
		cur->flags = NULL;
		cur->beam = NULL;
469

Thomas White's avatar
Thomas White committed
470
		/* This is the raw list of reflections */
Thomas White's avatar
Thomas White committed
471
472
473
		as = asymmetric_indices(cur->reflections, sym);
		reflist_free(cur->reflections);
		cur->reflections = as;
474

475
		update_partialities(cur);
476

477
478
		nobs += select_scalable_reflections(cur->reflections,
		                                    reference);
479

480
		progress_bar(i, n_total_patterns-1, "Loading pattern data");
Thomas White's avatar
Thomas White committed
481
		n_usable_patterns++;
482
483
484

	}
	fclose(fh);
Thomas White's avatar
Thomas White committed
485

486
	/* Make initial estimates */
487
	STATUS("Performing initial scaling.\n");
Thomas White's avatar
Thomas White committed
488
489
	full = scale_intensities(images, n_usable_patterns, reference,
	                         nthreads);
Thomas White's avatar
Thomas White committed
490

491
492
493
	sr = sr_titlepage(images, n_usable_patterns, "scaling-report.pdf",
	                  infile, cmdline);
	sr_iteration(sr, 0, images, n_usable_patterns, full);
Thomas White's avatar
Thomas White committed
494

Thomas White's avatar
Thomas White committed
495
	/* Iterate */
496
	for ( i=0; i<n_iter; i++ ) {
Thomas White's avatar
Thomas White committed
497

498
		int j;
499
		RefList *comp;
500

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

503
504
505
506
507
		if ( reference == NULL ) {
			comp = full;
		} else {
			comp = reference;
		}
508

Thomas White's avatar
Thomas White committed
509
		/* Refine the geometry of all patterns to get the best fit */
510
511
		select_reflections_for_refinement(images, n_usable_patterns,
		                                  comp, have_reference);
Thomas White's avatar
Thomas White committed
512
		refine_all(images, n_usable_patterns, det, comp, nthreads);
Thomas White's avatar
Thomas White committed
513

514
		nobs = 0;
515
516
517
518
		for ( j=0; j<n_usable_patterns; j++ ) {

			struct image *cur = &images[j];

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

		}

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

529
530
		sr_iteration(sr, i+1, images, n_usable_patterns, full);

Thomas White's avatar
Thomas White committed
531
532
	}

533
534
	sr_finish(sr);

535
	n_dud = 0;
Thomas White's avatar
Thomas White committed
536
	for ( i=0; i<n_usable_patterns; i++ ) {
537
		if ( images[i].pr_dud ) n_dud++;
Thomas White's avatar
Thomas White committed
538
	}
539
	STATUS("%i images could not be refined on the last cycle.\n", n_dud);
Thomas White's avatar
Thomas White committed
540
541

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

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

	return 0;
}