def print_comparative_outcomes(calibrated_model_no_drug,
                               calibrated_model_with_drug):
    """ prints expected and percentage increase in average survival time when drug is available
    :param calibrated_model_no_drug: calibrated model simulated when drug is not available
    :param calibrated_model_with_drug: calibrated model simulated when drug is available
    """
    # increase in survival time
    increase_stat = Stat.DifferenceStatPaired(
        name='Increase in mean survival time',
        x=calibrated_model_with_drug.multiCohorts.multiCohortOutcomes.
        meanSurvivalTimes,
        y_ref=calibrated_model_no_drug.multiCohorts.multiCohortOutcomes.
        meanSurvivalTimes)
    # mean and prediction interval
    mean = increase_stat.get_mean()
    pred_int = increase_stat.get_PI(alpha=D.ALPHA)

    print(
        "Expected increase in mean survival time (years) and {:.{prec}%} prediction interval:"
        .format(1 - D.ALPHA, prec=0), mean, pred_int)

    # % increase in mean survival time
    relative_diff_stat = Stat.RelativeDifferencePaired(
        name='% increase in mean survival time',
        x=calibrated_model_with_drug.multiCohorts.multiCohortOutcomes.
        meanSurvivalTimes,
        y_ref=calibrated_model_no_drug.multiCohorts.multiCohortOutcomes.
        meanSurvivalTimes)
    # estimate and prediction interval
    mean = relative_diff_stat.get_mean()
    pred_int = relative_diff_stat.get_PI(alpha=D.ALPHA)

    print(
        "Expected percentage increase in mean survival time and {:.{prec}%} confidence interval:"
        .format(1 - D.ALPHA, prec=0), mean, pred_int)
    def extract_outcomes(self, simulated_patients):
        """ extracts outcomes of a simulated cohort
        :param simulated_patients: a list of simulated patients"""

        # record survival time and time until AIDS
        for patient in simulated_patients:
            # survival time
            if patient.stateMonitor.survivalTime is not None:
                self.survivalTimes.append(patient.stateMonitor.survivalTime)
            # time until AIDS
            if patient.stateMonitor.timeToAIDS is not None:
                self.timesToAIDS.append(patient.stateMonitor.timeToAIDS)
            # discounted cost and discounted utility
            self.costs.append(
                patient.stateMonitor.costUtilityMonitor.totalDiscountedCost)
            self.utilities.append(
                patient.stateMonitor.costUtilityMonitor.totalDiscountedUtility)

        # summary statistics
        self.statSurvivalTime = Stat.SummaryStat(name='Survival time',
                                                 data=self.survivalTimes)
        self.statTimeToAIDS = Stat.SummaryStat(name='Time until AIDS',
                                               data=self.timesToAIDS)
        self.statCost = Stat.SummaryStat(name='Discounted cost',
                                         data=self.costs)
        self.statUtility = Stat.SummaryStat(name='Discounted utility',
                                            data=self.utilities)

        # survival curve
        self.nLivingPatients = Path.PrevalencePathBatchUpdate(
            name='# of living patients',
            initial_size=len(simulated_patients),
            times_of_changes=self.survivalTimes,
            increments=[-1] * len(self.survivalTimes))
