UEMColumn.pm

filter: Statementstmt 88.8% 16 / 18 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 6 / 6 Podpod n/a totaltotal 91.6% 22 / 24 CC 1 SCAR 0.5
CC
1
Cov
89%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« UEMColumn/RFCavity.pm ↑ Summary
1 package Physics::UEMColumn;
2  
3 our $VERSION = '0.901';
4 $VERSION = eval $VERSION;
5  
6 =head1 NAME
7  
8 Physics::UEMColumn - An Implementation of the Analytic Gaussian (AG) Model for Ultrafast Electron Pulse Propagation
9  
10 =head1 SYNOPSIS
11  
12 use strict;
13 use warnings;
14  
15 use Physics::UEMColumn alias => ':standard';
16 use Physics::UEMColumn::Auxiliary ':constants';
17  
18 my $pulse = Pulse->new(
19 number => 1e8,
20 velocity => '1e8 m/s',
21 sigma_t => 100 ** 2 / 2 . 'um^2',
22 sigma_z => 50 ** 2 / 2 . 'um^2',
23 eta_t => me * 5.3 / 3 * 0.5 / 10 . 'kg eV',
24 );
25  
26 my $column = Column->new(
27 length => '100 cm',
28 );
29  
30 my $sim = Physics::UEMColumn->new(
31 column => $column,
32 pulse => $pulse,
33 );
34  
35 my $result = $sim->propagate;
36  
37 =head1 DESCRIPTION
38  
39 L<Physics::UEMColumn> is an implementation of the Analytic Gaussian (AG) electron pulse propagation model, presented by Michalik and Sipe (L<http://dx.doi.org/10.1063/1.2178855>) and extended by Berger and Schroeder (L<http://dx.doi.org/10.1063/1.3512847>).
40  
41 =head2 About the Model
42  
43 This extended model calculates the dynamics of electron pulse propagation for an ultrashort pulse of electrons (that is electron packets of short enough temporal length to be completely contained inside the acceleration region). These electrons are then subject to the internal repulsive Coulomb forces, as well as the external forces of acceleration regions, magnetic lenses and radio-frequency (RF) cavities.
44  
45 =head2 Caveats
46  
47 =over
48  
49 =item *
50  
51 The model is a self-similar Gaussian model, and therefore a mean-field model; futher the modeling of external forces is restricted to perfect lensing.
52  
53 =item *
54  
55 The equations governing the generation of pulse (and therefore the initial parameters), are as-yet unpublished, and unexplained. Should this not be preferable, one should manually create a L<Physics::UEMColumn::Pulse> object, rather than allowing the C<Physics::UEMColumn::Photocathode> object to create one automatically.
56  
57 =item *
58  
59 While sensible defaults have been given to the underlying solver's options (see L</solver_opts>, these defaults may not always produce a desired or physically correct output. Care should be taken to be ensure that the solver is setup correctly especially for the scales involved in your particular simulation.
60  
61 =back
62  
63 =head2 Examples
64  
65 Included in the source package is an F<examples> directory. Contained within is a system analogous to an optical Cooke triplet. After a Tantalum photocathode and the acceleration region, is a triplet composed of a magnetic lens, an RF cavity and another magnetic lens. The triplet is tuned to generate a three dimensional focus, presumably at the sample stage location. If available, the script then uses L<PDL> and L<PDL::Graphics::Prima> to plot the transverse (red) and longitudinal (green) HW1/eM beam widths. If those modules are not available the raw data is dumped to STDOUT as comma separated values.
66  
67 =head2 API Stability
68  
69 The author hopes that the user-facing API is stable. Unfortunately the internal and subclassing API are still likely to change; use with care.
70  
71 =head2 Units Handling
72  
73 L<Physics::UEMColumn> uses C<MooseX::Types::NumUnit> (and thus C<Physics::Unit>) to handle unit coercion. This allows units of different (but compatible) unit to be given to initialization directives. Those units are automatically coerced to the proper internal unit. Please note however that returned values are in the unit system used internally. That is to say, these coercions are an input convenience and not a choice of active unit system.
74  
75 L<Physics::Unit> is missing a few commonly used abbreviated units, for example C<fs> is unrecognized. It may be prudent to use the L<physics-unit> script to check a new unit for existence. In these cases, the long form of the unit (e.g. C<femtoseconds>) may be used. Such omissions may be filed as bugs on that module and will hopefully be present in subsequent releases.
76  
77 =cut
78  
79 2 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
80 2 ▶use namespace::autoclean;
Subroutine BEGIN: called CC=1 SCAR=0.0
81  
82 2 ▶use Method::Signatures;
Subroutine BEGIN: called CC=1 SCAR=0.0
83  
84 2 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
85 2 ▶use List::Util 'sum';
Subroutine BEGIN: called CC=1 SCAR=0.0
86  
87 0 ▶use PerlGSL::DiffEq;
Subroutine BEGIN: called CC=1 SCAR=2.6
88  
89 use Physics::UEMColumn::Column;
90 use Physics::UEMColumn::Pulse;
91 use Physics::UEMColumn::Laser;
92 use Physics::UEMColumn::Photocathode;
93  
94 #use Physics::UEMColumn::Element;
95 use Physics::UEMColumn::DCAccelerator;
96 use Physics::UEMColumn::MagneticLens;
97 use Physics::UEMColumn::RFCavity;
98  
99 use Physics::UEMColumn::Auxiliary ':all';
100  
101 use MooseX::Types::NumUnit qw/num_of_unit/;
102 my $seconds = num_of_unit('s');
103  
104 =head1 THE C<Physics::UEMColumn> CLASS
105  
106 Instances of the L<Physics::UEMColumn> class may be thought of as the "simulation" objects. The state of a simulation and all its constituent objects are stored in an instance of this class. It does not rely on any internal global state and thus several objects may be used simultaneously.
107  
108 =head2 Attributes
109  
110 L<Physics::UEMColumn> objects have certain properties which may be set during instantiation when passed as key value pairs to the C<new> method or may be accessed and possible changed via accessor methods of the same name. These attributes are as follows.
111  
112 =over
113  
114 =item C<debug>
115  
116 A testing parameter which might give additional output. At this early release stage, no specific output is guaranteed.
117  
118 =cut
119  
120 has 'debug' => ( isa => 'Num', is => 'ro', default => 0);
121  
122 =item C<number>
123  
124 The number of electrons to be generated. If no C<Pulse> object is available, this value is used for pulse generation.
125  
126 =cut
127  
128 has 'number' => ( isa => 'Num', is => 'rw', predicate => 'has_number');
129  
130 =item C<pulse>
131  
132 Holder for a L<Physics::UEMColumn::Pulse> object. If one is not given, an attempt will be made to generate one, if enough other information has been given. If generation of such an object is not possible an error message will be shown. Such an object must be present to simulate a column.
133  
134 =cut
135  
136 has 'pulse' => (
137 isa => 'Physics::UEMColumn::Pulse',
138 is => 'ro',
139 lazy => 1,
140 builder => '_generate_pulse',
141 predicate => 'has_pulse',
142 );
143  
144 =item C<column>
145  
146 Holder for a L<Physics::UEMColumn::Column> object. This object acts as a holder for other column elements and defines the total column length. This object is required.
147  
148 =cut
149  
150 has 'column' => (
151 isa => 'Physics::UEMColumn::Column',
152 is => 'ro',
153 required => 1,
154 handles => [ qw/ add_element / ],
155 );
156  
157 =item C<start_time>
158  
159 Initial time for the simulation, this is C<0> by default. Unit: seconds.
160  
161 =cut
162  
163 has 'start_time' => ( isa => $seconds, is => 'rw', default => 0 );
164  
165 =item C<end_time>
166  
167 The estimated time at which the simulation will be ended. In actuality the full simulation will end when the pulse has reached the end of the column. For performance reasons it is advantageous for this time to be long enough to reach the end of the simulation. If no value is given for this attribute, one will be estimated from known parameters. Unit: seconds.
168  
169 =cut
170  
171 has 'end_time' => ( isa => $seconds, is => 'rw', lazy => 1, builder => '_est_init_end_time' );
172  
173 =item C<steps>
174  
175 The requested number of time-step data points returned. This is neither the total number evaluations performed nor guaranteed to be the number of actual data points returned. This is more of a shorthand for specifying a step-width when the total duration is unknown. The default is C<100>. This number must be an integer.
176  
177 =cut
178  
179 has 'steps' => (isa => 'Int', is => 'rw', default => 100); # this is not likely to be the number of output steps
180  
181 =item C<step_width>
182  
183 The estimated duration of steps. This number is usually determined from the above parameters. This helps to create a uniform data spacing, even if multiple runs are needed to span the entire column. Unit: seconds.
184  
185 =cut
186  
187 has 'step_width' => ( isa => $seconds, is => 'ro', lazy => 1, builder => '_set_step_width' );
188  
189 =item C<time_error>
190  
191 A multiplicative factor used when estimating the simulation ending time. The default is C<1.1> or 10% additional time. Set to C<1> for no extra time.
192  
193 =cut
194  
195 has 'time_error' => ( isa => 'Num', is => 'ro', default => 1.1 );
196  
197 =item C<solver_opts>
198  
199 The options hashref passed directly to the C<ode_solver> from L<PerlGSL::DiffEq>. Unless explicitly changed, the options C<< h_max => 5e-12 >> and C<< h_init => 5e-13 >> are used.
200  
201 =cut
202  
203 has 'solver_opts' => ( isa => 'HashRef', is => 'rw', default => sub { {} } );
204  
205 =back
206  
207 =cut
208  
209 method BUILD ($param) {
210  
211 # check for proper combinations of inputs
212 unless ( $self->has_pulse or $self->column->can_make_pulse ) {
213 die "You must either provide a pulse object to the simulation object or else include laser, accelerator and photocathode objects to the column";
214 }
215  
216 if ( $self->has_pulse and $self->has_number ) {
217 carp "'number' attribute is superfluous (and ignored) when a pulse object is provided";
218 }
219  
220 unless ( $self->has_pulse or $self->has_number ) {
221 die "You must provide either a pulse object or a number of electrons to create";
222 }
223  
224 # initialize some solver options, if not specified
225 my $solver_opts = $self->solver_opts;
226
227 $solver_opts->{h_max} = exists $solver_opts->{h_max} ? $solver_opts->{h_max} : 5e-12;
228 $solver_opts->{h_init} = exists $solver_opts->{h_init} ? $solver_opts->{h_init} : 5e-13;
229 }
230  
231 method _generate_pulse () {
232 $self->column->photocathode->generate_pulse( $self->number );
233 }
234  
235 method _set_step_width () {
236 return ( ($self->end_time - $self->start_time) / $self->steps );
237 }
238  
239 method _est_init_end_time () {
240 my $t0 = $self->start_time;
241 my $tf = $t0;
242  
243 my $acc = $self->column->accelerator;
244  
245 # this test is a holdover, leaving in case I want to implement a Null Accelerator
246 # test should always succeed as acclerator is now a required attribute of the column
247 if ($acc) {
248 $tf += $acc->est_exit_time;
249 $tf += ( ($self->column->length() - $acc->length()) / $acc->est_exit_vel );
250 } else {
251 # otherwise use given velocity
252 $tf += $self->column->length() / $self->pulse->velocity;
253 }
254  
255 #add 10% error factor (time will be extended later if needed)
256 $tf *= $self->time_error;
257  
258 return $tf;
259 }
260  
261 =head2 Methods
262  
263 =over
264  
265 =item C<add_element>
266  
267 A pass-through convenience method which adds a given L<Physics::UEMColumn::Element> instance to the column. Therefore these two calls are exactly equivalent.
268  
269 $sim->column->add_element($elem);
270 $sim->add_element($elem);
271  
272 =item C<propagate>
273  
274 This method call begins the main simulation. It returns the result of this evaluation. Should a single pulse be propagated more than once the return will not include the results of the previous runs; the full propagation history will be available via the pulse's C<data> attribute.
275  
276 =back
277  
278 =cut
279  
280 method propagate () {
281  
282 my $iter = 0;
283 my $result = [];
284  
285 # continue to evaluate until pulse leaves column
286 while ($self->pulse->location < $self->column->length) {
287 $iter++;
288 warn "Segment iteration number: " . $iter . "\n" if $self->debug;
289  
290 my $segment_result = $self->_evaluate_single_run();
291 join_data( $result, $segment_result );
292 }
293
294 my $stored_data = $self->pulse->data;
295 join_data( $stored_data, $result );
296  
297 # return only this propagation result
298 # full data available from $pulse->data;
299 return $result;
300  
301 }
302  
303 method _evaluate_single_run () {
304 my $pulse = $self->pulse;
305 my $eqns = $self->_make_diffeqs;
306 my $start_time = $self->start_time;
307 my $end_time = $self->end_time;
308  
309 if ($end_time == $start_time) {
310 $end_time = $self->time_error * ($self->column->length - $pulse->location) / $self->pulse->velocity;
311 $self->end_time( $end_time );
312 }
313  
314 #logic here allows uniform step width over multiple runs
315 my $steps = int(0.5 + ($end_time - $start_time) / $self->step_width);
316  
317 #calculate the propagation on the specified time range
318 my $result;
319 {
320 local $SIG{__WARN__} = sub{ unless( $_[0] =~ /'ode_solver'/) { warn @_ } };
321 $result = ode_solver( $eqns, [ $start_time, $end_time, $steps ], $self->solver_opts);
322 }
323  
324 #update the simulation/pulse parameters from the result
325 #this sets up the next run if needed
326 my $end_state = $result->[-1];
327 $self->start_time($end_state->[0] );
328 $pulse->location( $end_state->[1] );
329 $pulse->velocity( $end_state->[2] );
330 $pulse->sigma_t( $end_state->[3] );
331 $pulse->sigma_z( $end_state->[4] );
332 #$pulse->eta_t( $end_state->[5] );
333 #$pulse->eta_z( $end_state->[6] );
334 $pulse->gamma_t( $end_state->[5] );
335 $pulse->gamma_z( $end_state->[6] );
336 $pulse->eta_t( $pulse->liouville_gamma2_t / $pulse->sigma_t );
337 $pulse->eta_z( $pulse->liouville_gamma2_z / $pulse->sigma_z );
338  
339 return $result;
340 }
341  
342 method _make_diffeqs () {
343 my @return;
344  
345 my $pulse = $self->pulse;
346 my $Ne = $pulse->number;
347 my $Cn = $Ne * (qe**2) / ( 24 * pi * epsilon_0 * sqrt(pi));
348 my $lg2_t = $pulse->liouville_gamma2_t;
349 my $lg2_z = $pulse->liouville_gamma2_z;
350  
351 my @init_conds = (
352 $pulse->location,
353 $pulse->velocity,
354 $pulse->sigma_t,
355 $pulse->sigma_z,
356 $pulse->gamma_t,
357 $pulse->gamma_z,
358 );
359  
360 #get the effect of all the elements in the column
361 my $elements = $self->column->elements;
362 my (@M_t, @M_z, @acc_z);
363 foreach my $effect (map { $_->effect } @$elements) {
364 push @M_t, $effect->{M_t} if defined $effect->{M_t};
365 push @M_z, $effect->{M_z} if defined $effect->{M_z};
366 push @acc_z, $effect->{acc} if defined $effect->{acc};
367 }
368  
369 ## Create DE Code Reference ##
370 my $eqns = sub {
371  
372 ## Initial Conditions ##
373  
374 unless (@_) {
375 return @init_conds;
376 }
377  
378 ## Parameters ##
379  
380 my ($t, $z, $v, $st, $sz, $gt, $gz) = @_;
381  
382 #if (1) { #make if $debug
383 # push @main::debug, [ $t, $z, $v, $st, $sz, $gt, $gz ];
384 #}
385  
386 if ($st < 0) {
387 warn "Sigma_t has gone negative at z=$z, t=$t\n";
388 return (undef) x 6;
389 }
390 if ($sz < 0) {
391 warn "Sigma_z has gone negative at z=$z, t=$t\n";
392 return (undef) x 6;
393 }
394  
395 my $M_t = sum map { $_->($t, $z, $v) } @M_t;
396 my $M_z = sum map { $_->($t, $z, $v) } @M_z;
397 my $acc_z = sum map { $_->($t, $z, $v) } @acc_z;
398  
399 #avoid "mathematical use of undef" warnings
400 $M_t ||= 0;
401 $M_z ||= 0;
402 $acc_z ||= 0;
403  
404 ## Setup Differentials ##
405  
406 my $dz = $v;
407 my $dv = $acc_z;
408  
409 my $dst = 2 * $gt / me;
410 my $dsz = 2 * $gz / me;
411  
412 my $dgt =
413 ($lg2_t + ($gt**2)) / ( me * $st )
414 + $Cn / sqrt($st) * L_t(sqrt($sz/$st))
415 - $M_t * $st;
416 my $dgz =
417 ($lg2_z + ($gz**2)) / ( me * $sz )
418 + $Cn / sqrt($sz) * L_z(sqrt($sz/$st))
419 - $M_z * $sz;
420  
421 return ($dz, $dv, $dst, $dsz, $dgt, $dgz);
422 };
423  
424 return $eqns;
425  
426 }
427  
428 =head1 IMPORTING
429  
430 =head1 Class Aliases
431  
432 Since this is an object oriented simulation, many classes are available to be instantiated, unfortunately many have rather long names. To prevent carpal tunnel syndrome, these classes may be aliased in the current package (via stub functions) to remove the leading namespace C<Physics::UEMColumn::>. To create these aliases, use the import directive C<alias>
433  
434 use Physics::UEMColumn alias => ':standard';
435  
436 The value of the alias directive can be an arrayref of strings of the names of the classes to be aliased, or else the special strings C<:all> (attempts to alias all classes) or C<:standard> (aliases the classes C<Laser Column Photocathode MagneticLens DCAccelerator RFCavity>).
437  
438 =cut
439  
440 sub import {
441 my $class = shift;
442 my $caller = caller;
443  
444 my %opts = ref $_[0] ? %{ shift() } : @_;
445  
446 if (exists $opts{alias} and $caller) {
447 $class->_setup_aliases( $caller, $opts{alias} );
448 }
449 }
450  
451 #hic sunt dracones
452 sub _setup_aliases {
453 my $class = shift;
454 my ($caller, $alias) = @_;
455  
456 # find all "classes" under Physics::UEMColumn and their short names
457 my %can_alias =
458 map { @$_ }
459 grep { $_->[1]->can('new') }
460 map { [ $_ => 'Physics::UEMColumn::' . $_ ] }
461 grep { s/::$// }
462 keys %Physics::UEMColumn::;
463  
464 # these are the classes that will be exported in place of the :standard tag
465 my @standard = ( qw/ Laser Column Photocathode MagneticLens DCAccelerator RFCavity / );
466  
467 # define requested aliases
468 my @to_alias = ref $alias ? @$alias : ( $alias );
469  
470 if ( $to_alias[0] eq ':standard' ) {
471 shift @to_alias;
472 unshift @to_alias, @standard;
473  
474 } elsif( $to_alias[0] eq ':all' ) {
475 @to_alias = keys %can_alias;
476 }
477  
478 # do the aliasing
479 for my $short ( @to_alias ) {
480 my $full = $can_alias{$short};
481
482 # check that requested alias is known
483 unless (defined $full) {
484 carp "Unknown alias requested ($short)";
485 next;
486 }
487  
488 no strict 'refs';
489 *{$caller . '::' . $short} = eval "sub () { '$full' }";
490 }
491 }
492  
493 __PACKAGE__->meta->make_immutable;
494  
495 1;
496  
497 =head1 SOURCE REPOSITORY
498  
499 L<http://github.com/jberger/Physics-UEMColumn>
500  
501 =head1 AUTHOR
502  
503 Joel Berger, E<lt>joel.a.berger@gmail.comE<gt>
504  
505 =head1 COPYRIGHT AND LICENSE
506  
507 Copyright (C) 2012-2013 by Joel Berger
508  
509 This library is free software; you can redistribute it and/or modify
510 it under the same terms as Perl itself.
511  
« UEMColumn/RFCavity.pm ↑ Summary