Physics/Ellipsometry/VASE/Parameter.pm untested

filter: Statementstmt 0.0% 0 / 71 Branchbran 0.0% 0 / 26 Conditioncond 0.0% 0 / 16 MC/DCmcdc 0.0% 0 / 6 Subroutinesub 0.0% 0 / 11 Podpod 0.0% 0 / 7 totaltotal 0.0% 0 / 137 CC 14 SCAR 33.8
CC
14
Cov
0%
_value_to_internal
72.0
_internal_to_value
20.0
params_to_pdl
6.0
CRAP 29.3
1 package Physics::Ellipsometry::VASE::Parameter;
2 use strict;
3 use warnings;
4 use PDL;
5 use Exporter 'import';
6  
7 our @EXPORT_OK = qw(param params_to_pdl pdl_to_params make_fit_model get_values);
8  
9 our $VERSION = '1.04';
10  
11 =encoding utf8
12  
13 =head1 NAME
14  
15 Physics::Ellipsometry::VASE::Parameter - Named parameters with bounds,
16 vary/fix control, and internal transformations for model fitting
17  
18 =head1 SYNOPSIS
19  
20 use PDL;
21 use Physics::Ellipsometry::VASE;
22 use Physics::Ellipsometry::VASE::Parameter qw(
23 param params_to_pdl pdl_to_params make_fit_model get_values
24 );
25  
26 # Define model parameters with physical constraints
27 my @params = (
28 param(name => 'thickness', value => 100.0,
29 min => 0.0, max => 500.0),
30 param(name => 'n_cauchy_A', value => 2.1,
31 min => 1.0, max => 4.0),
32 param(name => 'n_cauchy_B', value => 0.01,
33 min => 0.0, max => 1.0),
34 param(name => 'angle_offset', value => 0.0, vary => 0), # fixed
35 );
36  
37 # Convert varying parameters to a PDL for fitting
38 my $p0 = params_to_pdl(\@params); # 3-element piddle (angle_offset excluded)
39  
40 # After fitting, update parameter values from the fitted PDL
41 pdl_to_params(\@params, $fitted_pdl);
42  
43 # Read back all values (fixed and varying)
44 my @values = get_values(\@params);
45 printf "thickness = %.2f nm\n", $values[0];
46  
47 =head1 DESCRIPTION
48  
49 Levenberg-Marquardt fitting operates on an unconstrained vector of real
50 numbers, but physical model parameters often have hard constraints:
51 thicknesses cannot be negative, refractive indices must stay within
52 sensible ranges, and some parameters (e.g., a known substrate angle)
53 should be held fixed during the fit.
54  
55 Physics::Ellipsometry::VASE::Parameter provides a lightweight parameter
56 object that addresses these needs:
57  
58 =over 4
59  
60 =item B<Named parameters>
61  
62 Each parameter carries a human-readable name for identification in
63 reports and diagnostics.
64  
65 =item B<Bounds enforcement via smooth transformations>
66  
67 Rather than clamping (which creates discontinuous derivatives and
68 confuses gradient-based optimizers), bounded parameters are mapped to
69 an unbounded internal space using invertible transformations:
70  
71 =over 4
72  
73 =item I<Two-sided bounds> (min and max) — logit transform:
74  
75 internal = ln( (v − min) / (max − v) )
76  
77 =item I<Lower bound only> — log transform:
78  
79 internal = ln( v − min )
80  
81 =item I<Upper bound only> — negative log transform:
82  
83 internal = −ln( max − v )
84  
85 =back
86  
87 The optimizer works in internal space where all parameters are
88 unconstrained. The transforms are smooth (C∞), so the Jacobian
89 computed by finite differences remains well-behaved near the bounds.
90  
91 =item B<Vary/fix control>
92  
93 Parameters with C<< vary => 0 >> are held at their current value and
94 excluded from the fitted PDL vector. This lets you freeze known
95 quantities (e.g., substrate optical constants) without rewriting the
96 model function.
97  
98 =item B<Scaling>
99  
100 An optional C<scale> factor adjusts the internal representation for
101 numerical conditioning. This is useful when parameters span very
102 different orders of magnitude.
103  
104 =back
105  
106 =head1 FUNCTIONS
107  
108 =head2 param
109  
110 my $p = param(
111 name => 'thickness',
112 value => 100.0,
113 min => 0.0,
114 max => 500.0,
115 vary => 1,
116 scale => 1.0,
117 );
118  
119 Creates a parameter hashref. All keyword arguments are optional:
120  
121 =over 4
122  
123 =item C<name> — descriptive name (default: C<'unnamed'>)
124  
125 =item C<value> — current value (default: 0.0)
126  
127 =item C<min> — lower bound, or C<undef> for unbounded below
128  
129 =item C<max> — upper bound, or C<undef> for unbounded above
130  
131 =item C<vary> — 1 to vary during fitting, 0 to hold fixed (default: 1)
132  
133 =item C<scale> — internal scaling factor (default: 1.0)
134  
135 =back
136  
137 # Unbounded parameter
138 param(name => 'offset', value => 0.5)
139  
140 # Lower-bounded only (e.g., thickness ≥ 0)
141 param(name => 'thickness', value => 50.0, min => 0.0)
142  
143 # Fixed parameter (excluded from fit)
144 param(name => 'angle', value => 70.0, vary => 0)
145  
146 =head2 params_to_pdl
147  
148 my $pdl = params_to_pdl(\@params);
149  
150 Extracts the B<varying> parameters from the list, transforms each to
151 its internal (unbounded) representation, and returns a 1-D PDL piddle
152 suitable for passing to the fitter. Fixed parameters are skipped.
153  
154 =head2 pdl_to_params
155  
156 pdl_to_params(\@params, $fitted_pdl);
157  
158 The inverse of L</params_to_pdl>. Takes a fitted PDL of internal
159 values and maps each back to physical space, updating the C<value>
160 field of each varying parameter in-place. Fixed parameters are
161 unchanged.
162  
163 =head2 get_values
164  
165 my @vals = get_values(\@params);
166  
167 Returns the current C<value> of every parameter (both fixed and
168 varying), preserving order. Convenient for building a full parameter
169 PDL or for printing a summary.
170  
171 =head2 make_fit_model
172  
173 my $wrapped = make_fit_model(\@params, \&full_model);
174  
175 Creates a closure that bridges the gap between the fitter (which sees
176 only varying parameters in internal space) and the user's model
177 function (which expects the full physical parameter vector).
178  
179 The returned closure has the signature expected by
180 L<Physics::Ellipsometry::VASE/fit>:
181  
182 $wrapped->($vary_pdl, $x_data) → $y_pdl
183  
184 Internally it:
185  
186 =over 4
187  
188 =item 1.
189  
190 Transforms each element of C<$vary_pdl> from internal to physical
191 space using the inverse bound transform.
192  
193 =item 2.
194  
195 Inserts fixed parameter values at the correct positions.
196  
197 =item 3.
198  
199 Calls C<$full_model-E<gt>($all_params_pdl, $x_data)>.
200  
201 =back
202  
203 =head1 COMPLETE FITTING EXAMPLE
204  
205 use PDL;
206 use Physics::Ellipsometry::VASE;
207 use Physics::Ellipsometry::VASE::Parameter qw(
208 param params_to_pdl pdl_to_params make_fit_model get_values
209 );
210  
211 # 1. Define parameters with physical bounds
212 my @params = (
213 param(name => 'd', value => 80.0, min => 0, max => 500),
214 param(name => 'A', value => 2.0, min => 1, max => 4),
215 param(name => 'B', value => 0.01, min => 0, max => 1),
216 param(name => 'C', value => 0.0, vary => 0), # fix at zero
217 );
218  
219 # 2. Write the model in terms of a full parameter vector
220 sub my_model {
221 my ($all_p, $x) = @_;
222 my ($d, $A, $B, $C) = ($all_p->at(0), $all_p->at(1),
223 $all_p->at(2), $all_p->at(3));
224 # ... compute psi, delta using TMM ...
225 return cat($psi, $delta)->flat;
226 }
227  
228 # 3. Wrap the model to handle bounds and fixed params
229 my $wrapped = make_fit_model(\@params, \&my_model);
230  
231 # 4. Fit — optimizer sees only 3 unconstrained variables
232 my $vase = Physics::Ellipsometry::VASE->new(layers => 1);
233 $vase->load_data('sample.dat');
234 $vase->set_model($wrapped);
235  
236 my $p0 = params_to_pdl(\@params);
237 my $fitted = $vase->fit($p0);
238  
239 # 5. Map fitted values back to physical space
240 pdl_to_params(\@params, $fitted);
241 for my $p (@params) {
242 printf "%-12s = %8.4f %s\n",
243 $p->{name}, $p->{value},
244 $p->{vary} ? '' : '(fixed)';
245 }
246  
247 =head1 SEE ALSO
248  
249 L<Physics::Ellipsometry::VASE>,
250 L<Physics::Ellipsometry::VASE::Optimizer>
251  
252 =cut
253  
254 sub param {
255 my (%args) = @_;
256 return {
257 name => $args{name} // 'unnamed',
258 value => $args{value} // 0.0,
259 min => $args{min}, # undef = unbounded below
260 max => $args{max}, # undef = unbounded above
261 vary => $args{vary} // 1, # 1=vary, 0=fixed
262 scale => $args{scale} // 1.0, # internal scaling factor
263 };
264 }
265  
266 # Convert parameter list to internal PDL for fitting (only varying params)
267 sub params_to_pdl {
268 my ($params) = @_; # arrayref of param hashes
269 my @values;
270 for my $p (@$params) {
271 next unless $p->{vary};
272 my $internal = _value_to_internal($p);
273 push @values, $internal;
274 }
275 return pdl(\@values);
276 }
277  
278 # Update parameter list from fitted PDL values
279 sub pdl_to_params {
280 my ($params, $fitted_pdl) = @_;
281 my $idx = 0;
282 for my $p (@$params) {
283 next unless $p->{vary};
284 my $internal = $fitted_pdl->at($idx);
285 $p->{value} = _internal_to_value($p, $internal);
286 $idx++;
287 }
288 return $params;
289 }
290  
291 # Get all parameter values as a list (both fixed and varying)
292 sub get_values {
293 my ($params) = @_;
294 return map { $_->{value} } @$params;
295 }
296  
297 # Create a model wrapper that handles parameter transformation
298 # Returns a closure compatible with VASE fit()
299 sub make_fit_model {
300 my ($params, $full_model) = @_;
301 # $full_model receives ($all_values_pdl, $x_data)
302 # Returns wrapper that receives ($vary_pdl, $x_data)
303  
304 return sub {
305 my ($vary_pdl, $x_data) = @_;
306 # Reconstruct full parameter vector
307 my @all_values;
308 my $vary_idx = 0;
309 for my $p (@$params) {
310 if ($p->{vary}) {
311 my $internal = $vary_pdl->at($vary_idx);
312 push @all_values, _internal_to_value($p, $internal);
313 $vary_idx++;
314 } else {
315 push @all_values, $p->{value};
316 }
317 }
318 my $all_pdl = pdl(\@all_values);
319 return &$full_model($all_pdl, $x_data);
320 };
321 }
322  
323 # Transform value to internal (unbounded) space for fitting
324 sub _value_to_internal {
325 my ($p) = @_;
326 my $v = $p->{value};
327  
328 if (defined $p->{min} && defined $p->{max}) {
329 # Bounded: use logit transform
330 my $range = $p->{max} - $p->{min};
331 my $norm = ($v - $p->{min}) / $range;
332 # Clamp to avoid log(0)
333 $norm = 0.001 if $norm < 0.001;
334 $norm = 0.999 if $norm > 0.999;
335 return log($norm / (1.0 - $norm)) * $p->{scale};
336 } elsif (defined $p->{min}) {
337 # Lower bounded: use log transform
338 my $shifted = $v - $p->{min};
339 $shifted = 0.001 if $shifted < 0.001;
340 return log($shifted) * $p->{scale};
341 } elsif (defined $p->{max}) {
342 # Upper bounded: use negative log transform
343 my $shifted = $p->{max} - $v;
344 $shifted = 0.001 if $shifted < 0.001;
345 return -log($shifted) * $p->{scale};
346 } else {
347 # Unbounded
348 return $v * $p->{scale};
349 }
350 }
351  
352 # Transform from internal (unbounded) space back to actual value
353 sub _internal_to_value {
354 my ($p, $internal) = @_;
355 my $x = $internal / ($p->{scale} || 1.0);
356  
357 if (defined $p->{min} && defined $p->{max}) {
358 # Inverse logit (sigmoid)
359 my $range = $p->{max} - $p->{min};
360 my $sigmoid = 1.0 / (1.0 + exp(-$x));
361 return $p->{min} + $range * $sigmoid;
362 } elsif (defined $p->{min}) {
363 # Inverse log
364 return $p->{min} + exp($x);
365 } elsif (defined $p->{max}) {
366 # Inverse negative log
367 return $p->{max} - exp(-$x);
368 } else {
369 # Unbounded
370 return $x;
371 }
372 }
373  
374 1;