root/branches/mcstas-1.x/mcresplot.pl

Revision 2058, 14.1 KB (checked in by pkwi, 5 years ago)

From next release, McStas is GPL 2 only.

The debate on the internet about the future GPL 3 suggests that this license might have implications on the 'derived work', hence have implications on what and how our users use their McStas simulations.

  • Property svn:executable set to *
Line 
1#! /usr/bin/perl
2#
3# Implements plotting of McStas resolution function data using PGPLOT
4#
5#
6#   This file is part of the McStas neutron ray-trace simulation package
7#   Copyright (C) 1997-2004, All rights reserved
8#   Risoe National Laborartory, Roskilde, Denmark
9#   Institut Laue Langevin, Grenoble, France
10#
11#   This program is free software; you can redistribute it and/or modify
12#   it under the terms of the GNU General Public License as published by
13#   the Free Software Foundation; version 2 of the License.
14#
15#   This program is distributed in the hope that it will be useful,
16#   but WITHOUT ANY WARRANTY; without even the implied warranty of
17#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18#   GNU General Public License for more details.
19#
20#   You should have received a copy of the GNU General Public License
21#   along with this program; if not, write to the Free Software
22#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23
24use PDL;
25use PDL::Core;
26use PDL::Math;
27use PDL::Slatec;
28use PDL::IO::FastRaw;
29use PGPLOT;
30use PDL::Graphics::PGPLOT;
31
32# Determine the path to the McStas system directory. This must be done
33# in the BEGIN block so that it can be used in a "use lib" statement
34# afterwards.
35BEGIN {
36    if($ENV{"MCSTAS"}) {
37        $MCSTAS::sys_dir = $ENV{"MCSTAS"};
38    } else {
39        $MCSTAS::sys_dir = "/usr/local/lib/mcstas";
40    }
41    $MCSTAS::perl_dir = "$MCSTAS::sys_dir/tools/perl"
42}
43use lib $MCSTAS::perl_dir;
44
45require "mcfrontlib2D.pl";
46
47$PI = 3.14159265358979323846;
48
49sub read_mcstas_info {
50  my ($file) = @_;
51  my $basedir;
52  $basedir = $1 if $file && $file =~ m|^(.*)/[^/]*$|;
53  my $handle = new FileHandle;
54  open $handle, $file or die "Could not open file '$file'";
55  $info = read_simulation_info($handle);
56  close($handle);
57  return ($info);
58}
59
60sub read_mcstas_res {
61    my ($filename) = @_;
62    my ($data,$kix,$kiy,$kiz,$kfx,$kfy,$kfz,$x,$y,$z,$pi,$pf);
63    my ($size,$ki,$kf,$q,$qx,$qy,$qz,$p,$Ei,$Ef,$w);
64    my ($r,$qx_mc,$qy_mc,$qz_mc,$w_mc, $npts,$cntr,$gaus);
65    my ($ave_q,$unit_q,$unit_n,$unit_z,$tmat,$q_t);
66    my ($A,$ave_A,$mid_A,$C,$umat,$C_t,$res_mat);
67    my ($pos);
68
69    # Read data from file (either raw or ascii).
70    if($filename =~ /\.raw$/) {
71        $data = readfraw($filename);
72        ($kix,$kiy,$kiz,$kfx,$kfy,$kfz,$x,$y,$z,$pi,$pf) = dog $data;
73    } else {
74        ($kix,$kiy,$kiz,$kfx,$kfy,$kfz,$x,$y,$z,$pi,$pf) = rcols($filename);
75        $data = cat ($kix,$kiy,$kiz,$kfx,$kfy,$kfz,$x,$y,$z,$pi,$pf);
76    }
77    # Compute some basic entities
78    ($size) = $kix->dims;
79    $ki = cat($kix, $kiy, $kiz);
80    $kf = cat($kfx, $kfy, $kfz);
81    $q = $ki - $kf;
82    $Ei = 2.072*($kix*$kix+$kiy*$kiy+$kiz*$kiz);
83    $Ef = 2.072*($kfx*$kfx+$kfy*$kfy+$kfz*$kfz);
84    $w = $Ei-$Ef;
85    $p = $pi*$pf;
86    # Compute coordinate change: X along average Q vector projected
87    # into plane, Y perpendicular to X in plane, Z upwards.
88    $ave_q = sumover($q*$p->dummy(1,3)) / (sum($p));
89    $unit_q = $ave_q->copy;
90    $unit_q->set(1,0);                # Force into scattering plane.
91    $unit_q /= sqrt(inner($unit_q,$unit_q));
92    $unit_n = pdl($unit_q->at(2), 0, -$unit_q->at(0));
93    $unit_z = pdl(0,1,0);
94    # Build orthogonal transformation matrix, and change coordinates of Q.
95    $tmat = cat ($unit_q, $unit_n, $unit_z);
96    $q_t = xchg(PDL::Primitive::matmult($tmat,$q->dummy(2)),1,2);
97    $q_t = $q_t->clump(2);
98    ($qx,$qy,$qz) = dog $q_t;
99
100    # Now compute resolution matrix.
101    $A = append($q->transpose, $w->dummy(0));
102    $ave_A = sumover($A->transpose*$p->dummy(1,4)) / sum($p);
103    $mid_A = $A - $ave_A->dummy(1);
104    # Get the covariance matrix in original coordinates.
105    $C = PDL::Primitive::matmult
106        ($mid_A->transpose, $mid_A*$p->dummy(0,4)) / sum($p);
107    # Change coordinates, and compute the resolution matrix.
108    $umat = transpose(append(transpose(append($tmat,pdl [0])),
109                             pdl [[0],[0],[0],[1]]));
110    $C_t = inner2t($umat->transpose,$C,$umat);
111    $res_mat = $C_t->matinv;
112    print "The covariance matrix is\n";
113    print $C_t;
114    print "and the resolution matrix is\n";
115    print $res_mat;
116    print "Gaussian half width [Qx Qy Qz En] in Angs-1 and meV are\n";
117    $gqx = int(2.3548/sqrt($res_mat->at(0,0))*1e4)/1e4;
118    $gqy = int(2.3548/sqrt($res_mat->at(1,1))*1e4)/1e4;
119    $gqz = int(2.3548/sqrt($res_mat->at(2,2))*1e4)/1e4;
120    $gen = int(2.3548/sqrt($res_mat->at(3,3))*1e4)/1e4;
121    print "[$gqx $gqy $gqz $gen]\n";
122
123    return($qx,$qy,$qz,$w,$p,$C_t,$res_mat,$size);
124}
125
126sub plot_mcstas_res {
127  my ($filename,$device,$qx,$qy,$qz,$w,$p,$C_t,$res_mat,$size,$interactive,$si) = @_;
128  # Plot histograms for the four 1-d projections.
129    if (defined(&dev)) { $dev = dev "$device",4,2; }
130    else { $dev = pgopen("$device"); pgsubp(4,2); }
131    die "DEV/PGOPEN $device failed!" unless $dev > 0;
132
133    pgsch(2.1);
134    pgsci(1);
135
136    # Make a 3d visualization of the resolution elipsoid. Use MC
137    # choice to eliminate the weights.
138    $r = random $size;
139    $qx_mc = $qx->where($p > $r*max($p));
140    $qy_mc = $qy->where($p > $r*max($p));
141    $qz_mc = $qz->where($p > $r*max($p));
142    $w_mc = $w->where($p > $r*max($p));
143    $npts = $w_mc->nelem;
144    $R0 = 1;
145    $NP = $res_mat;
146
147    # plot 2D histograms, and add the gaussian ellipsoid on top of each
148    pgpanl(1,1);
149    q_hist2($qx_mc, $w_mc, "Q\\dx\\u [\\A\\u-1\\d]","\\gw [meV]",50,0);
150    mcs_proj($R0,$NP,1, $qx_mc->sum/$npts, $w_mc->sum/$npts, pdl([0,1,3]),pdl([0,3]));
151
152    pgpanl(2,1);
153    q_hist2($qy_mc, $w_mc, "Q\\dy\\u [\\A\\u-1\\d]","\\gw [meV]",50,0);
154    mcs_proj($R0,$NP,0, $qy_mc->sum/$npts, $w_mc->sum/$npts, pdl([0,1,3]),pdl([1,3]));
155
156    pgpanl(3,1);
157    q_hist2($qz_mc, $w_mc, "Q\\dz\\u [\\A\\u-1\\d]","\\gw [meV]",50,0);
158    mcs_proj($R0,$NP,0, $qz_mc->sum/$npts, $w_mc->sum/$npts, pdl([0,2,3]),pdl([2,3]));
159
160    pgpanl(4,1);
161    q_hist2($qx_mc, $qy_mc, "Q\\dx\\u [\\A\\u-1\\d]","Q\\dy\\u [\\A\\u-1\\d]",50,1);
162    mcs_proj($R0,$NP,2, $qx_mc->sum/$npts, $qy_mc->sum/$npts,pdl([0,1,3]),pdl([0,1]));
163
164
165    pgpanl(1,2);
166    my $offset=-1;
167    pgmtxt("t",$offset-0*1.2,.0,0.0,"Bragg (Gaussian) Half Widths");
168    pgmtxt("t",$offset-1*1.2,0.2,0.0,"\\gDQ\\dx\\u = " .
169           int(2.3548/sqrt($res_mat->at(0,0))*1e4)/1e4 . " \\A\\u-1\\d");
170    pgmtxt("t",$offset-2*1.2,0.2,0.0,"\\gDQ\\dy\\u = " .
171           int(2.3548/sqrt($res_mat->at(1,1))*1e4)/1e4 . " \\A\\u-1\\d");
172    pgmtxt("t",$offset-3*1.2,0.2,0.0,"\\gDQ\\dz\\u = " .
173           int(2.3548/sqrt($res_mat->at(2,2))*1e4)/1e4 . " \\A\\u-1\\d");
174    pgmtxt("t",$offset-4*1.2,0.2,0.0,"\\gD\\gw = " .
175           int(2.3548/sqrt($res_mat->at(3,3))*1e4)/1e4 . " meV");
176
177    pgmtxt("t",$offset-6*1.2,0.0,0.0,"Resolution matrix [Q\\dx\\u Q\\dy\\u Q\\dz\\u \\gw]:");
178    $pos = matout($offset-7*1.2, $res_mat);
179    pgmtxt("t",$pos+$offset-0*1.2,.0,0.0,"Covariance matrix [Q\\dx\\u Q\\dy\\u Q\\dz\\u \\gw]:");
180    $pos = matout($pos+$offset-1*1.2, $C_t);
181
182    pgpanl(2,2);
183    pgmtxt("t",$offset-0*1.2,0.0,0.0,"File: $filename");
184    my $time=gmtime;
185    pgmtxt("t",$offset-1*1.2,0.0,0.0,"Date: $time");
186    pgmtxt("t",$offset-2*1.2,0.0,0.0,"X along <Q> in plane");
187    pgmtxt("t",$offset-3*1.2,0.0,0.0,"Y perp. to X in plane, Z upwards");
188
189    pgpanl(3,2);
190
191    my $i;
192    my $j=0;
193    my $shift=0.0;
194    pgmtxt("t",$offset,0.0,0.0,"Instrument simulation parameters:");
195    foreach $i (keys %{$si->{'Params'}}) {
196      $j = $j+1;
197      pgmtxt("t",$offset-$j*1.2,$shift,0.0,$i . " = " . $si->{'Params'}{$i});
198      if ($j > 20) { $shift = $shift+0.5; $j=0; }
199    }
200    if ($j == 0 && $shift == 0) { pgmtxt("t",$offset-2*1.2,0.0,0.0,"None"); }
201}
202
203sub chol {
204    my ($A) = @_;
205    my ($i,$j,$k,$L,$n,$n2,$li,$lj,$v);
206
207    ($n,$n2) = $A->dims;
208    die "Must be square matrix" unless $n==$n2;
209    $L = zeroes $n,$n;
210    $li = $lj = pdl [];                # Handle special case for i=0
211    for($i=0; $i<$n; $i++) {
212        $li = $L->mslice([0,$i-1],[$i]) if $i;
213        $v = $A->at($i,$i) - sum($li*$li);
214        die "Not positive definite" unless $v >= 0;
215        $L->set($i,$i, sqrt($v));
216        for($j=$i+1; $j<$n; $j++) {
217            $lj = $L->mslice([0,$i-1],[$j]) if $i;
218            $L->set($i,$j, ($A->at($i,$j) - sum($li*$lj))/$L->at($i,$i));
219        }
220    }
221    return $L;
222}
223
224sub q_hist2 {
225    my ($x,$y,$xl,$yl,$npts,$plot_wedge) = @_;
226    ($xmin,$xmax) = minmax($x);
227    ($ymin,$ymax) = minmax($y);
228    $dx=($xmax-$xmin)/$npts;
229    $dy=($ymax-$ymin)/$npts;
230    my $tr;
231    if (defined(&label_axes))
232    { $tr = pdl [$xmin + $dx/2, $dx, 0, $ymin + $dy/2, 0, $dy]; }
233    else
234    { $tr = cat $xmin + $dx/2, $dx, pdl(0), $ymin + $dy/2, pdl(0), $dy; }
235    $hxy = histogram2d($x, $y, $dx, $xmin, $npts, $dy, $ymin, $npts);
236    my ($min, $max) = (min($hxy), max($hxy));
237    if ($min == $max) {
238      if($min == 0) {
239          $max = 1;
240      } else {
241          $min = 0.9*$min;
242          $max = 0.9*$max;
243      }
244    }
245    my $ramp = pdl [[ 0,  1/8,  3/8,  5/8,  7/8,  8/8],
246                [ 0,    0,    0,    1,    1,   .5],
247                [ 0,    0,    1,    1,    0,    0],
248                [.5,    1,    1,    0,    0,    0]];
249    my $numcol = 64;
250    # now do the plottings
251    pgswin($xmin,$xmax,$ymin,$ymax);
252    pgscir(16,16+$numcol-1);
253    ctab $ramp;
254    # If using the black&white postscript driver, swap foreground and
255    # background when doing the image to get more printer-friendly
256    # output.
257    my ($buf, $len);
258    my ($r0, $g0, $b0, $r1, $g1, $b1);
259    pgqinf("TYPE", $buf, $len);
260    if($buf =~ /^V?PS$/i) {
261      pgqcr(0, $r0, $g0, $b0);
262      pgqcr(1, $r1, $g1, $b1);
263      pgscr(0, $r1, $g1, $b1);
264      pgscr(1, $r0, $g0, $b0);
265    }
266    imag $hxy, $min, $max, $tr;
267    if ($plot_wedge) { pgwedg("RI", 0.5, 3.0, $min, $max, ' '); }
268    if($buf =~ /^V?PS$/i) {
269      pgscr(0, $r0, $g0, $b0);
270      pgscr(1, $r1, $g1, $b1);
271    }
272    pglab($xl, $yl,"");
273}
274
275sub matout {
276    my ($pos,$x) = @_;
277    my @lines = split("\n","$x");
278#    shift(@lines);shift(@lines);pop(@lines);
279    for(@lines) {
280        if(m'\[([^]]*)\]') {
281            pgmtxt("t",$pos,0.0,0.0,$1);
282            $pos-= 1.2;
283        }
284    }
285    return $pos;
286}
287
288# The rest of this file is converted from rescal5 matlab code.
289sub rot_elip {
290    my ($a,$b,$phi) = @_;
291    my($n,$x,$y,$s,$c,$th);
292
293    $n = 100;
294    $th = sequence($n+1)/$n*2*$PI;
295    $x = $a*cos($th);
296    $y = $b*sin($th);
297    $c = cos($phi);
298    $s = sin($phi);
299    $th = $x*$c - $y*$s;
300    $y = $x*$s + $y*$c;
301    $x = $th;
302    return ($x,$y);
303}
304
305sub rc_int {
306    my ($i,$r0,$m) = @_;
307    my ($n1,$n2,$r,$sel,$b,$mp,$new);
308
309    ($n1,$n2) = $m->dims;
310    die "Must have square input matrix" unless $n1==$n2;
311    $r = sqrt(2*$PI/$m->at($i,$i))*$r0;
312    $sel = pdl [0..$i-1,$i+1..$n1-1];
313    $b = $m->slice(",($i)") + $m->slice("($i),");
314    $b = $b->dice($sel);
315
316    $mp = zeroes $n1-1,$n2-1;
317    if($i > 0) {
318        $mp = $mp->ins($m->mslice([0,$i-1],[0,$i-1]),0,0);
319    }
320    if($i < $n1 - 1) {
321        $mp = $mp->ins($m->mslice([$i+1,$n1-1],[$i+1,$n2-1]),$i,$i);
322    }
323    if($i > 0 && $i < $n1 - 1) {
324        $mp = $mp->ins($m->mslice([0,$i-1],[$i+1,$n2-1]),0,$i);
325        $mp = $mp->ins($m->mslice([$i+1,$n1-1],[0,$i-1]),$i,0);
326    }
327    $new = $mp - 1/(4*$m->at($i,$i))*
328      PDL::Primitive::matmult($b->dummy(0),$b->dummy(1));
329    return ($r, $new);
330}
331
332
333
334sub mcs_proj {
335    my ($R0,$A,$index,$x0,$y0,$sel1,$sel2) = @_;
336    my($B,$R0P,$MP,$x,$y);
337
338    $B = $A->dice($sel1,$sel1);
339    ($R0P,$MP) = rc_int($index,$R0,$B);
340    ($x,$y) = proj_elip($MP);
341    #poly($x,$y, {COLOUR => RED});
342    hold;
343    line($x+$x0,$y+$y0,{COLOUR => BLACK});
344    ($x,$y) = proj_elip($A->dice($sel2,$sel2));
345    #poly($x,$y, {COLOUR => GREEN});
346    line($x+$x0,$y+$y0,{COLOUR => BLACK, LINESTYLE => 'DOT-DASH'});
347    rel;
348}
349
350sub proj_elip {
351    my ($MP) = @_;
352    my ($const,$theta,$S,$MP2,$hwhm_xp,$hwhm_yp,$x,$y);
353
354    $const = 1.17741;
355    $theta = 0.5*atan(2*$MP->at(0,1)/($MP->at(0,0)-$MP->at(1,1)));
356    $S = cat(cat(cos($theta),  sin($theta)),
357             cat(-sin($theta), cos($theta)));
358    $MP2 = inner2t($S->transpose,$MP,$S);
359    $hwhm_xp=$const/sqrt($MP2->at(0,0));
360    $hwhm_yp=$const/sqrt($MP2->at(1,1));
361    ($x,$y) = rot_elip($hwhm_xp,$hwhm_yp,$theta);
362    return ($x,$y);
363}
364
365# Start of mcresplot program =====================================================
366
367my $cc;
368my $filename;
369my $interactive=1;
370for($i = 0; $i < @ARGV; $i++) {
371        $_ = $ARGV[$i];
372  # Options specific to mcplot.
373        if(/^-psc$/ || /^-c$/) {
374            $cc = "c"; $interactive=0;
375        } elsif(/^-ps$/ || /^-p$/) {
376            $cc = "p"; $interactive=0;
377        } elsif(/^-gif$/ || /^-g$/) {
378            $cc = "g"; $interactive=0;
379  } elsif(/^--help$/ || /^-h$/ || /^-v$/) {
380      print "mcresplot [-ps|-psc|-gif|-v] <FILE from Res_monitor>\n";
381      print "  The FILE to be used by mcresplot is generated when using Res_sample\n";
382      print "  at the sample position, and Res_monitor afterwards.\n";
383      print "  Plots the instrument resolution function (projections).\n";
384      print "  When using -ps -psc -gif, the program writes the hardcopy file\n";
385      print "  and then exits.\n";
386      print "SEE ALSO: mcstas, mcdoc, mcplot, mcrun, mcgui, mcresplot, mcstas2vitess\n";
387      print "DOC:      Please visit http://www.mcstas.org/\n";
388      exit;
389        } else {
390      $filename = $ARGV[$i];
391  }
392}
393die "mcresplot <file name from Res_monitor>\n" unless @ARGV;
394
395#read resolution data
396my ($qx,$qy,$qz,$w,$p,$C_t,$res_mat,$size) = read_mcstas_res($filename);
397# now get parameter list (if any)
398my $simulation_info;
399$simulation_info =read_mcstas_info($filename);
400# now either output direct and exit, or plot xwin and wait for exit
401if ($interactive) {
402  print "Type 'P' 'C' or 'G' (in graphics window) for hardcopy, 'Q' to quit.\n";
403}
404for (;;) {
405  if($cc =~ /[pcg]/i) {        # Hardcopy?
406        my $ext="ps";
407        my $dev = ($cc =~ /c/i) ? "cps" : "ps";
408        if($cc =~ /g/i) { $dev = "gif"; $ext="gif"; }
409        my $fileout = "$filename.$ext";
410        plot_mcstas_res($filename, "$fileout/$dev", $qx,$qy,$qz,$w,$p,$C_t,$res_mat,$size,0,$simulation_info);
411        print "Wrote file '$fileout' ($dev)\n";
412      }
413  if ($interactive == 0) { $cc = "q"; }
414  else {
415    my ($ax,$ay,$cx,$cy) = (0,0,0,0);
416    plot_mcstas_res($filename, "/xwin", $qx,$qy,$qz,$w,$p,$C_t,$res_mat,$size,1,$simulation_info);
417    pgband(0, 0, $ax, $ay, $cx, $cy, $cc);
418  }
419  last if $cc =~ /[xq]/i;
420}
421if (defined(&close_window)) { close_window(); }
422      else { pgclos(); }
423
4241;
Note: See TracBrowser for help on using the browser.