File: powder.pl

package info (click to toggle)
horae 066-3
  • links: PTS
  • area: contrib
  • in suites: lenny
  • size: 17,272 kB
  • ctags: 1,656
  • sloc: perl: 64,718; lisp: 744; sh: 82; makefile: 67; ansic: 35
file content (394 lines) | stat: -rwxr-xr-x 12,960 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
#!/usr/bin/perl -w
my $cvs_info = '$Id: powder.pl,v 1.3 2001/09/20 17:28:26 bruce Exp $ ';
## Time-stamp: <14 December, 2005>
######################################################################
## Powder for Atoms version 3.0beta9
##                                     copyright (c) 2000 Bruce Ravel
##                                          ravel@phys.washington.edu
##                            http://feff.phys.washington.edu/~ravel/
##
##	  The latest version of Atoms can always be found at
##	 http://feff.phys.washington.edu/~ravel/software/atoms/
##
## -------------------------------------------------------------------
##     All rights reserved. This program is free software; you can
##     redistribute it and/or modify it under the same terms as Perl
##     itself.
##
##     This program 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
##     Artistic License for more details.
## -------------------------------------------------------------------
######################################################################
## This reads input files for Atoms and simulates the powder
## diffraction spectrum for that crystal.  Do `powder.pl -h' for
## details.
######################################################################

##use lib '/usr/local/share/ifeffit/perl';
## =============================== load methods
require 5.004;
use strict;
use Carp;
use Xray::Xtal;
$Xray::Xtal::run_level = 0;
use Xray::ATP;
use Xray::Absorption;
use Xray::Scattering;
use IO::File;
use File::Basename;
use Cwd;
use constant EPSI  => 0.01;
use constant PI    => 4 * atan2 1, 1;
use constant HBARC => 1973.27053324;

## =============================== process command line switches
use Getopt::Std;
use vars qw(%opt);
$opt{o} = "";
getopts('ADIvqhst:o:e:m:', \%opt);


my ($file, $inputdir);
if ($ARGV[0] and ($ARGV[0] eq '-')) {		# read from STDIN
  $file = '____stdin';		# an unlikely string (I hope)
  $inputdir = cwd;
} elsif ($opt{A}) {
  my $inp = $ARGV[0];
  unless ($inp =~ /\.inp$/) {
    $inp .= ($inp =~ /\.$/) ? 'inp' : '.inp';
  };
  $file = $Xray::Atoms::meta{ADB_location} . $inp;
  $inputdir = cwd;
} else {
  unless ($^O eq 'MacOS') {
  INPUT: {
      $file = "atoms.inp",       last INPUT if (not $ARGV[0]);
      $file = $ARGV[0],          last INPUT if (-e $ARGV[0]);
      $file = $ARGV[0] . ".inp", last INPUT if (-e "$ARGV[0].inp");
      $file = $ARGV[0] . "inp",  last INPUT if (-e "$ARGV[0]inp");
      die $ARGV[0] . ": " . $$Xray::Atoms::messages{'invalid_input'} . $/;
    }
  } else {
    require Mac::StandardFile;
    $file = Mac::StandardFile::StandardGetFile(0, 'TEXTclpt');
    if ($file -> sfGood()) {
      $file = $file->sfFile();
    } else {
      die "File opening canceled.  Powder quitting.$/";
    };
  };
  $inputdir = dirname($file);	# if write_to_pwd is false...
}

my @sites   = ();		# list of sites
my @cluster = ();		# spherical cluster
my @neutral = ();		# charge neutral rhomboidal cluster

## =============================== run time screen messages
my $v		= $Xray::Atoms::VERSION;
my $date	= (split(" ", $cvs_info))[3] || '';
my $scriptv	= (split(" ", $cvs_info))[2] || 'pre-release';
my $screen_line = "=" x 71;

if ($opt{h}) {
  require Pod::Text;
  $^W=0;
  if ($Pod::Text::VERSION < 2.0) {
    Pod::Text::pod2text($0, *STDOUT);
  } elsif ($Pod::Text::VERSION >= 2.0) {
    my $parser = Pod::Text->new;
    open STDIN, $0;
    $parser->parse_from_filehandle;
  };
  exit;
};

print STDOUT <<EOH
$screen_line
 Powder $scriptv ($^O) $date
$screen_line
EOH
unless ($opt{q});

my $resource = (grep /CL/, Xray::Absorption->scattering()) ? 'CL' : 'Chantler';
$opt{I} and ($resource = "None");
Xray::Absorption -> load($resource);

my $absorption_resource = Xray::Absorption -> current_resource;
print STDOUT <<EOH
    by Bruce Ravel copyright (c) 2000
    <ravel\@phys.washington.edu>

    powder.pl for Atoms $v
    using Atoms.pm $Xray::Atoms::module_version, ATP.pm $Xray::ATP::module_version
          Xtal.pm $Xray::Xtal::VERSION, space groups database $Xray::Xtal::sg_version
          Absorption.pm $Xray::Absorption::cvs_version
          $absorption_resource
    with perl $] on $^O.