Esempio n. 3
0
def print_comparative_outcomes(sim_outcomes_none, sim_outcomes_anti):
    """ prints average increase in survival time, discounted cost, and discounted utility
    under combination therapy compared to mono therapy
    :param sim_outcomes_mono: outcomes of a cohort simulated under mono therapy
    :param sim_outcomes_combo: outcomes of a cohort simulated under combination therapy
    """

    # increase in mean survival time under combination therapy with respect to mono therapy
    increase_survival_time = Stat.DifferenceStatIndp(
        name='Increase in mean survival time',
        x=sim_outcomes_anti.survivalTimes,
        y_ref=sim_outcomes_none.survivalTimes)

    # estimate and CI
    estimate_CI = increase_survival_time.get_formatted_mean_and_interval(
        interval_type='c', alpha=D.ALPHA, deci=2)
    print(
        "Increase in mean survival time and {:.{prec}%} confidence interval:".
        format(1 - D.ALPHA, prec=0), estimate_CI)

    # increase in mean discounted cost under combination therapy with respect to mono therapy
    increase_discounted_cost = Stat.DifferenceStatIndp(
        name='Increase in mean discounted cost',
        x=sim_outcomes_anti.costs,
        y_ref=sim_outcomes_none.costs)

    # estimate and CI
    estimate_CI = increase_discounted_cost.get_formatted_mean_and_interval(
        interval_type='c', alpha=D.ALPHA, deci=2, form=',')
    print(
        "Increase in mean discounted cost and {:.{prec}%} confidence interval:"
        .format(1 - D.ALPHA, prec=0), estimate_CI)

    # increase in mean discounted utility under combination therapy with respect to mono therapy
    increase_discounted_utility = Stat.DifferenceStatIndp(
        name='Increase in mean discounted utility',
        x=sim_outcomes_anti.utilities,
        y_ref=sim_outcomes_none.utilities)

    # estimate and CI
    estimate_CI = increase_discounted_utility.get_formatted_mean_and_interval(
        interval_type='c', alpha=D.ALPHA, deci=2)
    print(
        "Increase in mean discounted utility and {:.{prec}%} confidence interval:"
        .format(1 - D.ALPHA, prec=0), estimate_CI)

    # increase in mean discounted utility under combination therapy with respect to mono therapy
    increase_num_strokes = Stat.DifferenceStatIndp(
        name='Increase in mean discounted utility',
        x=sim_outcomes_anti.nTotalStrokes,
        y_ref=sim_outcomes_none.nTotalStrokes)

    # estimate and CI
    estimate_CI = increase_num_strokes.get_formatted_mean_and_interval(
        interval_type='c', alpha=D.ALPHA, deci=2)
    print(
        "Increase in number of strokes and {:.{prec}%} confidence interval:".
        format(1 - D.ALPHA, prec=0), estimate_CI)
Esempio n. 4
0
    def if_acceptable(self, scenario):
        """ :returns True if this scenario meets the conditions to be on this series """

        if self.scenarioNames is not None:
            # if the name of this scenario is included
            if scenario.name in self.scenarioNames:
                return True
        else:
            for condition in self.varConditions:
                if condition.values is None:
                    if scenario.variables[condition.varName] < condition.min \
                            or scenario.variables[condition.varName] > condition.max:
                        return False
                else:
                    if not (scenario.variables[condition.varName]
                            in condition.values):
                        return False

            for condition in self.outcomeConditions:
                if condition.values is None:
                    # mean of this outcome
                    mean = Stat.SummaryStat(
                        name=condition.outcomeName,
                        data=scenario.outcomes[
                            condition.outcomeName]).get_mean()

                    if mean < condition.min or mean > condition.max:
                        return False

        return True
Esempio n. 5
0
    def get_diff_mean_interval(self,
                               scenario_name_base,
                               scenario_names,
                               outcome_name,
                               deci=0,
                               form=None,
                               multiplier=1,
                               interval_type='p'):

        if type(scenario_names) is not list:
            scenario_names = [scenario_names]

        list_mean_PI = {}
        for name in scenario_names:
            stat = Stat.DifferenceStatPaired(
                name='',
                x=self.scenarios[name].outcomes[outcome_name],
                y_ref=self.scenarios[scenario_name_base].outcomes[outcome_name]
            )

            list_mean_PI[name] = Support.get_mean_interval(
                stat=stat,
                interval_type=interval_type,
                deci=deci,
                form=form,
                multiplier=multiplier)

        if len(scenario_names) == 1:
            return list_mean_PI[scenario_names[0]]
        else:
            return list_mean_PI
Esempio n. 6
0
    def get_relative_diff_mean_interval(self,
                                        scenario_name_base,
                                        scenario_names,
                                        outcome_name,
                                        deci=0,
                                        form=None):
        """
        :return: dictionary of mean and percentile interval of the relative difference of the selected outcome
        """

        if type(scenario_names) is not list:
            scenario_names = [scenario_names]

        list_mean_PI = {}
        for name in scenario_names:
            ratio_state = Stat.RelativeDifferencePaired(
                name='',
                x=self.scenarios[name].outcomes[outcome_name],
                y_ref=self.scenarios[scenario_name_base].
                outcomes[outcome_name],
                order=1)

            list_mean_PI[name] = Support.get_mean_interval(stat=ratio_state,
                                                           interval_type='p',
                                                           deci=deci,
                                                           form=form)

        if len(scenario_names) == 1:
            return list_mean_PI[scenario_names[0]]
        else:
            return list_mean_PI
