partialator.c 13.1 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
 * Copyright © 2012 Thomas White <taw@physics.org>
7
 *
Thomas White's avatar
Thomas White committed
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 * 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/>.
22
23
24
25
26
27
28
29
30
31
32
33
34
35
 *
 */


#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
36
#include <assert.h>
Thomas White's avatar
Tidy up    
Thomas White committed
37
#include <pthread.h>
38
#include <gsl/gsl_errno.h>
39

Thomas White's avatar
Thomas White committed
40
41
42
43
44
45
46
47
48
49
50
#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>

51
#include "post-refinement.h"
52
#include "hrs-scaling.h"
Thomas White's avatar
Thomas White committed
53
#include "scaling-report.h"
54
55
56
57
58
59


static void show_help(const char *s)
{
	printf("Syntax: %s [options]\n\n", s);
	printf(
60
"Scaling and post refinement for coherent nanocrystallography.\n"
61
62
63
"\n"
"  -h, --help                 Display this help message.\n"
"\n"
Thomas White's avatar
Thomas White committed
64
65
"  -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
66
"  -o, --output=<filename>    Output filename.  Default: partialator.hkl.\n"
Thomas White's avatar
Thomas White committed
67
"  -g. --geometry=<file>      Get detector geometry from file.\n"
68
69
70
71
"  -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"
72
"  -y, --symmetry=<sym>       Merge according to symmetry <sym>.\n"
73
"  -n, --iterations=<n>       Run <n> cycles of scaling and post-refinement.\n"
74
"      --no-scale             Fix all the scaling factors at unity.\n"
75
"  -r, --reference=<file>     Refine images against reflections in <file>,\n"
76
77
"                              instead of taking the mean of the intensity\n"
"                              estimates.\n"
78
"\n"
Thomas White's avatar
Thomas White committed
79
80
81
82
"  -j <n>                     Run <n> analyses in parallel.\n");
}


Thomas White's avatar
Thomas White committed
83
struct refine_args
Thomas White's avatar
Thomas White committed
84
{
85
	RefList *full;
Thomas White's avatar
Thomas White committed
86
87
88
89
	struct image *image;
};


Thomas White's avatar
Thomas White committed
90
struct queue_args
Thomas White's avatar
Thomas White committed
91
{
Thomas White's avatar
Thomas White committed
92
93
94
95
96
97
98
99
100
101
102
	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;
103
	struct image *image = pargs->image;
Thomas White's avatar
Thomas White committed
104
	image->id = id;
105

106
	pr_refine(image, pargs->full);
107
108
109
}


Thomas White's avatar
Thomas White committed
110
static void *get_image(void *vqargs)
111
{
Thomas White's avatar
Thomas White committed
112
113
	struct refine_args *task;
	struct queue_args *qargs = vqargs;
Thomas White's avatar
Thomas White committed
114

Thomas White's avatar
Thomas White committed
115
116
	task = malloc(sizeof(struct refine_args));
	memcpy(task, &qargs->task_defaults, sizeof(struct refine_args));
117

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

Thomas White's avatar
Thomas White committed
120
121
122
123
	qargs->n++;

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

125

Thomas White's avatar
Thomas White committed
126
127
128
129
130
131
static void done_image(void *vqargs, void *task)
{
	struct queue_args *qargs = vqargs;

	qargs->n_done++;

Thomas White's avatar
Thomas White committed
132
	progress_bar(qargs->n_done, qargs->n_total_patterns, "Refining");
Thomas White's avatar
Thomas White committed
133
134
135
136
137
	free(task);
}


static void refine_all(struct image *images, int n_total_patterns,
138
                       struct detector *det,
Thomas White's avatar
Thomas White committed
139
                       RefList *full, int nthreads)
Thomas White's avatar
Thomas White committed
140
141
142
143
144
145
146
147
148
149
{
	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
150
151
	qargs.n_total_patterns = n_total_patterns;
	qargs.images = images;
Thomas White's avatar
Thomas White committed
152

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

Thomas White's avatar
Thomas White committed
156
	run_threads(nthreads, refine_image, get_image, done_image,
Thomas White's avatar
Thomas White committed
157
	            &qargs, n_total_patterns, 0, 0, 0);
158
159
160
}


161
/* Decide which reflections can be scaled */
162
static int select_scalable_reflections(RefList *list, RefList *reference)
163
164
165
166
167
168
169
170
171
{
	Reflection *refl;
	RefListIterator *iter;
	int nobs = 0;

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

172
		int sc = 1;
173
		double v, esd;
174

175
176
177
		/* This means the reflection was not found on the last check */
		if ( get_redundancy(refl) == 0 ) sc = 0;

178
		if ( get_partiality(refl) < 0.1 ) sc = 0;
179
		v = fabs(get_intensity(refl));
180
181
		esd = get_esd_intensity(refl);
		if ( v < 0.5*esd ) sc = 0;
182

183
184
185
		/* If we are scaling against a reference set, we additionally
		 * require that this reflection is in the reference list. */
		if ( reference != NULL ) {
186
187
			signed int h, k, l;
			get_indices(refl, &h, &k, &l);
188
			if ( find_refl(reference, h, k, l) == NULL ) sc = 0;
189
190
		}

191
192
193
		set_scalable(refl, sc);

		if ( sc ) nobs++;
194
195
196
197
198
199
	}

	return nobs;
}