EOH
and exit if ($opt{v});

## =============================== define a cell, parse the input file,
my $cell = Xray::Xtal::Cell -> new();
my $keywords = Xray::Atoms -> new();
$opt{q} && $keywords->make('quiet'=>1);
$keywords -> parse_input($file, 0);
die "\n" if $keywords->{cli_warn};
($opt{c}) && $keywords->make(core=>$opt{c});
$keywords->make('identity'=>"Powder $scriptv", die=>0);

## =============================== determine the energy at which to calculate
($resource eq 'None') or Xray::Absorption -> load('elam');
if ($opt{e}) {			# see Cookbook recipe 2.1
  unless ($opt{e} =~ /^(?:\d+(?:\.\d*)?|\.\d+)$/) { # regex matching a number
    my ($el, $en) = ("", "");
    ($el, $en) =  split(/[-_]/, $opt{e});
    $opt{e} = Xray::Absorption -> get_energy($el, $en);
  };
};
my $energy = $opt{e} || $keywords->{energy} ||
  Xray::Absorption -> get_energy('Cu', 'kalpha1');
my $lambda  = 2*PI*HBARC / $energy;
## the cutoff with this trick is about 111.3
($lambda > $energy) and (($lambda, $energy) = ($energy, $lambda));
$keywords->make('energy'=>$energy, 'lambda'=>$lambda);

($resource eq 'None') or Xray::Absorption -> load($resource);

## =============================== fill up the cell and the sites
$cell -> make( Space_group=>$keywords->{'space'} );
foreach my $param ('a', 'b', 'c', 'alpha', 'beta', 'gamma') {
  $cell -> make( $param=>$keywords->{$param} );
};
($file eq '____stdin') and $file = 'the input data';
( @{$keywords->{'sites'}} ) or croak "$$Xray::Atoms::messages{no_sites} $file$/";

my $nsites = 0;
foreach my $this (@{$keywords->{'sites'}}) {
  $sites[$nsites] = Xray::Xtal::Site -> new($nsites);
  $sites[$nsites] -> make(Element=>$$this[0],
			  X=>$$this[1]+${$keywords->{"shift"}}[0],
			  Y=>$$this[2]+${$keywords->{"shift"}}[1],
			  Z=>$$this[3]+${$keywords->{"shift"}}[2] );
  ($$this[4]) && ( $sites[$nsites] -> make(Tag=>$$this[4]) );
  ($$this[5]) && ( $sites[$nsites] -> make(Occupancy=>$$this[5]) );
  ## cache f' and f" for this site and this energy
  $sites[$nsites] ->
    make(F1=>scalar Xray::Absorption->cross_section($$this[0],$energy,'f1'));
  $sites[$nsites] ->
    make(F2=>scalar Xray::Absorption->cross_section($$this[0],$energy,'f2'));
  ++$nsites;
};


## =============================== error check, populate the cell, set rmax
$cell -> verify_cell();
$cell -> populate(\@sites);
$keywords -> verify_keywords($cell, \@sites, 0, 1);

## =============================== some error checking
($opt{q}) or print $cell -> warn_shift(), $cell -> cell_check();