Esempio n. 7
0
 def __init__(self,
              name,
              delta_t,
              sim_rep=0,
              collect_stat=True,
              warm_up_period=0):
     """
     :param name: name of this sample path
     :param delta_t: length of equally-spaced observation periods
     :param sim_rep: (int) simulation replication of this sample path
     :param collect_stat: set to True to collect statistics on average, max, min, stDev, etc for this sample path
     :param warm_up_period: warm up period (observations before this time will not be used to calculate statistics)
     """
     _SamplePath.__init__(self,
                          name=name,
                          sim_rep=sim_rep,
                          collect_stat=collect_stat,
                          warm_up_period=warm_up_period)
     self._deltaT = delta_t
     self._period_num = 0
     self._warm_up_period = warm_up_period
     self._period_nums = []  # times represent the observation period number
     self._values = []
     # statistics on this incidence sample path
     if self.ifCollectStat:
         self.stat = Stat.DiscreteTimeStat(name=name)
Esempio n. 8
0
 def __init__(self,
              name,
              initial_size=0,
              sim_rep=0,
              collect_stat=True,
              ave_method='step',
              warm_up_period=0):
     """
     :param name: name of this sample path
     :param initial_size: value of the sample path at simulation time 0
     :param sim_rep: (int) simulation replication of this sample path
     :param collect_stat: set to True to collect statistics
                     on average, max, min, stDev, etc for this sample path
     :param ave_method: to calculate the area under the curve,
         'step' assumes that changes occurred at the time where observations are recorded,
         'linear' assumes uses trapezoid approach to calculate the area under the curve
     :param warm_up_period: warm up period (observations before this time will not be used to calculate statistics)
     """
     _SamplePath.__init__(self,
                          name=name,
                          sim_rep=sim_rep,
                          collect_stat=collect_stat,
                          warm_up_period=warm_up_period)
     self.currentSize = initial_size  # current size of the sample path
     self._times = [0]
     self._values = [initial_size]
     # statistics on this prevalence sample path
     if collect_stat:
         self.stat = Stat.ContinuousTimeStat(name=name,
                                             initial_time=warm_up_period,
                                             ave_method=ave_method)
def print_comparative_outcomes(multi_cohort_outcomes_mono,
                               multi_cohort_outcomes_combo):
    """ prints average increase in survival time, discounted cost, and discounted utility
    under combination therapy compared to mono therapy
    :param multi_cohort_outcomes_mono: outcomes of a multi-cohort simulated under mono therapy
    :param multi_cohort_outcomes_combo: outcomes of a multi-cohort simulated under combination therapy
    """

    # increase in mean survival time under combination therapy with respect to mono therapy
    increase_mean_survival_time = Stat.DifferenceStatPaired(
        name='Increase in mean survival time',
        x=multi_cohort_outcomes_combo.meanSurvivalTimes,
        y_ref=multi_cohort_outcomes_mono.meanSurvivalTimes)

    # estimate and PI
    estimate_PI = increase_mean_survival_time.get_formatted_mean_and_interval(
        interval_type='p', alpha=D.ALPHA, deci=2)
    print(
        "Increase in mean survival time and {:.{prec}%} uncertainty interval:".
        format(1 - D.ALPHA, prec=0), estimate_PI)

    # increase in mean discounted cost under combination therapy with respect to mono therapy
    increase_mean_discounted_cost = Stat.DifferenceStatPaired(
        name='Increase in mean discounted cost',
        x=multi_cohort_outcomes_combo.meanCosts,
        y_ref=multi_cohort_outcomes_mono.meanCosts)

    # estimate and PI
    estimate_PI = increase_mean_discounted_cost.get_formatted_mean_and_interval(
        interval_type='p', alpha=D.ALPHA, deci=2, form=',')
    print(
        "Increase in mean discounted cost and {:.{prec}%} uncertainty interval:"
        .format(1 - D.ALPHA, prec=0), estimate_PI)

    # increase in mean discounted QALY under combination therapy with respect to mono therapy
    increase_mean_discounted_qaly = Stat.DifferenceStatPaired(
        name='Increase in mean discounted QALY',
        x=multi_cohort_outcomes_combo.meanQALYs,
        y_ref=multi_cohort_outcomes_mono.meanQALYs)

    # estimate and PI
    estimate_PI = increase_mean_discounted_qaly.get_formatted_mean_and_interval(
        interval_type='p', alpha=D.ALPHA, deci=2)
    print(
        "Increase in mean discounted utility and {:.{prec}%} uncertainty interval:"
        .format(1 - D.ALPHA, prec=0), estimate_PI)
