package DoseMe::Algorithms::PopulationModelSuitability;

use v5.36;

use strict;
use warnings;
use utf8;

use version; our $VERSION = qv('0.3.1');

# ABSTRACT: Methods and algorithms that estimate model suitability based on patient's demographics and their distribution within the model's population sample.

use Exporter;
use base 'Exporter';
use Carp qw(confess);
use DoseMe::Algorithms::Distributions::BCCG;
use DoseMe::Util::Types;

our @ISA = qw(Exporter);
our @EXPORT = qw(
    estimate_population_model_suitability_score
    estimate_population_model_suitability_significance
);



### -- Unit.Accept:PatientParams.Undefined.True
### -- Unit.Fault:PatientParams.Invalid{Height,Age,Weight,Sex}
### -- Unit.Accept:PatientPopDistributions.Undefined.True
### -- Unit.Fault:PatientPopDistributions.Age.Invalid{Mu,Sigma,Nu}
### -- Unit.Fault:PatientPopDistributions.Weight.Invalid{Mu,Sigma,Nu}
### -- Unit.Fault:PatientPopDistributions.Female.Invalid{P}
sub estimate_population_model_suitability_score {
    my ($patient, $patient_pop_distributions) = @_;

    # Note: we do not require patient height to estimate the population model suitability score.
    # However, we are forcing the height information to be present in $patient
    DoseMe::Util::Types::Verify::patientref($patient);

    if (defined $patient_pop_distributions) {

        my $patient_age = $patient->{age};
        my $patient_weight = $patient->{weight};
        my $patient_sex = $patient->{sex};

        my $pop_age_mu = $patient_pop_distributions->{age}{mu};
        DoseMe::Util::Types::verify_positive($pop_age_mu);
        my $pop_age_sigma = $patient_pop_distributions->{age}{sigma};
        DoseMe::Util::Types::verify_positive($pop_age_sigma);
        my $pop_age_nu = $patient_pop_distributions->{age}{nu};
        DoseMe::Util::Types::verify_numeric($pop_age_nu);

        my $pop_weight_mu = $patient_pop_distributions->{weight}{mu};
        DoseMe::Util::Types::verify_positive($pop_weight_mu);
        my $pop_weight_sigma = $patient_pop_distributions->{weight}{sigma};
        DoseMe::Util::Types::verify_positive($pop_weight_sigma);
        my $pop_weight_nu = $patient_pop_distributions->{weight}{nu};
        DoseMe::Util::Types::verify_numeric($pop_weight_nu);

        my $pop_female_p = $patient_pop_distributions->{female}{p};
        DoseMe::Util::Types::verify_nonnegative($pop_female_p);
        # FIXME: Add 'verify_pvalue()' to DoseMe::Util::Types
        confess("Invalid value binomial p value \"$pop_female_p\"\n") if ($pop_female_p > 1);

        my $age_z = undef;
        if ($patient_age > $pop_age_mu) {
            $age_z = bccg_cdf($patient_age, $pop_age_mu, $pop_age_sigma, $pop_age_nu, 0);
        }
        else {
            $age_z = bccg_cdf($patient_age, $pop_age_mu, $pop_age_sigma, $pop_age_nu, 1);
        }

        my $weight_z = undef;
        if ($patient_weight > $pop_weight_mu) {
            $weight_z = bccg_cdf($patient_weight, $pop_weight_mu, $pop_weight_sigma, $pop_weight_nu, 0);
        }
        else {
            $weight_z = bccg_cdf($patient_weight, $pop_weight_mu, $pop_weight_sigma, $pop_weight_nu, 1);
        }

        my $sex_binomp = undef;
        if ($patient_sex eq 'Male') {
            $sex_binomp = 1 - $pop_female_p;
        }
        else {
            $sex_binomp = $pop_female_p;
        }

        my $population_model_suitability_score = $age_z * $weight_z * $sex_binomp;
        return $population_model_suitability_score;

    }
    return;
}



### -- Unit.Accept:PopModSuitabilityScore.Undefined.True
### -- Unit.Accept:BackgroundPopDistributions.Undefined.True
### -- Unit.Fault:PatientPopDistributions.Background.Invalid{Mu,Sigma,Nu}
sub estimate_population_model_suitability_significance {
    my ($population_model_suitability_score, $bg_pop_distributions) = @_;

    return unless (defined $population_model_suitability_score && defined $bg_pop_distributions);

    my $bg_score_mu = $bg_pop_distributions->{background}{mu};
    DoseMe::Util::Types::verify_positive($bg_score_mu);
    my $bg_score_sigma = $bg_pop_distributions->{background}{sigma};
    DoseMe::Util::Types::verify_positive($bg_score_sigma);
    my $bg_score_nu = $bg_pop_distributions->{background}{nu};
    DoseMe::Util::Types::verify_numeric($bg_score_nu);

    return bccg_cdf($population_model_suitability_score, $bg_score_mu, $bg_score_sigma, $bg_score_nu, 0);
}


# A Perl module must end with a true value or else it is considered not to
# have loaded.  By convention this value is usually 1 though it can be
# any true value.  A module can end with false to indicate failure but
# this is rarely used and it would instead die() (exit with an error).
1;

__END__

=pod

=encoding UTF-8

=head1 NAME

DoseMe::Algorithms::PopulationModelSuitability - Methods and algorithms that estimate model suitability based on patient's demographics and their distribution within the model's population sample.

=head1 VERSION

version 0.3.1

=head2 estimate_population_model_suitability_score

Returns the population model suitability score for a patient for a drug model

Params:
    patient : patient to compute the population model suitability score for
    patient_pop_distributions: demographics distribution information for the drug model

=head2 estimate_population_model_suitability_significance

Returns significance (p - value) for estimated model suitability score compared to the next best drug model

Params:
    population_model_suitability_score : population model suitability score of the best model suited model for a patient
    bg_pop_distributions: demographics distribution information for the drug model with the next best population model suitability score of that patient

=head1 AUTHOR

Anita Sathyanarayanan

=head1 LICENCE AND COPYRIGHT

Copyright (c) 2023, DoseMe Pty Ltd. All rights reserved.

This module is not for distribution. It is for internal DoseMe use only.

=head1 DISCLAIMER OF WARRANTY

THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE
LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER
PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE
QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR
CORRECTION.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY
COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE
SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO
LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR
THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.

=head1 AUTHOR

DoseMe Pty Ltd <software@doseme.com.au>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2025 by DoseMe Pty Ltd.  No
license is granted to other entities.

=cut