200
static void select_reflections_for_refinement(struct image *images, int n,
201
                                              RefList *full, int have_reference)
202
203
204
205
206
207
208
{
	int i;

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

		Reflection *refl;
		RefListIterator *iter;
209
210
211
212
213
		int n_acc = 0;
		int n_nomatch = 0;
		int n_noscale = 0;
		int n_fewmatch = 0;
		int n_ref = 0;
214

215
216
		if ( images[i].pr_dud ) continue;

217
218
219
220
221
222
223
		for ( refl = first_refl(images[i].reflections, &iter);
		      refl != NULL;
		      refl = next_refl(refl, iter) )
		{
			signed int h, k, l;
			int sc;

224
225
226
227
228
229
			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. */
230
231
			get_indices(refl, &h, &k, &l);
			sc = get_scalable(refl);
232
233
234
			if ( !sc ) {

				n_noscale++;
235
				set_refinable(refl, 0);
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252

			} 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++;
253
					set_refinable(refl, 0);
254
				}
255
256
257
258

			}
		}

259
260
261
		//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);
262
263
264
265
266

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

267
268
269
270
	}
}


Thomas White's avatar
Thomas White committed
271
272
273
274
int main(int argc, char *argv[])
{
	int c;
	char *infile = NULL;
Thomas White's avatar
Thomas White committed
275
	char *outfile = NULL;
Thomas White's avatar
Thomas White committed
276
	char *geomfile = NULL;
Thomas White's avatar
Thomas White committed
277
278
	char *sym_str = NULL;
	SymOpList *sym;
Thomas White's avatar
Thomas White committed
279
	FILE *fh;
Thomas White's avatar
Thomas White committed
280
281
	int nthreads = 1;
	struct detector *det;
Thomas White's avatar
Thomas White committed
282
283
	int i;
	int n_total_patterns;
284
285
	struct image *images;
	int n_iter = 10;
Thomas White's avatar
Thomas White committed
286
	struct beam_params *beam = NULL;
287
	RefList *full;
Thomas White's avatar
Thomas White committed
288
	int n_usable_patterns = 0;
289
	int nobs;
290
	char *reference_file = NULL;
291
	RefList *reference = NULL;
292
	int n_dud;
293
	int have_reference = 0;
Thomas White's avatar
Thomas White committed
294
295
	char cmdline[1024];
	SRContext *sr;
296
	int noscale = 0;
Thomas White's avatar
Thomas White committed
297
298
299
300
301

	/* Long options */
	const struct option longopts[] = {
		{"help",               0, NULL,               'h'},
		{"input",              1, NULL,               'i'},
Thomas White's avatar
Thomas White committed
302
		{"output",             1, NULL,               'o'},
Thomas White's avatar
Thomas White committed
303
		{"geometry",           1, NULL,               'g'},
Thomas White's avatar
Thomas White committed
304
		{"beam",               1, NULL,               'b'},
305
		{"symmetry",           1, NULL,               'y'},
306
		{"iterations",         1, NULL,               'n'},
307
		{"no-scale",           0, &noscale,            1},
308
		{"reference",          1, NULL,               'r'},
Thomas White's avatar
Thomas White committed
309
310
311
		{0, 0, NULL, 0}
	};

Thomas White's avatar
Thomas White committed
312
313
314
315
316
317
	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
318
	/* Short options */
319
	while ((c = getopt_long(argc, argv, "hi:g:x:j:y:o:b:r:",
320
321
	                        longopts, NULL)) != -1)
	{
Thomas White's avatar
Thomas White committed
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339

		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;

340
		case 'y' :
Thomas White's avatar
Thomas White committed
341
			sym_str = strdup(optarg);
342
343
			break;

Thomas White's avatar
Thomas White committed
344
345
346
347
		case 'o' :
			outfile = strdup(optarg);
			break;

348
349
350
351
		case 'n' :
			n_iter = atoi(optarg);
			break;

Thomas White's avatar
Thomas White committed
352
353
354
355
356
357
358
359
360
		case 'b' :
			beam = get_beam_parameters(optarg);
			if ( beam == NULL ) {
				ERROR("Failed to load beam parameters"
				      " from '%s'\n", optarg);
				return 1;
			}
			break;

361
		case 'r' :
362
			reference_file = strdup(optarg);
363
364
			break;

Thomas White's avatar
Thomas White committed
365
366
367
368
369
370
371
372
373
		case 0 :
			break;

		default :
			return 1;
		}

	}

