blib/lib/Statistics/GaussHelmert.pm

filter: Statementstmt 92.3% 24 / 26 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 9 / 9 Podpod n/a totaltotal 94.2% 33 / 35 CC 1 SCAR 0.3
CC
1
Cov
92%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
↑ Summary
1 package Statistics::GaussHelmert;
2  
3 =head1 NAME
4  
5 Statistics::GaussHelmert - General weighted least squares estimation
6  
7 =head1 VERSION
8  
9 This document refers to version 0.03
10  
11 =head1 SYNOPSIS
12  
13 use Statistics::GaussHelmert;
14  
15 # create an empty model
16 my $estimation = new Statistics::GaussHelmert;
17  
18 # setup the model given observations $y, covariance matrices
19 # $Sigma_yy, an initial guess $b0 for the unknown parameters.
20 $estimation->observations($y);
21 $estimation->covariance_observations($Sigma_yy);
22 $estimation->initial_guess($b0);
23  
24 # specify the implicit model function and its Jacobians by using
25 # closures.
26 $estimation->observation_equations(sub { ... });
27 $estimation->Jacobian_unknowns(sub { ... });
28 $estimation->Jacobian_observations(sub { ... });
29  
30 # Maybe we want to impose some constraints on the unknown
31 # parameters, this is not mandatory
32 $estimation->constraints(sub { ... });
33 $estimation->Jacobian_constraints(sub { ... });
34  
35 # start estimation
36 $estimation->start(verbose => 1);
37  
38 # print result
39 print $estimation->estimated_unknown(),
40 $estimation->covariance_unknown();
41  
42 =head1 DESCRIPTION
43  
44 This module is a flexible tool for estimating model parameters given a
45 set of observations. The module provides function for a linear
46 estimation model, the underlying model is called Gauss-Helmert model.
47  
48 Statistics::GaussHelmert is different to modules such as
49 Statistics::OLS in the sense that it may fit arbitrary functions to
50 data of any dimensions. You have to specify an implicit minimization
51 function (in contrast to explicit functions as in traditional
52 regression methods) and its derivatives with respects to the unknown
53 and the observations. You may also specify constraint function on the
54 unknowns (with its derivative). Furthermore you already need an
55 approximate solution. For some problems it is easy finding approximate
56 solutions by directly solving for the unknown parameters with some
57 well chosen observations.
58  
59 =head2 Setting up the model
60  
61 Assume you have a some measurements (or observations) which are
62 related to some unknown parameters that you want to know. For example,
63 you measure points in 2D which should lie on an unknown line.
64  
65 The points that you measure in 2D will be put in a L<PDL::Matrix>
66 object $y (a so-called multipiddle i.e. multi-PDL object, a vector of
67 vectors). The unknown parameter vector $b is again a L<PDL::Matrix>
68 object, just a vector. Additionally, you should have an idea on how
69 precise your measurements are and specify this in a covariance matrix
70 - actually again a multipiddle: a vector of matrices.
71  
72 Before you use this module to solve your problem, you first have to
73 sit down and calculate the equations which relate your observations
74 with the unknown parameters. The Gauss-Helmert model requires that you
75 specify this equation in the form w($y,$b) = 0, where $y are the
76 observations (lined up in a L<PDL::Matrix> vector of vectors, see
77 below) and $b is the unknown parameter vector. This equation w($y,$b)
78 = 0 is called "observation equation". Note that in general this is a
79 "vector equation", i.e. a set of scalar equations.
80  
81 Then you have to think about, what constraints you want to impose on
82 the unkown parameter vector $b. It could be that you want it to have
83 the (euclidean) length 1, or you want to set one parameter to a
84 certain value. So you specify a function of the form h($b) = 0, again
85 in general being a "vector equation".
86  
87 To do the minimization according to the model w($y,$b)=0 and h($b) =
88 0, you also need to specify the Jacobians of the observation function
89 w($y,$b) and the constraint function h($b). We need the Jacobians with
90 respect to the observation vector $y and the unknown vector $b. Right
91 now it is not possible to do numerical differentiation - in that case
92 the Jacobians wouldn't be needed.
93  
94 =head2 Coding the model
95  
96 Let us say you have an array @y of n different observation vectors,
97 each of the vectors being a PDL::Matrix vector, for example generated
98 by the special constructor vpdl from L<PDL::Matrix>. To put then in the
99 estimation, you have line them up in a multipiddle $y using $y =
100 PDL::cat(@y).
101  
102 The same applies for the set of covariance matrices @Sigma_yy for the
103 elements of the array @y.
104  
105 The observation function and its Jacobians (also the constraints on
106 the unknown and its Jacobians) may be defined as closures. The
107 Jacobian closures return L<PDL::Matrix> matrices, the dimensions
108 depend on the dimensions of the vectors in @y and $b.
109  
110 You may want to look at some examples in the t/ directory or the
111 example/ directory for more detailed information.
112  
113 Furthermore you may pass some options to the estimation:
114  
115 =over
116  
117 =item verbose() ; verbose(2) ; verbose("/path/to/my/logfile")
118  
119 If this variable is set to 1, a short protocol is printed on STDOUT,
120 If it is set to 2, a more elaborated output is written to the file
121 "./GaussHelmert.log". You may also pass a filename to verbose so the
122 elaborated output will go to this file.
123  
124 The value of verbose() defaults to 0, i.e. no output at all.
125  
126 =item max_iteration() ; max_iteration(10)
127  
128 returns or sets the maximum number of iteration which may be reached
129 if the abort criteria is not met. Default is 15.
130  
131 =item eps() ; eps($small_number)
132  
133 Returns or sets a small number which is used for the abort criteria of
134 the iteration. This refers to the largest difference of change that is
135 allowed in the unknown vector divided by its standard deviation. It
136 defaults to 10^(-2), this means we want to be within a precision of 1%
137 of the standard deviation.
138  
139 =back
140  
141 =head2 Estimation results
142  
143 You may now start and retrieve the results:
144  
145 =over
146  
147 =item start() ; start(verbose => 2)
148  
149 Starts the estimation and returns the object itself.
150  
151 =item estimated_unknown()
152  
153 returns the estimated unknown parameter vector as a PDL::Matrix
154 object.
155  
156 =item sigma0_squared()
157  
158 returns the estimated covariance factor.
159  
160 =item covariance_unknown()
161  
162 returns the estimated covariance matrix, without the covariance factor.
163  
164 =item estimated_observations()
165  
166 returns the fitted observations as a multipiddle.
167  
168 =item estimated_unknowns_iterations()
169  
170 returns a list of estimated unknown parameter vectors for each iteration.
171  
172 =item number_of_iterations()
173  
174 returns the used number of iterations.
175  
176 =back
177  
178 =head1 EXAMPLE USAGE
179  
180 See t/ and example/ folder (to be expanded).
181  
182 =head1 NOT YET DOCUMENTED
183  
184 There is a subclass Statistics::GaussHelmertBlocks, which can deal
185 with blocks of observation vectors. This is not documented yet, but
186 used in L<Math::UncertainGeometry>.
187  
188 =head1 LITERATURE
189  
190 =over
191  
192 =item Press et al. (1992) Numerical Recipes in C, 2nd Ed., Cambridge
193 University Press, Chapter 15.
194  
195 Chapter 15, "Modeling of Data", deals with general weighted least
196 squares estimation, though it describes the Levenber-Marquardt method
197 in more detail. Additionally, it is assumed that only one maesurement
198 is observed.
199  
200 =item Mikhail, E.M. and Ackermann, F. (1976): Observations and Least
201 Squares University Press of America
202  
203 This book covers the classical Gauss-Helmert model.
204  
205 =item Koch, K. (1999) Parameter Estimation and Hypothesis Testing in
206 Linear Models, Springer Verlag, 2nd edition
207  
208 This book covers the Gauss-Markoff model, a cousin of the
209 Gauss-Helmert model, but modelling explicit functions.
210  
211 =back
212  
213 =head1 DIAGNOSTICS
214  
215 Not really done yet, meanwhile check the output with the verbose flag.
216  
217 =head1 BUGS
218  
219 Probably there are some, but this function has been extensively and
220 succesfully tested in conjunction with the Math::UncertainGeometry
221 library.
222  
223 =head1 TODO
224  
225 =over
226  
227 =item numerical differentiation instead of explicit Jacobians
228  
229 =item Better diagnostics, more examples
230  
231 =item Speed Optimization not done at all.
232  
233 =item More examples
234  
235 =item A more complete TODO list
236  
237 =back
238  
239 =head1 SEE ALSO
240  
241 This module uses the Perl Data Language, L<PDL>, especially
242 L<PDL::Matrix>, to perform matrix operations.
243  
244 For a complex example on how this module is used, see
245 L<Math::UncertainGeometry::Estimation> for estimating points, lines
246 and planes in 2D and 3D.
247  
248 =head1 AUTHOR
249  
250 Stephan Heuel
251 (perl@heuel.org)
252  
253 =head1 COPYRIGHT
254  
255 Copyright (C) 2000/2001 Stephan Heuel and Institute for
256 Photogrammetry, University of Bonn. All rights reserved. There is no
257 warranty. You are allowed to redistribute this software /
258 documentation under certain conditions, see the GNU Public License,
259 GPL for details, http://www.gnu.org/copyleft/gpl.html.
260  
261 =cut
262  
263 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
264 3 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
265 3 ▶use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $VERSION);
Subroutine BEGIN: called CC=1 SCAR=0.0
266  
267 3 ▶use 5.6.0;
Subroutine BEGIN: called CC=1 SCAR=0.0
268  
269 3 ▶use Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
270 $VERSION = 0.05;
271 @ISA = qw(Exporter);
272  
273 @EXPORT = qw(); # symbols to autoexport, will be filled later on
274 @EXPORT_OK = qw(); #symbols to export on request
275 %EXPORT_TAGS = ( );
276  
277 3 ▶use PDL;
Subroutine BEGIN: called CC=1 SCAR=0.0
278 3 ▶use PDL::Matrix;
Subroutine BEGIN: called CC=1 SCAR=0.0
279 3 ▶use PDL::Math;
Subroutine BEGIN: called CC=1 SCAR=0.0
280 0 ▶use PDL::Slatec;
Subroutine BEGIN: called CC=1 SCAR=2.6
281  
282 # this may be accessed from outside, but it is more advisable to use
283 # the OO interface and the verbose method
284 our $OUTPUT = 0;
285  
286 # default number of iterations
287 my $number_of_iteration=15;
288  
289 # default abort criteria. This refers to the largest difference of
290 # change in the estimated vector divided by its standard deviation
291 my $eps = 1e-2;
292  
293 #################################################
294 ## OO wrapper for GaussHelmertBlocks:
295 ##
296  
297 # build lookup table for input data
298 my %input_data = map { ($_,1) }
299 qw/observations initial_guess covariance_observations
300 observation_equations Jacobian_unknowns Jacobian_observations
301 constraints Jacobian_constraints constraints_observations noblocks
302 Jacobian_constraints_observations maximal_no_iterations epsilon
303 verbose/;
304  
305 # build lookup table for output data
306 my %output_data = map { ($_,1) }
307 qw/estimated_unknown sigma0_squared covariance_unknown
308 estimated_observations estimated_unknowns_iterations
309 number_of_iterations/;
310  
311 # constructor
312 sub new {
313 my ($protoverse, %arg) = @_;
314 my $class = ref($protoverse) || $protoverse;
315
316 my $self = { };
317 set_all($self,%arg);
318  
319 # this parameter will determine whether we specify blocks of
320 # observation vectors or just one single observation vector
321 $self->{_noblocks} = 1;
322  
323 bless $self,$class;
324 }
325  
326 # set member variables by passing a hash
327 sub set_all {
328 my ($self,%arg) = @_;
329  
330 # store all passed keys
331 foreach my $arg_key (keys %arg) {
332 defined $input_data{$arg_key} or
333 warn "*** Unknown input argument $arg_key for constructing ".__PACKAGE__." object\n";
334 $self->{"_$arg_key"} = $arg{$arg_key};
335 }
336 }
337  
338 # declare all member functions such that members may access and change
339 # object data
340 foreach my $input_data (keys %input_data) {
341 no strict 'refs';
342 *$input_data = sub { # closures are cool !
343 my ($self,$value) = @_;
344 return $self->{"_$input_data"} unless defined $value;
345 $self->{"_$input_data"} = $value;
346 }
347 }
348  
349 # output data can only be accessed by read-only member functions
350 foreach my $output_data (keys %output_data) {
351 no strict 'refs';
352 *$output_data = sub { $_[0]->{"_$output_data"}; }
353 }
354  
355 # do the actual estimation
356 sub start {
357 my $self = shift;
358 $self->set_all(@_);
359  
360 # copy data to temporary hash, uhm... well... I should get around
361 # this.
362 my %arg;
363 $arg{$_} = $self->{"_$_"} for (keys %input_data);
364  
365 # call the actual estimation procedure
366 my $result = GaussHelmertBlocks(\%arg);
367  
368 # and now copy the result to myself
369 $self->{"_$_"} = $result->{$_} for (keys %$result);
370
371 return $self;
372 }
373  
374 # this is needed when GaussHelmertBlocks is called, but actually we
375 # only have one block of observations and therefore we don't want to
376 # get into the hassle of expressing the functions (and Jacobians) in
377 # blocks. This function wraps a single call (&$function) to a block
378 # call
379 sub wrap_single_function_to_block_function {
380 my ($y,$b,$function) = @_;
381  
382 my @ygroup = PDL::dog( $y->[0] ); # dog is the opposite of PDL::cat
383
384 my @Jgroup;
385  
386 # this could be a PP function as well.
387 @Jgroup = map {
388 &$function($_,$b);
389 } @ygroup ;
390
391 return (PDL::cat(@Jgroup));
392 }
393  
394 ##########################################################################
395 # This is the actual function for estimating
396 #
397 # there is some experimental code included which may let the
398 # observations $y constrained in a second stage by the constraint
399 # g($y$) and its Jacobian $G$. This part of the code has been not
400 # tested.
401 sub GaussHelmertBlocks {
402 my ($args) = @_;
403  
404 warn "I expect only one hash argument to GaussHelmertBlocks" if @_>1;
405  
406 # decode hash arguments;
407 my $y = delete $args->{observations};
408 my $b0 = delete $args->{initial_guess};
409 my $Sigma_yy = delete $args->{covariance_observations};
410 my $func_w_in = delete $args->{observation_equations};
411 my $func_A_in = delete $args->{Jacobian_unknowns};
412 my $func_B_in = delete $args->{Jacobian_observations};
413 my $func_h_in = delete $args->{constraints};
414 my $func_H_in = delete $args->{Jacobian_constraints};
415 my $func_g = delete $args->{constraints_observations};
416 my $func_G = delete $args->{Jacobian_constraints_observations};
417 my $max_iterations = delete $args->{maximal_no_iterations};
418 my $epsilon = delete $args->{epsilon} || $eps;
419 my $noblocks = delete $args->{noblocks};
420 my $verbose = delete $args->{verbose};
421  
422 my $logfile = "./GaussHelmert.log";
423  
424 # if verbose is defined and nonempty and does not only contain
425 # numbers, then we assume it's the string for the filename of the
426 # logfile.
427 if (defined $verbose and $verbose ne "" and $verbose !~ /^\d+$/) {
428 $logfile=$verbose;
429 $verbose=2;
430 }
431  
432 # set for verbosity
433 my $tmp = $OUTPUT; # so that I can restore the global variable
434 # $OUTPUT, should be changed since $OUTPUT must
435 # not be global
436 $OUTPUT = $verbose if defined $verbose;
437  
438  
439 # warn for unknown options in argument hash
440 foreach (keys %$args) {
441 warn "*** Warning: Unknown option to GaussHelmertBlocks: $_\n";
442 }
443  
444  
445 my ($func_w,$func_A,$func_B,$func_h,$func_H);
446 if (defined $noblocks and $noblocks) {
447 $func_A = sub { wrap_single_function_to_block_function($_[0],$_[1],$func_A_in); };
448 $func_B = sub { wrap_single_function_to_block_function($_[0],$_[1],$func_B_in); };
449 $func_w = sub { wrap_single_function_to_block_function($_[0],$_[1],$func_w_in); };
450 if (defined $func_h_in) {
451 $func_h = sub { wrap_single_function_to_block_function($_[0],$_[1],$func_h_in); };
452 $func_H = sub { wrap_single_function_to_block_function($_[0],$_[1],$func_H_in); };
453 }
454 # wrap observations etc in an array
455 $Sigma_yy = [ $Sigma_yy ];
456 $y = [ $y ];
457 }
458 else {
459 $func_w = $func_w_in;
460 $func_A = $func_A_in;
461 $func_B = $func_B_in;
462 if (defined $func_h_in) {
463 $func_h = $func_h_in;
464 $func_H = $func_H_in;
465 }
466 }
467  
468 ################################################################################
469 #
470 # some preperations needed
471  
472 # set the maximum number of iterations
473 $max_iterations ||= $number_of_iteration;
474  
475 # initialize $y^\hat$ and $b^\hat$.
476 my @y_observed = @$y; # these are my observations!
477 # in @y will be the estimated observations
478 my @y = map { defined($_) ? $_->copy : undef } @y_observed;
479 # now we set up variables such as unknowns $b, we keep track of the
480 # unknowns per iteration (@b_iterations), the offerenc between two
481 # consecutive unknowns $delta_b, the error $e and the coariance
482 # matrix $Sigma_bb for the unknowns
483 my ($b,@b_iterations,$delta_b,$e,$Sigma_bb);
484  
485 # check if we get the number of contradictions from the funtion w
486 # itself.
487 my ($nU,$nW,$nH) = (0,0,0);
488  
489 # iteration 0
490 my $i=0;
491  
492 # if the initial guess $b0 for the unknown is not defined and
493 # therefore the Jacobian $A$ not defined either, we assume that only
494 # the observations are supposed to be estimated.
495 my ($only_observations,@A_init)=(0,undef);
496 if (!defined($b0) && !defined($func_A)) {
497 $only_observations=1;
498 # build dummy observation and dummy Jacobian so that we do not
499 # have to change too much code (for the sake of less
500 # efficiency).
501 $b0 = vpdl([0]); # the shortest unknown possible
502 @A_init = map { (my $x = ~$y[$_]->copy) .= 0; $x; } (0..$#y);
503 $nU=0;
504 $nH=0;
505 }
506 else {
507 $b = $b0->copy;
508 @b_iterations = ($b); # here I store all iterations of the
509 # unknown vector b
510 $nU = ($b0->mdims())[0];
511 if (defined $func_h) {
512 my $ch_dummy = &$func_h($b);
513 # the number of constraints are equal to the number of elements
514 # in the resulting vector of constraint function &$func_h
515 $nH = ($ch_dummy->clump(-1)->dims)[0];
516 } else {
517 $nH=0;
518 }
519 }
520  
521 # determine number of contradictions
522 my @cw_dummy = &$func_w([@y],$b0);
523 # sum up the list of contradictions for each block
524 $nW += ($_->clump(-1)->dims)[0] foreach (@cw_dummy);
525  
526 # assume Sigma_yy to be identity if it is not defined
527 if (!defined($Sigma_yy)) {
528 $Sigma_yy = [ map { my ($dim,undef,$no) = $y[$_]->mdims();
529 my $Id = mzeroes($dim,$dim,$no);
530 (my $tmp = $Id->diagonal(0,1)) .= 1;
531 $Id;
532 } (0..$#y) ];
533 }
534
535 if ($nW + $nH < $nU) {
536 warn "*** Warning: ",
537 __FILE__," line ",__LINE__,"\n",
538 " # of unknowns ($nU) is larger than # of obs. ($nW) + # of constraints ($nH)\n";
539 return undef;
540 }
541 my $Omega_last_iteration = 0;
542 my (@w,$sigma_hat);
543  
544 if ($OUTPUT>1) {
545 print "Generating logfile in $logfile\n";
546 open LOG,">$logfile" or warn "**** cannot open logfile $logfile: $!\n";
547 print LOG "generated on ",scalar(localtime),"\n";
548 print LOG "nW = $nW; nH = $nH; nU = $nU\n";
549
550 print LOG "Sigma_yy ",join(",",@$Sigma_yy);
551 }
552
553 ################################################################################
554 #
555 # now start iterations!
556 while ($i++ < $max_iterations) {
557 if ($OUTPUT) {
558 print LOG "Iteration $i\n" if $OUTPUT > 1;
559 print "Iteration $i\n";
560 }
561 my @A = ($only_observations) ? @A_init : &$func_A([@y],$b);
562 my @B = &$func_B([@y],$b);
563 my $H = ($only_observations || !defined($func_H)) ? undef : &$func_H($b);
564
565 if ($OUTPUT>1) {
566 print LOG "y$i part $_ ".$y[$_]->clump(3)."\n" for (0..$#y);
567 }
568  
569 # compute $c_w$.
570 my @dy = map { $y_observed[$_] - $y[$_] } (0 .. $#y);
571 my @cw = &$func_w([@y],$b);
572 $cw[$_] += $B[$_] x $dy[$_] for (0..$#y);
573  
574 if ($OUTPUT>1) {
575 print LOG "A($i)",join(",",@A);
576 print LOG "B($i)",join(",",@B);
577 print LOG "H($i)",$H if defined $H;
578 }
579
580  
581 # $Sigma_ww^{-1}$.
582 # print @B; print @$Sigma_yy;
583 print LOG "\@B x ~\@B", join(",",map { ($B[$_] x $Sigma_yy->[$_] x ~$B[$_]) } (0 .. $#y)) if $OUTPUT>1;
584 my @Sigma_ww_inv = map { ($B[$_] x $Sigma_yy->[$_] x ~$B[$_])->matinv } (0 .. $#y);
585  
586 if ($OUTPUT>1) {
587 @w = &$func_w([@y_observed],$b); # new calculation of w for output purposes
588 foreach (0..$#w) {
589 print LOG "cw(b$i,y$i) part $_ ".$cw[$_]->clump(3)."\n";
590 print LOG "w(b$i,y) part $_ ".$w[$_]->clump(3)."\n";
591 print LOG "Sigma_ww_inv(b$i,y) part $_ ".$Sigma_ww_inv[$_]."\n";
592 }
593 }
594  
595 if (!$only_observations) {
596 my $ch = defined($func_h) ? &$func_h($b) : undef;
597
598 # building and solving normal equation system
599 my $AtSwwA = mzeroes($nU,$nU);
600 for (0..$#y) { $AtSwwA += msumover(~$A[$_] x $Sigma_ww_inv[$_] x $A[$_]) }
601 my $M;
602 if (defined $H) {
603 $M = ~append(~append($AtSwwA,~$H ),
604 ~append($H ,mzeroes($nH,$nH)));
605 }
606 else {
607 $M = $AtSwwA;
608 }
609
610 my $AtSwwcw = mzeroes($nU);
611 for (0..$#y) { $AtSwwcw += msumover(~$A[$_] x $Sigma_ww_inv[$_] x $cw[$_]) }
612
613 my $s = defined($ch) ? ~append( transpose(-$AtSwwcw),
614 transpose(-$ch) )
615 : -$AtSwwcw ;
616 my $Minv = $M->matinv;
617 my $x = $Minv x $s;
618
619 # now compute the corrections to $\beta$.
620 $delta_b = $x->slice("0:".($nU-1));
621 $b = $b + $delta_b;
622 push @b_iterations,$b;
623  
624 $Sigma_bb = $Minv->slice("0:".($nU-1).",0:".($nU-1));
625 }
626 else {
627 $delta_b = vpdl([0]);
628 }
629
630 my @lambda = map { $Sigma_ww_inv[$_] x ($cw[$_] + $A[$_] x $delta_b ) } (0..$#y);
631 my @e = map { $Sigma_yy->[$_] x ~$B[$_] x $lambda[$_] } (0..$#y);
632  
633 if ( $OUTPUT>1 ) {
634 print LOG "lambda($i) part $_ ".$lambda[$_]->clump(3)."\n" foreach (0..$#lambda);
635 }
636  
637 @y = map { $y_observed[$_] - $e[$_] } (0..$#y);
638  
639 # do we have to correct the observations y ?
640 if (defined($func_g) && defined($func_G)) {
641  
642 my @ytmp = map { $_->copy } @y;
643  
644 if ( $OUTPUT>1 ) {
645 print LOG "-------> before correction of observations:\n";
646 foreach (0..$#y) {
647 print LOG "y($i) part $_ ".$y[$_]->clump(3)."\n";
648 }
649 }
650
651 my $tmp = $OUTPUT;
652 $OUTPUT=0;
653 my $tmpresult=
654 GaussHelmertBlocks({
655 observations => [@ytmp],
656 observation_equations => $func_g,
657 Jacobian_observations => $func_G,
658 maximal_no_iterations => 5
659 });
660  
661  
662 $OUTPUT=$tmp;
663 my $y_est = $tmpresult->{estimated_observations};
664 @y = @$y_est;
665  
666 if ( $OUTPUT>1 ) {
667 print LOG "-------->after correction of observations:\n";
668 foreach (0..$#y) {
669 print LOG "y($i) part $_ ".$y[$_]->clump(3)."\n";
670 }
671 }
672  
673 if ( $OUTPUT>1 ) {
674 print LOG "-------> division of before/after::\n";
675 foreach (0..$#y) {
676 print LOG "y($i) part $_ ".($y[$_]->clump(3)/$ytmp[$_]->clump(3))."\n";
677 }
678 }
679 }
680  
681 # almost done ...
682 my $Omega = 0;
683 $Omega += sum(~$e[$_] x ~$B[$_] x $lambda[$_]) foreach (0..$#y);
684  
685 $sigma_hat = (($nW + $nH - $nU) > 0) ? ($Omega / ($nW + $nH - $nU)) : 1;
686  
687 # compute criteria for a premature abortion of the iteration.
688 # This is \delta(\beta)/sqrt(\sigma_\beta\beta) < 1e-2 means that the
689 # corrections to the estimation is less than 1% w.r.t. to its
690 # standard deviation.
691 my ($abort_criterion,$abort_p);
692 if (!$only_observations) {
693 # only look at those entries where \sigma_\beta\beta is
694 # significantly larger than 0
695 my ($db_s,$sigma_bb_s) = where(abs($delta_b->clump(2)),
696 sqrt($Sigma_bb->diagonal(0,1)),
697 $Sigma_bb->diagonal(0,1) > 1e-16);
698 if ( $OUTPUT>1) {
699 print LOG "|db| (selected)",$db_s,"\n";
700 print LOG "sqrt(sigma_bb^2) (selected)",$sigma_bb_s,"\n";
701 }
702 $abort_criterion = max($db_s/$sigma_bb_s);
703 $abort_p = ($abort_criterion < $epsilon);
704 }
705 else {
706 $abort_p = 0; # TODO: needs to be defined properly
707 }
708  
709  
710  
711 # that's all computation for this iteration, but maybe we want to
712 # output some of the results....
713 if ( $OUTPUT) {
714 my $Omega1 = 0;
715 foreach (0..$#y) {
716 $Omega1 += sum(~$e[$_] x ~$B[$_] x $Sigma_ww_inv[$_] x $B[$_] x $e[$_]);
717 };
718
719 # proof if Omega is equal to ...
720 print LOG "Omega e^T B \\lambda : $Omega\n" if $OUTPUT > 1;
721 print LOG "Omega1 e^T B^T \\Sigma B e : $Omega1\n" if $OUTPUT > 1;
722 print "Omega = ($Omega | $Omega1 )\n";
723  
724 if ($sigma_hat<0) {
725 print "*** Warning: sigma0^2 = $sigma_hat < 0, taking absolute value\n";
726 # print "$Omega,$Omega1\n";
727 # die;
728 print LOG "*** Warning: sigma0^2 = $sigma_hat < 0, taking absolute value\n" if $OUTPUT > 1;
729 }
730 print LOG "sigma0 : ",sqrt(abs($sigma_hat)),"\n" if $OUTPUT > 1;
731 print "sigma0 : ",sqrt(abs($sigma_hat)),"\n";
732  
733
734 my $test=0;
735 foreach (0..$#y) {
736 # print "-->".$lambda[$_].$B[$_].$y[$_]."\n";
737 $test += sum(~$lambda[$_] x $B[$_] x $y[$_]);
738 };
739 # print LOG "e^T x Cyy^-1 x y^\\hat => $test\n";
740 # print "e^T x Cyy^-1 x y^\\hat => $test\n";
741 print LOG "\\lambda^T x B x y^\\hat => $test\n" if $OUTPUT > 1;
742 print "\\lambda^T x B x y^\\hat => $test\n";
743  
744  
745 @w = &$func_w([@y_observed],$b);
746 foreach (0..$#y) {
747 my $tmp = PDL::max(abs(($B[$_] x $e[$_]) - $w[$_]->clump(3)));
748 print LOG " max |B*e - w(b$i,y) | ($_) : $tmp\n" if $OUTPUT > 1;
749 print "max |B*e - w(b$i,y) | ($_) : $tmp\n";
750 };
751  
752 @w = &$func_w([@y],$b); # new calculation of w for output purposes
753 foreach (0..$#w) {
754 print LOG "w(b$i,y$i) part ($_) ".$w[$_]->clump(3)."\n" if $OUTPUT > 1;
755 print LOG "max | w(b$i,y$i) | ($_) ".PDL::max(abs($w[$_]->clump(3)))."\n" if $OUTPUT > 1;
756 print "max | w(b$i,y$i) | ($_) ".PDL::max(abs($w[$_]->clump(3)))."\n";
757
758 }
759  
760 if (!$only_observations && defined($func_h)) {
761 my $h = &$func_h($b); # new calculation of h
762 print LOG "h(b$i) ".$h->slice(",(0)")."\n" if $OUTPUT > 1;
763 print LOG "max | h(b$i) | ".PDL::max(abs($h->clump(2)))."\n" if $OUTPUT > 1;
764 print "max | h(b$i) | ".PDL::max(abs($h->clump(2)))."\n";
765 }
766  
767 if (!$only_observations) {
768 print LOG "db($i) ".$delta_b->slice(",(0)")."\n" if $OUTPUT > 1;
769 print LOG "b($i) ".$b->slice(",(0)")."\n" if $OUTPUT > 1;
770 print LOG "b($i) (spherical)",($b->slice(",(0)")/sqrt(sum($b**2))),"\n" if $OUTPUT > 1;
771 print "b($i) ".$b->slice(",(0)")."\n";
772 print "b($i) (spherical)",($b->slice(",(0)")/sqrt(sum($b**2))),"\n";
773 }
774  
775 foreach (0..$#e) {
776 print LOG "e($i) part $_ ".$e[$_]->clump(3)."\n" if $OUTPUT > 1;
777 }
778  
779  
780 foreach (0..$#y) {
781 print LOG "y($i) part $_ ".$y[$_]->clump(3)."\n" if $OUTPUT > 1;
782 }
783
784 print LOG "max(db(i)/sigma_b(i)) $abort_criterion\n" if $OUTPUT > 1;
785 print "max(db(i)/sigma_b(i)) $abort_criterion\n";
786  
787 print LOG "--------------------------------------------------\n" if $OUTPUT > 1;
788 print "--------------------------------------------------\n";
789  
790 }
791
792 # check if we can leave this estimation earlier
793 last if ($abort_p);
794 $Omega_last_iteration=$Omega;
795 }
796
797 close LOG if ($OUTPUT>1);
798  
799 # restore global $OUTPUT
800 $OUTPUT = $tmp;
801  
802 # return the unknown and its covariance matrix, the estimated
803 # observations. Furthermore return an array with the unknown vector
804 # for each iteration step and the number of iterations
805 return { "estimated_unknown" => $b,
806 "sigma0_squared" => $sigma_hat,
807 "covariance_unknown" => $Sigma_bb, # without sigma_0 !
808 "estimated_observations" => [@y],
809 "estimated_unknowns_iterations" => [@b_iterations],
810 "number_of_iterations" => $i,
811 };
812 }
813 push @EXPORT_OK,"GaussHelmertBlocks";
814  
815 1;
816  
817 # make a class which can deal with blocks. This inherits from
818 # GaussHelmert,
819 package Statistics::GaussHelmertBlocks;
820  
821 use base qw/Statistics::GaussHelmert/;
822  
823 sub new {
824 my $self = Statistics::GaussHelmert::new(@_);
825 $self->noblocks(0); # we want to have blocks!
826 return $self;
827 }
828  
829 1;
830  
831  
832 __END__
↑ Summary