Esempio n. 10
0
    def calculate_summary_stats(self):
        """
        calculate the summary statistics
        """

        # summary statistics of mean survival time
        self.statMeanSurvivalTime = Stat.SummaryStat(
            name='Average survival time', data=self.meanSurvivalTimes)
        # summary statistics of mean time to AIDS
        self.statMeanTimeToAIDS = Stat.SummaryStat(name='Average time to AIDS',
                                                   data=self.meanTimeToAIDS)
        # summary statistics of mean cost
        self.statMeanCost = Stat.SummaryStat(name='Average cost',
                                             data=self.meanCosts)
        # summary statistics of mean QALY
        self.statMeanQALY = Stat.SummaryStat(name='Average QALY',
                                             data=self.meanQALYs)
Esempio n. 11
0
    def calculate_cohort_outcomes(self, initial_pop_size):
        """ calculates the cohort outcomes
        :param initial_pop_size: initial population size
        """
        self.statSurvivalTime = Stat.SummaryStat(name='Survival Time',
                                                 data=self.survivalTimes)
        self.statCost = Stat.SummaryStat(name='Discounted cost',
                                         data=self.costs)
        self.statUtility = Stat.SummaryStat(name='Discounted utility',
                                            data=self.utilities)
        self.statNumStrokes = Stat.SummaryStat(name='Total Number of Strokes',
                                               data=self.nStrokes)

        self.nLivingPatients = Path.PrevalencePathBatchUpdate(
            name='# of living patients',
            initial_size=initial_pop_size,
            times_of_changes=self.survivalTimes,
            increments=[-1] * len(self.survivalTimes))
Esempio n. 12
0
def mytest_discrete_time(data):
    # define a discrete-time statistics
    discrete_stat = Stat.DiscreteTimeStat('Test discrete-time statistics')
    # record data points
    for point in data:
        discrete_stat.record(point)

    print('Testing discrete-time statistics:')
    print_results(discrete_stat)
Esempio n. 13
0
    def get_ratio_mean_interval(self, numerator_par_name, denominator_par_names, deci=0, form=None):

        # print the ratio estimate and credible interval
        sum_stat = Stat.SummaryStat('', self.__calculate_ratio_obss(numerator_par_name, denominator_par_names))

        if form is None:
            return sum_stat.get_mean(), sum_stat.get_PI(alpha=0.05)
        else:
            return sum_stat.get_formatted_mean_and_interval(
                interval_type='p', alpha=0.05, deci=deci, form=form)
Esempio n. 14
0
    def get_cohort_PI_survival(self, cohort_index, alpha):
        """ :returns: the prediction interval of the survival time for a specified cohort
        :param cohort_index: integer over [0, 1, ...] corresponding to the 1st, 2ndm ... simulated cohort
        :param alpha: significance level
        """

        stat = Stat.SummaryStat(name='Summary statistics',
                                data=self.survivalTimes[cohort_index])

        return stat.get_PI(alpha=alpha)
Esempio n. 15
0
    def get_mean_interval(self, parameter_name, deci=0, form=None):

        # print the ratio estimate and credible interval
        sum_stat = Stat.SummaryStat('', self.dictOfParamValues[parameter_name])

        if form is None:
            return sum_stat.get_mean(), sum_stat.get_PI(alpha=0.05)
        else:
            return sum_stat.get_formatted_mean_and_interval(
                interval_type='p', alpha=0.05, deci=deci, form=form)
Esempio n. 16
0
    def simulate(self, n):

        for i in range(n):
            model = Model(decision_rule=self.decisionRule,
                          cost_sigma=self.costSigma,
                          action_cost=self.actionCost)
            model.simulate(itr=i)
            self.cumCosts.append(sum(model.seqCosts))

        self.statCost = S.SummaryStat(data=self.cumCosts)
Esempio n. 17
0
    def calculate_summary_stats(self):
        """
        calculate the summary statistics
        """

        # calculate average patient survival time for all simulated cohorts
        for obs_set in self.survivalTimes:
            self.meanSurvivalTimes.append(sum(obs_set) / len(obs_set))

        # summary statistics of mean survival time
        self.statMeanSurvivalTime = Stat.SummaryStat(
            name='Mean survival time', data=self.meanSurvivalTimes)