## =============================== dump...
if ($opt{D}) {
  use Data::Dumper;
  print Data::Dumper->Dump([$keywords, $cell], [qw/*keywords *cell/]);
  exit;
};

## =============================== determine bounds of calculation
my $max_order = $keywords -> {maxorder} || 0;
## the $max_order variable will be eval-ed a little below.  thus we
## must do some taint checking of the value of the $opt{m} variable
if ($opt{m}) {
  if ($opt{m} =~ /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/) {
    $max_order = int($opt{m});
  } else {
    warn "max_order should be an integer or a float$/";
  };
};
##   require Safe;
##   my $cpt = new Safe;
##   $ {$cpt->varglob('m')} = $cpt->reval($opt{m});
##   $max_order = $ {$cpt->varglob('m')};
##   ($max_order) || warn " Tainted value for max_order found.  Reset to default.$/";
$max_order ||= 12;

my $class = $cell -> crystal_class;
my ($hrange, $krange, $lrange);
CLASS: {
  ($class eq 'cubic') and do {
    $hrange = "(0 .. \$max_order)";
    $krange = "(0 .. \$h)";
    $lrange = "(0 .. \$k)";
    last CLASS;
  };
  ($class eq 'trigonal') and do {
    die " Sorry, no trigonal yet$/";
  };
  (($class eq 'hexagonal') or ($class eq 'tetragonal')) and do {
    $hrange = "(0 .. \$max_order)";
    $krange = "(0 .. \$h)";
    $lrange = "(0 .. \$max_order)";
    last CLASS;
  };
  do {				# ortho, mono, tri
    $hrange = "(0 .. \$max_order)";
    $krange = "(0 .. \$max_order)";
    $lrange = "(0 .. \$max_order)";
    last CLASS;
  };
};


$$Xray::Atoms::messages{powder_comp} = "Computing powder diffraction";
($opt{q}) or printf " %s -- %8.2f eV (%.4f )$/",
  $$Xray::Atoms::messages{powder_comp}, $energy, $lambda;
my %peaks;
foreach my $h (eval $hrange) {
  foreach my $k (eval $krange) {
    foreach my $l (eval $lrange) {
      next unless $h||$k||$l;	# watch out for (0,0,0)

      my %f0 = ();
      my $d = $cell -> d_spacing($h, $k, $l);
      next if (($lambda / (2*$d)) > 1);	# unreachable reflections at this energy

      my $theta   = asin($lambda / (2*$d));
      $theta     *= 180/PI;
      my $twoth   = $theta * 2;

      my ($real, $imag, $m) = (0, 0, 0);
      foreach my $s (@sites) {
	my ($positions, $tag, $elem, $occ, $f1, $f2, $b) =
	  $s -> attributes('Positions', 'Tag', 'Element', 'Occupancy', 'F1', 'F2', 'B');
	$f0{$elem} ||= Xray::Scattering->get_f($elem, $d); # memoize for a bit of speed
	my ($freal, $fimag) = ($f0{$elem}+$f1, $f2);
	foreach my $pos (@$positions) {
	  my $phase = $$pos[0]*$h + $$pos[1]*$k + $$pos[2]*$l;
	  $phase   *= 2 * PI;
	  $real    += $occ * (cos($phase)*$freal - sin($phase)*$fimag);
	  $imag    += $occ * (sin($phase)*$freal + cos($phase)*$fimag);
	};
	$m = $b*(sin($theta)/$lambda)**2;
      };
      (abs($real) < EPSI) and $real = 0;
      (abs($imag) < EPSI) and $imag = 0;
      next unless ($real or $imag);
      ## just cache the values of the structure factor.  computing
      ## intensity will happen when the atp file is parsed
      @{$peaks{$twoth}} = ($h, $k, $l, $real, $imag, $m);
    };
  };
};

## sort and prep for atp
my @calculation;
foreach my $tth (sort {$a <=> $b} (keys(%peaks))) {
  push @calculation, [$tth, @{$peaks{$tth}}];
};


## =============================== open the output file and make the file header
my ($fh, $atp, $outfile);
if (defined %{$keywords->{'atp'}}) {
 LOOP: while (($atp, $outfile) = each(%{$keywords->{'files'}})) {
    last LOOP;			# just the first (should only be one)
  };				# there must be a better way!
} else {
  $atp = 'powder';
};
($atp =~ /^powder/) and ($atp = 'powder');
($opt{t}) and $atp = $opt{t};
my $data = "";
my ($default_name, $is_feff) =
  &parse_atp($atp, $cell, $keywords, \@calculation, \@neutral, \$data);

if ($opt{s}) {
  $fh = *STDOUT;
  $outfile = "to standard output";
} else {
  $outfile = $opt{o} || $default_name;
  unless ($keywords->{'write_to_pwd'}) {
    $outfile = File::Spec -> catfile($inputdir, $outfile);
  };
  $fh = IO::File->new();
  open $fh, ">".$outfile
    or die $$Xray::Atoms::messages{cannot_write} . $outfile . $/;
}

print $fh $data;
($opt{s}) or close $fh;

($opt{q}) or
  print STDOUT " $atp: ", $$Xray::Atoms::messages{'writing'}, " ", $outfile, $/;

## =============================== finish up
($opt{q}) or print STDOUT $screen_line, $/, $/;

sub asin { atan2($_[0], sqrt(1 - $_[0] * $_[0])) }


1;

######################################################################
## End of main program powder

=head1 NAME

Powder - Simulate powder diffraction for a crystal

=head1 SYNOPSIS

   powder [-m#] [-e#] [-AIqvh] [-t atptype] [-o file] input_file

=head1 DESCRIPTION

Take crystallographic data from the input file given on the command
line and compute a powder diffraction simulation for the crystal
described in the that input file.  By default, the simulation is made
at the copper Kalpha1 energy, although a different energy can be
specified.  If the input file specified at the command line is '-',
then input is read from STDIN.  Several command line switches can be
used to override the contents of the input files.

 output file flags
    -t s  user supplied template   -o f  output file name
    -O    write to STDOUT

 operational flags
    -I    ignore anomalous corrections to the scattering factors
    -A    use a named file from the Atoms Database
    -e #  override the value of energy with the given value
    -m #  override the value of maxorder with the given value (12)
    -q    suppress screen messages
    -v    write version information and exit
    -h    write this message and exit

               # = number   f = file   s = string

The argument to -e can be an energy, a wavelength, or a string such as
"cu_kalpha1" or "Pt-Lbeta2" (i.e. an element symbol and a line symbol
separated by a dash or an underscore, case does not matter).  Line
energies from the Elam tables (see L<Xray::Absorption::Elam>) are
used.

For complete information about Powder and/or Atoms, consult the
documentation.

=head1 AUTHOR

Bruce Ravel, ravel@phys.washington.edu

my homepage

   http://feff.phys.washington.edu/~ravel/

the Atoms homepage

   http://feff.phys.washington.edu/~ravel/software/atoms/

=cut