Thomas White's avatar
Thomas White committed
374
375
376
377
378
	if ( nthreads < 1 ) {
		ERROR("Invalid number of threads.\n");
		return 1;
	}

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

Thomas White's avatar
Thomas White committed
398
399
400
	if ( sym_str == NULL ) sym_str = strdup("1");
	sym = get_pointgroup(sym_str);
	free(sym_str);
Thomas White's avatar
Thomas White committed
401

Thomas White's avatar
Thomas White committed
402
	/* Get detector geometry */
Thomas White's avatar
Thomas White committed
403
404
405
406
407
408
409
	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
410
411
412
413
414
	if ( beam == NULL ) {
		ERROR("You must provide a beam parameters file.\n");
		return 1;
	}

415
	if ( reference_file != NULL ) {
Thomas White's avatar
Thomas White committed
416

417
		RefList *list;
418

419
		list = read_reflections(reference_file);
420
421
422
423
		if ( list == NULL ) {
			ERROR("Failed to read '%s'\n", reference_file);
			return 1;
		}
424
		free(reference_file);
425
		reference = asymmetric_indices(list, sym);
426
		reflist_free(list);
427
		have_reference = 1;
428

429
430
	}

Thomas White's avatar
Thomas White committed
431
	n_total_patterns = count_patterns(fh);
Thomas White's avatar
Thomas White committed
432
433
434
435
	if ( n_total_patterns == 0 ) {
		ERROR("No patterns to process.\n");
		return 1;
	}
Thomas White's avatar
Thomas White committed
436
437
	STATUS("There are %i patterns to process\n", n_total_patterns);

438
439
	gsl_set_error_handler_off();

440
441
442
443
444
445
446
447
	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);
448
	nobs = 0;