Esempio n. 18
0
    def get_mortality_estimate_credible_interval(self, alpha):
        """
        :param alpha: the significance level
        :returns tuple (mean, [lower, upper]) of the posterior distribution"""

        # calculate the credible interval
        sum_stat = Stat.SummaryStat(name='Posterior samples',
                                    data=self.resampledMortalityProb)

        estimate = sum_stat.get_mean()  # estimated mortality probability
        credible_interval = sum_stat.get_PI(alpha=alpha)  # credible interval

        return estimate, credible_interval
Esempio n. 19
0
    def get_mean_interval(self,
                          scenario_name,
                          outcome_name,
                          interval_type='c',
                          deci=0,
                          form=None):
        """
        :return: mean and percentile interval of the selected outcome for the selected scenario
        """

        stat = Stat.SummaryStat(
            name='', data=self.scenarios[scenario_name].outcomes[outcome_name])
        return Support.get_mean_interval(stat, interval_type, deci, form)
Esempio n. 20
0
def mytest_continuous_time(times, observations):
    # define a continuous-time statistics
    continuous_stat = Stat.ContinuousTimeStat(initial_time=0, name='Test continuous-time statistics')

    for obs in range(0, len(times)):
        # find the increment
        inc = 0
        if obs == 0:
            inc = observations[obs]
        else:
            inc = observations[obs] - observations[obs - 1]
        continuous_stat.record(times[obs], inc)

    print('Testing continuous-time statistics:')
    print_results(continuous_stat)
Esempio n. 21
0
def utility_sample_stat(utility, d_cost_samples, d_effect_samples,
                        wtp_random_variate, n_samples, rnd):

    discrete_rnd = RVG.UniformDiscrete(l=0, u=len(d_cost_samples) - 1)

    samples = []
    for i in range(n_samples):
        j = discrete_rnd.sample(rnd)

        u = utility(d_effect=d_effect_samples[j], d_cost=d_cost_samples[j])

        w = wtp_random_variate.sample(rnd)
        samples.append(u(w))

    return Stat.SummaryStat(name='', data=samples)
Esempio n. 22
0
def print_comparative_outcomes(cohort_no_drug, cohort_with_drug):
    """ prints expected and percentage increase in survival time when drug is available
    :param cohort_no_drug: a cohort simulated when drug is not available
    :param cohort_with_drug: a cohort simulated when drug is available
    """

    # create a difference statistics for the increase in survival time
    increase_stat = Stat.DifferenceStatIndp(
        name='Increase in survival time',
        x=cohort_with_drug.cohortOutcomes.survivalTimes,
        y_ref=cohort_no_drug.cohortOutcomes.survivalTimes)

    # get mean and t-based confidence interval for the increase in survival time
    mean = increase_stat.get_mean()
    conf_int = increase_stat.get_t_CI(alpha=D.ALPHA)

    print(
        "Average increase in survival time (years) and {:.{prec}%} confidence interval:"
        .format(1 - D.ALPHA, prec=0), mean, conf_int)
Esempio n. 23
0
def print_outcomes(multi_cohort, strategy_name):
    """ prints the outcomes of a simulated cohort under steady state
    :param multi_cohort: output of a simulated cohort
    :param strategy_name: the name of the selected therapy
    """

    # create a summary statistics
    survival_time_stat = Stat.SummaryStat(
        name='Survival time statistics',
        data=multi_cohort.multiCohortOutcomes.meanSurvivalTimes)

    # get mean and t-based confidence interval
    mean = survival_time_stat.get_mean()
    pred_int = survival_time_stat.get_PI(alpha=D.ALPHA)

    # print survival time statistics
    print(strategy_name)
    print(
        "  Estimate of mean survival time (years) and {:.{prec}%} prediction interval:"
        .format(1 - D.ALPHA, prec=0), mean, pred_int)
Esempio n. 24
0
def print_outcomes(simulated_cohort, strategy_name):
    """ prints the outcomes of a simulated cohort under steady state
    :param simulated_cohort: a simulated cohort
    :param strategy_name: the name of the selected therapy
    """

    # create a summary statistics
    survival_time_stat = Stat.SummaryStat(
        name='Survival time statistics',
        data=simulated_cohort.cohortOutcomes.survivalTimes)

    # get mean and confidence confidence interval
    mean = survival_time_stat.get_mean()
    conf_int = survival_time_stat.get_t_CI(alpha=D.ALPHA)

    # print survival time statistics
    print(strategy_name)
    print(
        "  Estimate of mean survival time (years) and {:.{prec}%} confidence interval:"
        .format(1 - D.ALPHA, prec=0), mean, conf_int)
