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 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
|
package Demeter::Fit::Happiness;
=for Copyright
.
Copyright (c) 2006-2019 Bruce Ravel (http://bruceravel.github.io/home).
All rights reserved.
.my
This file is free software; you can redistribute it and/or
modify it under the same terms as Perl itself. See The Perl
Artistic License.
.
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.
=cut
use autodie qw(open close);
use Moose::Role;
use Carp;
sub get_happiness {
my ($self) = @_;
my $cheer = 100;
my $summary = q{};
## R-factor
my ($c, $s) = $self->_penalize_rfactor;
$cheer -= $c;
$summary .= $s;
## path parameter values
($c, $s) = $self->_penalize_pathparams;
$cheer -= $c;
$summary .= $s;
## restraints
($c, $s) = $self->_penalize_restraints;
$cheer -= $c;
$summary .= $s;
## Nidp
($c, $s) = $self->_penalize_nidp;
$cheer -= $c;
$summary .= $s;
## correlations
($c, $s) = $self->_penalize_correlations;
$cheer -= $c;
$summary .= $s;
$cheer = 0 if ($cheer < 0);
return wantarray ? ($cheer, $summary) : $cheer;
};
sub color {
my ($self, $cheer) = @_;
$cheer ||= $self->happiness;
my @bad = $self->_slice_rgb( $self->co->default("happiness", "bad_color" ) );
my @ok = $self->_slice_rgb( $self->co->default("happiness", "average_color") );
my @good = $self->_slice_rgb( $self->co->default("happiness", "good_color" ) );
my (@bottom, @top, $fraction);
my $min = $self->co->default("happiness", "minimum");
my $scaled = ($cheer < $min) ? 0 : ($cheer-$min) / (100-$min);
my $center = $self->co->default("happiness", "shoulder");
if ($scaled < $center) {
$fraction = $scaled / $center;
@bottom = @bad;
@top = @ok;
} else {
$fraction = ($scaled-$center) / $center;
@bottom = @ok;
@top = @good;
};
my @answer = map { $bottom[$_] * (1-$fraction) + $top[$_] * $fraction } (0 .. 2);
return sprintf("#%X%X%X", @answer);
};
sub _slice_rgb {
my ($self, $string) = @_;
## what if color is an rgb.txt named color?
## use Color::Rgb and provide an rgb.txt file, perhaps in share/
$string =~ s{^\#}{};
my $r = substr($string, 0, 2);
my $g = substr($string, 2, 2);
my $b = substr($string, 4, 2);
return (eval "0x$r", eval "0x$g", eval "0x$b");
};
sub _penalize_rfactor {
my ($self) = @_;
my @data = @{ $self->data };
my $space = 1;
foreach my $d (@data) {
$space = 0.1 if ($d->fit_space eq 'k');
};
my ($low, $high, $scale) = (
$self->co->default("happiness", "rfactor_low"),
$self->co->default("happiness", "rfactor_high"),
$self->co->default("happiness", "rfactor_scale")
);
my $maximum = $scale * ($high - $low);
my $rfactor = $self->r_factor || 0;
return (0, q{}) if ($rfactor < $low);
my $penalty = ($rfactor-$low) * $scale * $space; # reduce penalty by 1/10 for fit in k-space
$penalty = ($rfactor > $high) ? $maximum : $penalty;
my $summary = sprintf("An R-factor of %.5f gives a penalty of %.5f.\n",
$rfactor, $penalty);
return ($penalty, $summary);
};
sub _penalize_pathparams {
my ($self) = @_;
my $scale = $self->co->default("happiness", "pathparams_scale");
my @paths = @{ $self->paths };
my @params = qw(e0 s02 delr sigma2); # third fourth dphase
my $count = 0;
my $summary = q{};
foreach my $p (@paths) {
next if not $p->include;
foreach my $pa (@params) {
my ($isok, $explanation) = $p->is_resonable($pa);
if (not $isok) {
$summary .= "Penalty of $scale : " . $explanation . "\n";
++$count;
};
};
};
$count *= $scale;
return ($count, $summary);
};
sub _penalize_restraints {
my ($self) = @_;
my $scale = $self->co->default("happiness", "restraints_scale");
my @gds = @{ $self->gds };
my $chisqr = $self->chi_square;
my $count = 0;
my $summary = q{};
foreach my $g (@gds) {
next if ($g->gds ne "restrain");
my $this = $g->bestfit;
#my $addon = ($chisqr) ? $this/$chisqr : 0;
my $addon = ($chisqr) ? $this : 0;
$count += $addon;
next if ($this == 0);
#print join("|", $scale,$this,$chisqr), $/;
$summary .= sprintf("The restraint \"%s\" evaluated to %.3f for a penalty of %.3f.\n",
$g->name, $g->bestfit, $scale*$this);
#$g->name, $g->bestfit, $scale*$this/$chisqr);
};
my $total = $scale * $count;
return ($total, $summary);
};
sub _penalize_nidp {
my ($self) = @_;
my ($cutoff, $scale) = (
$self->co->default("happiness", "nidp_cutoff"),
$self->co->default("happiness", "nidp_scale"),
);
return (0, q{}) if ($cutoff >= 1);
my $nidp = $self->n_idp;
my $nvar = $self->n_varys;
my $diff = $nidp-$nvar;
my $limit = (1 - $cutoff)*$nidp;
return (0, q{}) if ($diff > $limit);
my $penalty = ($limit-$diff) / $limit;
$penalty *= $scale;
my $summary = sprintf("Used %d of %.3f independent points for a penalty of %.3f\n",
$nvar, $nidp, $penalty);
return ($penalty, $summary);
};
sub _penalize_correlations {
my ($self) = @_;
my ($cutoff, $scale) = (
$self->co->default("happiness", "correl_cutoff"),
$self->co->default("happiness", "correl_scale"),
);
my %all = $self->all_correl;
my @order = sort {abs($all{$b}) <=> abs($all{$a})} (keys %all);
my $count = 0;
foreach my $k (@order) {
last if (abs($all{$k}) < $cutoff);
++$count;
};
my $penalty = $count * $scale;
my $s = ($count > 1) ? q{s} : q{};
my $summary = ($count)
? sprintf("%d correlation%s above %.3f for a penalty of %.3f\n", $count, $s, $cutoff, $penalty)
: q{};
return ($penalty, $summary);
};
1;
=head1 NAME
Demeter::Fit::Happiness - Semantic evaluation of an EXAFS fit
=head1 VERSION
This documentation refers to Demeter version 0.9.26.
=head1 SYNOPSIS
After a fit finishes, Demeter evaluates a semantic (i.e.
non-statistical) parameter for the fit based on the R-factor, path
parameter values, restraints, and other aspects of the fit. This
parameter is a tunable, I<ad hoc> measure of how happy the fit will
make the person running the fit.
=head1 DESCRIPTION
Ifeffit and Larch, and therefor Demeter, offers a number of parameters
after the completion of the fit. These include the chi-square, the
reduced chi-square, an R-factor, error bars, uncertainties, and
restraint evaluations. These various parameters serve different
purposes. The chi-square is the actual fitting metric, i.e. the
quantity which is minimized in the fit. The reduced chi-square is the
fitting metric normalized by the degrees of freedom (i.e. the
difference in the number of independent points and the number of guess
parameters used) and is a true statistical parameter. The reduced
chi-square can be used to compare two different fitting models against
a data set. The R-factor is merely a percentage misfit, a numerical
measure of how well the fit over-plots the data. Taken together the
reduced chi-square and the R-factor go a long way towards helping you
evaluate your fit.
Unfortunately, the EXAFS fitting problem is not a well-defined
Gaussian fitting problem. That's a shame, given that Ifeffit & Larch
apply the concepts of Gaussian statistics. In principle, one can do
much better than a simple application of Gaussian statistics. Several
workers, notably Krappe and Rossner, have applied Bayesian concepts to
the EXAFS problem. In practice Demeter uses Ifeffit or Larch because
they offer so many useful tools for arbitrary model building.
Consequently, Demeter and its users need to find a way to live with
the shortcomings of the Gaussian approach to the EXAFS problem.
A blind reliance on the reduced chi-square and the R-factor is not a
good idea. Because the EXAFS problem is so ill-posed in the Gaussian
sense, reduced chi-square is almost never close to 1 -- even tough
that is the definition of a good a fit in Gaussian statistics.
Consequently, reduced chi-square can only be used to compare fits. It
may not be used to evaluate the quality of a single fit.
The R-factor is even more problematic. It merely tells you whether
the fit closely over-plots the data. It does nothing to evaluate
whether the results of the fit make any kind of physical sense. Those
sorts of value judgments are the responsibility of the EXAFS
practitioner. She must consider whether the best fit values are
physically sensible, whether the error bars and correlations are
acceptible, and whether the path parameters evaluate to sensible
values. These value judgments, along the reduced chi-square and the
R-factor, go into the assessment of the fit.
Fortunately, we know a lot about what an EXAFS fit should do. For
instance,
=over 4
=item *
It should have a small R-factor (although a fit performed in k
space will always have a large R-factor).
=item *
The number of variables should be considerably less than the number of
independent points.
=item *
The S02 and sigma2 path parameters should not be negative.
=item *
The e0, deltaR and sigma2 path parameters should not be too big.
=item *
Fitting parameters should not be too highly correlated.
=back
This module introduces an entirely semantic (i.e. non-statistical, I<ad
hoc>, and non-publishable) parameter which attempts to quantify all of
the above. This parameter is called the I<happiness>. This name is
chosen , in part, because it can serve as an indication of how happy
the fit should make you and, in part, because it is a silly idea that
should not be taken too seriously. (I feel obliged to point out that
happiness in the abstract is not silly, merely the notion that your
EXAFS software can quantify happiness!)
The output is a number between 0 and 100. A happiness of 100 is the
happiest possible fit. A happiness of 0 should make you very sad
indeed. The happiness number is reported in the log file. A good use
of the happiness would be to provide a visual cue in a graphical
interface. For example, a region of the screen could glow green when
the happiness is above 90 and red when it is below 60, with values in
between producing colors that run the spectrum between red and green.
That is the sense in which happiness is a semantic parameter. It does
not provide you with a number that you can quote in the scientific
literature, but it provides a way for software to suggest how pleased
you are liable to be once the fit completes. Even better, it provides
a clue that something may have gone awry in a bad fit. In particular,
it evaluates more of the fit than just the percentage misfit. A fit
with a small R-factor and unreasonable path parameter values should be
an unhappy fit.
The idea for a semantic parameter of this sort came from a radio piece
(I think it was Eight Forty-Eight on Chicago Public Radio) I heard on
a device called L<The Ambient
Orb|http://www.ambientdevices.com/cat/orb/orborder.html>. The idea of
this device is that it snarfs stock data from the internet and glows
green when the market is up and red when the market is down. This
provides a semantic, ambient indication of the state of one's stock
portfolio. The part that interested me when I first heard about this
is that users of the orb tend to be less anxious about their stock
portfolios. Rather than needing to continuously check etrade.com, one
can glance a splash of color out of the corner of the eye. I like the
thought of having a visual indicator of how well a fit is working out
while in the middle of a lengthy analysis session.
The current version of the happiness parameter works like this:
=over 4
=item I<initial value>
The happiness starts at 100%, i.e. fully happy. Each of the
parameters used to evaluate the happiness can only subtract from the
happiness. Each parameter is checked in turn for its diminution of
the happiness.
=item I<R-factor>
An R-factor below 0.02 is a happy R-factor. An R-factor between 0.02
and 0.06 diminishes the happiness by this formula:
(R - 0.02) * 1000
Thus an R-factor of 0.03 reduces the happiness by 10. An R-factor in
excess of 0.06 incurs the full hit of 40 to the happiness.
The R-factor of a fit in k-space will almost always be large due the
effect of higher frequencies on the evaluation of the R-factor. Thus
the scaling factor for the R-factor penalty is made 1/10 as big.
=item I<parameter values>
Perform the sanity checks in L<Demeter::Path::Sanity>.
Penalize the happiness by 2 for each path parameter that fails a
sanity check.
=item I<restraints>
The restraints are added as fractional contributions to the evaluated
chi-square and multiplied by a scaling factor.
(restraint / chi-square) * scale
Thus a restraint that involves a guess parameter wandering farther
away from its nominal value diminishes the happiness more. This works
well with the C<penalty> function. When the guess parameter is within
its boundaries, the restraint will not diminish happiness.
=item I<nidp>
Diminish happiness if the number of variables used is too large
compared to the number of independent points. The full penalty is
applied when all independent points are used. No penalty is applied
if less than 2/3 of the independent points are used.
=item I<correlations>
Diminish happiness for each correlation above a certain value. No
penalty is applied if no correlations are too high.
=back
=head1 METHODS
=over 4
=item C<happiness>
This method evaluates the happiness for a fit.
In list context, the return values are the net numerical value of the
happiness and a text string summarizing each of the penalties against
the happiness.
($happpiness_value, $happiness_summary) = $fitobject -> happiness;
In scalar context, just the numerical value is returned.
$happpiness_value = $fitobject -> happiness;
=item C<color>
This method returns a color representation of the happiness as a
hexadecimal triplet.
print $fit->color;
==prints==>
#E2E995
This is intended as a visual representation of the happiness and could
be used to color a GUI element as an ambient cue as to the quality of
the fit. It takes four parameters. Three are colors representing the
best fit, the worst fit, and an average fit. The last parameter is
the happiness value that represents the worst fit. For instance:
good fit #C5E49A a greenish color
average fit #FFEE90 a yellowish color
bad fit #FD7E6F a reddish color
minimum happiness 60
For happiness values between 60 and 80, the color is the linear
interpolation between the bad and average colors. For happiness
values between 80 and 100, the color is the linear interpolation
between the average and good colors.
=back
=head1 CONFIGURATION AND ENVIRONMENT
See L<Demeter::Config> for a description of the configuration
system.
The following parameters are configurable so that the happiness
algorithm can be tuned. See the happiness group of configuration
parameters.
=over 4
=item I<R-factor>
The boundary values and the scaling factor. Defaults: 0.02, 0.06,
1000. The scaling factor is reduced to 1/10 its value for a fit in
k-space.
=item I<parameter values>
The per-failure penalty. Default: 2. Each penalty is configurable
using the parameters in the warnings group.
=item I<restraints>
The scaling factor. Default: 10.
=item I<nidp>
The cutoff and the scaling factor. Defaults: 2/3 and 40.
=item I<correlations>
The cutoff and the penalty for each high correlation. Defaults: 0.95
and 3.
=back
=head1 DEPENDENCIES
Demeter's dependencies are in the F<Build.PL> file.
=head1 BUGS AND LIMITATIONS
Aside from the obvious limitation that happiness is a non-statistical,
I<ad hoc>, non-reportable, and possibly ridiculous parameter, work
needs to be done to tune the various happiness and warnings
parameters.
Other possible penalties:
=over 4
=item *
The stated formula for computing the restraint penalty results in much
too small of a penalty since chi_square is typically much larger than
the restraint evaluation. I am currently playing with just
multiplying the restraint evaluation by the scaling factor.
=item *
Compare reff of each path to the fitting range. Penalize paths well
outside the range (which is probably not such a bad thing) or a range
well beyond the longest path (which is certainly a bad thing in that
it indicates an attempt to inflate Nidp).
=item *
Penalize the use of many e0 parameters, determined by comparing how
many different e0 path param values there are among the paths. The
penalty should apply if the number of e0s is greater than the number
of data sets.
=item *
Penalty parameter type -- like an after parameter but explicitly for
defining new penalties.
=item *
Plugin architecture for user-defined penalties
=back
Please report problems to the Ifeffit Mailing List
(L<http://cars9.uchicago.edu/mailman/listinfo/ifeffit/>)
Patches are welcome.
=head1 AUTHOR
Bruce Ravel, L<http://bruceravel.github.io/home>
L<http://bruceravel.github.io/demeter/>
=head1 LICENCE AND COPYRIGHT
Copyright (c) 2006-2019 Bruce Ravel (L<http://bruceravel.github.io/home>). All rights reserved.
This module is free software; you can redistribute it and/or
modify it under the same terms as Perl itself. See L<perlgpl>.
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.
=cut
|