449
450
	for ( i=0; i<n_total_patterns; i++ ) {

451
		RefList *as;
Thomas White's avatar
Thomas White committed
452
		struct image *cur;
453

Thomas White's avatar
Thomas White committed
454
		cur = &images[n_usable_patterns];
455

Thomas White's avatar
Thomas White committed
456
457
458
		cur->det = det;

		if ( read_chunk(fh, cur) != 0 ) {
Thomas White's avatar
Thomas White committed
459
460
			/* Should not happen, because we counted the patterns
			 * earlier. */
Thomas White's avatar
Thomas White committed
461
			ERROR("Failed to read chunk from the input stream.\n");
462
463
464
			return 1;
		}

465
		/* Won't be needing this, if it exists */
Thomas White's avatar
Thomas White committed
466
467
		image_feature_list_free(cur->features);
		cur->features = NULL;
468

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

Thomas White's avatar
Thomas White committed
472
		/* Fill in initial estimates of stuff */
Thomas White's avatar
Thomas White committed
473
474
475
476
477
		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
478
		cur->profile_radius = 0.003e9;
Thomas White's avatar
Thomas White committed
479
		cur->pr_dud = 0;
480

Thomas White's avatar
Thomas White committed
481
		/* Muppet proofing */
Thomas White's avatar
Thomas White committed
482
483
484
		cur->data = NULL;
		cur->flags = NULL;
		cur->beam = NULL;
485

Thomas White's avatar
Thomas White committed
486
		/* This is the raw list of reflections */
Thomas White's avatar
Thomas White committed
487
488
489
		as = asymmetric_indices(cur->reflections, sym);
		reflist_free(cur->reflections);
		cur->reflections = as;
490

491
		update_partialities(cur);
492

493
494
		nobs += select_scalable_reflections(cur->reflections,
		                                    reference);
495

496
		progress_bar(i, n_total_patterns-1, "Loading pattern data");
Thomas White's avatar
Thomas White committed
497
		n_usable_patterns++;
498
499
500

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

502
	/* Make initial estimates */
503
	STATUS("Performing initial scaling.\n");
504
	if ( noscale ) STATUS("Scale factors fixed at 1.\n");
Thomas White's avatar
Thomas White committed
505
	full = scale_intensities(images, n_usable_patterns, reference,
506
	                         nthreads, noscale);
Thomas White's avatar
Thomas White committed
507

508
509
510
	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
511

Thomas White's avatar
Thomas White committed
512
	/* Iterate */
513
	for ( i=0; i<n_iter; i++ ) {
Thomas White's avatar
Thomas White committed
514

515
		int j;
516
		RefList *comp;
517

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

520
521
522
523
524
		if ( reference == NULL ) {
			comp = full;
		} else {
			comp = reference;
		}
525

Thomas White's avatar
Thomas White committed
526
		/* Refine the geometry of all patterns to get the best fit */
527
528
		select_reflections_for_refinement(images, n_usable_patterns,
		                                  comp, have_reference);
Thomas White's avatar
Thomas White committed
529
		refine_all(images, n_usable_patterns, det, comp, nthreads);
Thomas White's avatar
Thomas White committed
530

531
		nobs = 0;
532
533
534
535
		for ( j=0; j<n_usable_patterns; j++ ) {

			struct image *cur = &images[j];

536
			nobs += select_scalable_reflections(cur->reflections,
537
			                                    reference);
538
539
540

		}

Thomas White's avatar
Thomas White committed
541
		/* Re-estimate all the full intensities */
542
		reflist_free(full);
Thomas White's avatar
Thomas White committed
543
		full = scale_intensities(images, n_usable_patterns,
544
		                         reference, nthreads, noscale);
545

546
547
		sr_iteration(sr, i+1, images, n_usable_patterns, full);

Thomas White's avatar
Thomas White committed
548
549
	}

550
551
	sr_finish(sr);

552
	n_dud = 0;
Thomas White's avatar
Thomas White committed
553
	for ( i=0; i<n_usable_patterns; i++ ) {
554
		if ( images[i].pr_dud ) n_dud++;
Thomas White's avatar
Thomas White committed
555
	}
556
	STATUS("%i images could not be refined on the last cycle.\n", n_dud);
Thomas White's avatar
Thomas White committed
557
558

	/* Output results */
559
	write_reflist(outfile, full);
Thomas White's avatar
Thomas White committed
560

Thomas White's avatar
Thomas White committed
561
	/* Clean up */
Thomas White's avatar
Thomas White committed
562
	for ( i=0; i<n_usable_patterns; i++ ) {
Thomas White's avatar
Thomas White committed
563
		reflist_free(images[i].reflections);
Thomas White's avatar
Thomas White committed
564
	}
565
	reflist_free(full);
Thomas White's avatar
Thomas White committed
566
	free(sym);
Thomas White's avatar
Thomas White committed
567
	free(outfile);
Thomas White's avatar
Thomas White committed
568
	free_detector_geometry(det);
569
	free(beam);
570
	if ( reference != NULL ) {
571
		reflist_free(reference);
572
	}
Thomas White's avatar
Thomas White committed
573
	for ( i=0; i<n_usable_patterns; i++ ) {
574
575
576
577
		cell_free(images[i].indexed_cell);
		free(images[i].filename);
	}
	free(images);
Thomas White's avatar
Thomas White committed
578
	free(infile);
579
580
581

	return 0;
}