Esempio n. 25
0
    def get_means_and_intervals(self, significance_level=0.05, sig_digits=3,
                                param_names=None, prior_info_csv_file=None):
        """
        :param significance_level: (float) significant level to calculate confidence or credible intervals
        :param sig_digits: (int) number of significant digits
        :param param_names: (list) of parameter names
        :param prior_info_csv_file: (string)
        :return:
        """

        results = []  # list of parameter estimates and credible intervals

        # read information about prior distributions
        dict_of_priors = None
        if prior_info_csv_file is not None:
            dict_of_priors = self.get_dict_of_priors(prior_info_csv_file=prior_info_csv_file)

        # if parameter names are not specified, include all parameters
        if param_names is None:
            param_names = self.get_all_parameter_names()

        # for each parameter get mean and  intervals
        for par_name in param_names:

            # get values for this parameter
            par_values = self.dictOfParamValues[par_name]

            # get info of this parameter
            title, multiplier, x_range, decimal, form = self.get_title_multiplier_x_range_decimal_format(
                par_name=par_name, dict_of_priors=dict_of_priors)

            # summary statistics
            sum_stat = Stat.SummaryStat(name=par_name, data=par_values)
            mean_PI_text = sum_stat.get_formatted_mean_and_interval(
                interval_type='p', alpha=significance_level, deci=decimal, sig_digits=sig_digits,
                form=form, multiplier=multiplier)

            results.append(
                [par_name, mean_PI_text])

        return results
Esempio n. 26
0
    def get_relative_diff_mean_PI(self,
                                  time_index0,
                                  time_index1,
                                  order=0,
                                  deci=0,
                                  format=None):
        """
        :return: the mean relative difference of trajectories at two time indeces
        """
        stat = Stat.RelativeDifferencePaired('',
                                             x=self.get_obss(time_index1),
                                             y_ref=self.get_obss(time_index0),
                                             order=order)

        if format is None:
            return stat.get_mean(), stat.get_PI(alpha=0.05)
        else:
            return stat.get_formatted_mean_and_interval(interval_type='p',
                                                        alpha=0.05,
                                                        deci=deci,
                                                        form=format)
Esempio n. 27
0
    def get_mean_PI(self,
                    time_index,
                    alpha,
                    multiplier=1,
                    deci=0,
                    format=None):
        """
        :param format: additional formatting instruction.
            Use ',' to format as number, '%' to format as percentage, and '$' to format as currency
        :return: the mean and percentile interval of observations at the specified time index formatted as instructed
        """

        # find the estimate and percentile interval
        stat = Stat.SummaryStat('', self.get_obss(time_index) * multiplier)
        estimate, pi = stat.get_mean(), stat.get_PI(alpha)

        if format is None:
            return estimate, pi
        else:
            return F.format_estimate_interval(estimate=estimate,
                                              interval=pi,
                                              deci=deci,
                                              format=format)
import SimPy.Plots.Histogram as Hist
import SimPy.Plots.ProbDist as Plot
import SimPy.RandomVariateGenerators as RVGs
import SimPy.Statistics as Stat

# read weekly number of drinks
cols = IO.read_csv_cols(file_name='dataNumOfDrinks.csv',
                        n_cols=1,
                        if_ignore_first_row=True,
                        if_convert_float=True)

# make a histogram
Hist.plot_histogram(data=cols[0], title='Weekly Number of Drinks', bin_width=1)

# mean and standard deviation
stat = Stat.SummaryStat(name='Weekly number of drinks', data=cols[0])
print('Mean = ', stat.get_mean())
print('StDev = ', stat.get_stdev())

# fit a Poisson distribution
fit_results = RVGs.Poisson.fit_ml(data=cols[0])
print('Fitting a Poisson distribution:', fit_results)

# plot the fitted Poisson distribution
Plot.plot_poisson_fit(data=cols[0],
                      fit_results=fit_results,
                      x_label='Weekly number of drinks',
                      x_range=(0, 40),
                      bin_width=1)

# fit a gamma-Poisson distribution
Esempio n. 29
0
def mytest_relativeDiff_stat_indp(x, y):
    # define
    stat = Stat.RelativeDifferenceIndp(x, y, name='Test RelativeDifferenceIndp')

    print('Testing RelativeDifferenceIndp:')
    print_results(stat)
Esempio n. 30
0
    def populate_sets_of_scenarios(list_of_scenario_sets,
                                   save_cea_results=False,
                                   colors_of_scenarios=None,
                                   interval_type='n',
                                   effect_multiplier=1,
                                   cost_multiplier=1,
                                   switch_cost_effect_on_figure=False,
                                   wtp_range=None):
        """
        :param list_of_scenario_sets: (list) of sets of scenarios
        :param save_cea_results: set it to True if the CE table should be generated
        :param colors_of_scenarios: (dictionary) of colors for scenarios
        :param interval_type: select from Econ.Interval (no interval, CI, or PI)
        :param effect_multiplier:
        :param cost_multiplier:
        :param switch_cost_effect_on_figure: displays cost on the x-axis and effect on the y-axis
        :param wtp_range: for net monetary benefit analysis
        """

        # populate series to display on the cost-effectiveness plane
        for i, scenario_set in enumerate(list_of_scenario_sets):

            if scenario_set.ifPopulated:
                continue

            # create the base strategy
            scn = scenario_set.scenarioDF.scenarios['Base']
            base_strategy = Econ.Strategy(
                name='Base',
                label='Base',
                cost_obs=scn.outcomes[COST_MEASURE],
                effect_obs=scn.outcomes[HEALTH_MEASURE],
                color=None
                if colors_of_scenarios is None else colors_of_scenarios[0])

            # add base
            scenario_set.strategies = [base_strategy]
            # add other scenarios
            i = 0
            for key, scenario in scenario_set.scenarioDF.scenarios.items():
                # add only non-Base strategies that can be on this series
                if scenario.name != 'Base' and scenario_set.if_acceptable(
                        scenario):

                    # find labels of each strategy
                    label_list = []
                    for varCon in scenario_set.varConditions:
                        if varCon.ifIncludedInLabel:

                            # value of this variable
                            value = scenario.variables[varCon.varName]
                            # if there is not label rules
                            if varCon.labelRules is None:
                                if varCon.labelFormat == '':
                                    label_list.append(str(value) + ',')
                                else:
                                    label_list.append(
                                        varCon.labelFormat.format(value) +
                                        ', ')
                            else:
                                label = varCon.get_label(value)
                                if label == '':
                                    pass
                                else:
                                    label_list.append(label + ', ')

                    for outcomeCon in scenario_set.outcomeConditions:
                        if outcomeCon.ifIncludedInLabel:

                            # value of this variable
                            value = Stat.SummaryStat(
                                name=outcomeCon.outcomeName,
                                data=scenario.outcomes[
                                    outcomeCon.outcomeName]).get_mean()
                            # if there is not label rules
                            if outcomeCon.labelRules is None:
                                if outcomeCon.labelFormat == '':
                                    label_list.append(str(value) + ',')
                                else:
                                    label_list.append(
                                        outcomeCon.labelFormat.format(value) +
                                        ', ')
                            else:
                                label = outcomeCon.get_label(value)
                                if label == '':
                                    pass
                                else:
                                    label_list.append(label + ', ')

                    label = ''.join(str(x) for x in label_list)

                    if len(label) > 0:
                        if label[-1] == ' ' or label[-1] == ',':
                            label = label[:-1]
                        if label[-1] == ' ' or label[-1] == ',':
                            label = label[:-1]

                    # legends
                    scenario_set.legend.append(label)

                    # color of this strategy
                    color = None
                    if colors_of_scenarios is not None:
                        color = colors_of_scenarios[i + 1]

                    if scenario_set.xyLabelsProvided:
                        label = scenario_set.xyLabels[i]

                    scenario_set.strategies.append(
                        Econ.Strategy(
                            name=scenario.name,
                            label=label,
                            cost_obs=scenario.outcomes[COST_MEASURE],
                            effect_obs=scenario.outcomes[HEALTH_MEASURE],
                            color=color))
                    i += 1

            # do CEA on this series
            scenario_set.build_CE_curve(
                save_cea_results=save_cea_results,
                interval_type=interval_type,
                effect_multiplier=effect_multiplier,
                cost_multiplier=cost_multiplier,
                switch_cost_effect_on_figure=switch_cost_effect_on_figure,
                wtp_range=wtp_range)

            scenario_set.ifPopulated = True