Skip to content

Inference

Comparison and optimization of model spectra to data.

Anscombe_Poisson_residual(model, data, mask=None)

Return the Anscombe Poisson residuals between model and data.

mask sets the level in model below which the returned residual array is masked. This excludes very small values where the residuals are not normal. 1e-2 seems to be a good default for the NIEHS human data. (model = 1e-2, data = 0, yields a residual of ~1.5.)

Residuals defined in this manner are more normally distributed than the linear residuals when the mean is small. See this reference below for justification: Pierce DA and Schafer DW, "Residuals in generalized linear models" Journal of the American Statistical Association, 81(396)977-986 (1986).

Note that I tried implementing the "adjusted deviance" residuals, but they always looked very biased for the cases where the data was 0.

Source code in dadi/Inference.py
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
def Anscombe_Poisson_residual(model, data, mask=None):
    """
    Return the Anscombe Poisson residuals between model and data.

    mask sets the level in model below which the returned residual array is
    masked. This excludes very small values where the residuals are not normal.
    1e-2 seems to be a good default for the NIEHS human data. (model = 1e-2,
    data = 0, yields a residual of ~1.5.)

    Residuals defined in this manner are more normally distributed than the
    linear residuals when the mean is small. See this reference below for
    justification: Pierce DA and Schafer DW, "Residuals in generalized linear
    models" Journal of the American Statistical Association, 81(396)977-986
    (1986).

    Note that I tried implementing the "adjusted deviance" residuals, but they
    always looked very biased for the cases where the data was 0.
    """
    if hasattr(data, 'folded') and data.folded and not model.folded:
        model = model.fold()
    if hasattr(data, 'folded_ancestral') and data.folded_ancestral\
       and not model.folded_ancestral:
        model = model.fold_ancestral()
    if hasattr(data, 'folded_major') and data.folded_major\
       and not model.folded_major:
        model = model.fold_major()
    # Because my data have often been projected downward or averaged over many
    # iterations, it appears better to apply the same transformation to the data
    # and the model.
    # For some reason data**(-1./3) results in entries in data that are zero
    # becoming masked. Not just the result, but the data array itself. We use
    # the power call to get around that.
    # This seems to be a common problem, that we want to use numpy.ma functions
    # on masked arrays, because otherwise the mask on the input itself can be
    # changed. Subtle and annoying. If we need to create our own functions, we
    # can use numpy.ma.core._MaskedUnaryOperation.
    datatrans = data**(2./3) - numpy.ma.power(data,-1./3)/9
    modeltrans = model**(2./3) - numpy.ma.power(model,-1./3)/9
    resid = 1.5*(datatrans - modeltrans)/model**(1./6)
    if mask is not None:
        tomask = numpy.logical_and(model <= mask, data <= mask)
        tomask = numpy.logical_or(tomask, data == 0)
        resid = numpy.ma.masked_where(tomask, resid)
    # It makes more sense to me to have a minus sign here... So when the
    # model is high, the residual is positive. This is opposite of the
    # Pierce and Schafner convention.
    return -resid

add_misid_param(func)

Add parameter to model ancestral state misidentification.

The returned function will have an additional element of the params list, which is the proportion of segregating sites whose ancestral state were misidentified.

Source code in dadi/Inference.py
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
def add_misid_param(func):
    """
    Add parameter to model ancestral state misidentification.

    The returned function will have an additional element of the params
    list, which is the proportion of segregating sites whose ancestral state
    were misidentified.
    """
    warnings.warning("Inference.add_misid_param is deprecated. Please use the updated Numerics.make_anc_state_misd_func instead.\n", FutureWarning)
    def misid_func(params, *args, **kwargs):
        misid = params[-1]
        fs = func(params[:-1], *args, **kwargs)
        return (1-misid)*fs + misid*Numerics.reverse_array(fs)
    misid_func.__name__ = func.__name__
    misid_func.__doc__ = func.__doc__
    return misid_func

linear_Poisson_residual(model, data, mask=None)

Return the Poisson residuals, (model - data)/sqrt(model), of model and data.

mask sets the level in model below which the returned residual array is masked. The default of 0 excludes values where the residuals are not defined.

In the limit that the mean of the Poisson distribution is large, these residuals are normally distributed. (If the mean is small, the Anscombe residuals are better.)

Source code in dadi/Inference.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
def linear_Poisson_residual(model, data, mask=None):
    """
    Return the Poisson residuals, (model - data)/sqrt(model), of model and data.

    mask sets the level in model below which the returned residual array is
    masked. The default of 0 excludes values where the residuals are not 
    defined.

    In the limit that the mean of the Poisson distribution is large, these
    residuals are normally distributed. (If the mean is small, the Anscombe
    residuals are better.)
    """
    if hasattr(data, 'folded') and data.folded and not model.folded:
        model = model.fold()
    if hasattr(data, 'folded_ancestral') and data.folded_ancestral\
       and not model.folded_ancestral:
        model = model.fold_ancestral()
    if hasattr(data, 'folded_major') and data.folded_major\
       and not model.folded_major:
        model = model.fold_major()

    resid = (model - data)/numpy.ma.sqrt(model)
    if mask is not None:
        tomask = numpy.logical_and(model <= mask, data <= mask)
        resid = numpy.ma.masked_where(tomask, resid)
    return resid

ll(model, data)

The log-likelihood of the data given the model sfs.

Evaluate the log-likelihood of the data given the model. This is based on Poisson statistics, where the probability of observing k entries in a cell given that the mean number is given by the model is P(k) = exp(-model) * model**k / k!

Note

If either the model or the data is a masked array, the return ll will ignore any elements that are masked in either the model or the data.

Source code in dadi/Inference.py
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
def ll(model, data):
    """
    The log-likelihood of the data given the model sfs.

    Evaluate the log-likelihood of the data given the model. This is based on
    Poisson statistics, where the probability of observing k entries in a cell
    given that the mean number is given by the model is 
    P(k) = exp(-model) * model**k / k!

    Note: 
        If either the model or the data is a masked array, the return ll will
          ignore any elements that are masked in *either* the model or the data.
    """
    ll_arr = ll_per_bin(model, data)
    return ll_arr.sum()

ll_multinom(model, data)

Log-likelihood of the data given the model, with optimal rescaling.

Evaluate the log-likelihood of the data given the model. This is based on Poisson statistics, where the probability of observing k entries in a cell given that the mean number is given by the model is P(k) = exp(-model) * model**k / k!

model is optimally scaled to maximize ll before calculation.

Note

If either the model or the data is a masked array, the return ll will ignore any elements that are masked in either the model or the data.

Source code in dadi/Inference.py
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
def ll_multinom(model, data):
    """
    Log-likelihood of the data given the model, with optimal rescaling.

    Evaluate the log-likelihood of the data given the model. This is based on
    Poisson statistics, where the probability of observing k entries in a cell
    given that the mean number is given by the model is 
    P(k) = exp(-model) * model**k / k!

    model is optimally scaled to maximize ll before calculation.

    Note:
        If either the model or the data is a masked array, the return ll will
          ignore any elements that are masked in *either* the model or the data.
    """
    ll_arr = ll_multinom_per_bin(model, data)
    return ll_arr.sum()

ll_multinom_per_bin(model, data)

Mutlinomial log-likelihood of each entry in the data given the model.

Scales the model sfs to have the optimal theta for comparison with the data.

Source code in dadi/Inference.py
550
551
552
553
554
555
556
557
def ll_multinom_per_bin(model, data):
    """
    Mutlinomial log-likelihood of each entry in the data given the model.

    Scales the model sfs to have the optimal theta for comparison with the data.
    """
    theta_opt = optimal_sfs_scaling(model, data)
    return ll_per_bin(theta_opt*model, data)

ll_per_bin(model, data, missing_model_cutoff=1e-06)

The Poisson log-likelihood of each entry in the data given the model sfs.

Parameters:

Name Type Description Default
model Spectrum

Model spectrum.

required
data Spectrum

Data spectrum.

required
missing_model_cutoff float

Due to numerical issues, there may be entries in the FS that cannot be stable calculated. If these entries involve a fraction of the data larger than missing_model_cutoff, a warning is printed.

1e-06
Source code in dadi/Inference.py
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
544
545
546
547
def ll_per_bin(model, data, missing_model_cutoff=1e-6):
    """
    The Poisson log-likelihood of each entry in the data given the model sfs.

    Args:
        model (Spectrum): Model spectrum.
        data (Spectrum): Data spectrum.
        missing_model_cutoff (float): Due to numerical issues, there may be entries in the
                            FS that cannot be stable calculated. If these entries
                            involve a fraction of the data larger than
                            missing_model_cutoff, a warning is printed.
    """
    if hasattr(data, 'folded') and data.folded and not model.folded:
        model = model.fold()
    if hasattr(data, 'folded_ancestral') and data.folded_ancestral\
       and not model.folded_ancestral:
        model = model.fold_ancestral()
    if hasattr(data, 'folded_major') and data.folded_major\
       and not model.folded_major:
        model = model.fold_major()

    # Using numpy.ma.log here ensures that any negative or nan entries in model
    # yield masked entries in result. We can then check for correctness of
    # calculation by simply comparing masks.
    # Note: Using .data attributes directly saves a little computation time. We
    # use model and data as a whole at least once, to ensure masking is done
    # properly.
    result = -model.data + data.data*model.log() - gammaln(data + 1.)
    if numpy.all(result.mask == data.mask):
        return result

    not_data_mask = logical_not(data.mask)
    data_sum = data.sum()

    missing = logical_and(model < 0, not_data_mask)
    if numpy.any(missing)\
       and data[missing].sum()/data.sum() > missing_model_cutoff:
        logger.warning('Model is < 0 where data is not masked.')
        logger.warning('Number of affected entries is %i. Sum of data in those '
                'entries is %g:' % (missing.sum(), data[missing].sum()))

    # If the data is 0, it's okay for the model to be 0. In that case the ll
    # contribution is 0, which is fine.
    missing = logical_and(model == 0, logical_and(data > 0, not_data_mask))
    if numpy.any(missing)\
       and data[missing].sum()/data_sum > missing_model_cutoff:
        logger.warning('Model is 0 where data is neither masked nor 0.')
        logger.warning('Number of affected entries is %i. Sum of data in those '
                    'entries is %g:' % (missing.sum(), data[missing].sum()))

    missing = numpy.logical_and(model.mask, not_data_mask)
    if numpy.any(missing)\
       and data[missing].sum()/data_sum > missing_model_cutoff:
        print(data[missing].sum(), data_sum)
        logger.warning('Model is masked in some entries where data is not.')
        logger.warning('Number of affected entries is %i. Sum of data in those '
                    'entries is %g:' % (missing.sum(), data[missing].sum()))

    missing = numpy.logical_and(numpy.isnan(model), not_data_mask)
    if numpy.any(missing)\
       and data[missing].sum()/data_sum > missing_model_cutoff:
        logger.warning('Model is nan in some entries where data is not masked.')
        logger.warning('Number of affected entries is %i. Sum of data in those '
                    'entries is %g:' % (missing.sum(), data[missing].sum()))

    return result

minus_ll(model, data)

The negative of the log-likelihood of the data given the model sfs.

Source code in dadi/Inference.py
460
461
462
463
464
def minus_ll(model, data):
    """
    The negative of the log-likelihood of the data given the model sfs.
    """
    return -ll(model, data)

minus_ll_multinom(model, data)

The negative of the log-likelihood of the data given the model sfs.

Return a double that is -(log-likelihood)

Source code in dadi/Inference.py
577
578
579
580
581
582
583
def minus_ll_multinom(model, data):
    """
    The negative of the log-likelihood of the data given the model sfs.

    Return a double that is -(log-likelihood)
    """
    return -ll_multinom(model, data)

optimal_sfs_scaling(model, data)

Optimal multiplicative scaling factor between model and data.

This scaling is based on only those entries that are masked in neither model nor data.

Source code in dadi/Inference.py
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
def optimal_sfs_scaling(model, data):
    """
    Optimal multiplicative scaling factor between model and data.

    This scaling is based on only those entries that are masked in neither
    model nor data.
    """
    if hasattr(data, 'folded') and data.folded and not model.folded:
        model = model.fold()
    if hasattr(data, 'folded_ancestral') and data.folded_ancestral\
       and not model.folded_ancestral:
        model = model.fold_ancestral()
    if hasattr(data, 'folded_major') and data.folded_major\
       and not model.folded_major:
        model = model.fold_major()

    model, data = Numerics.intersect_masks(model, data)
    return data.sum()/model.sum()

optimally_scaled_sfs(model, data)

Optimially scale model sfs to data sfs.

Returns a new scaled model sfs.

Source code in dadi/Inference.py
660
661
662
663
664
665
666
def optimally_scaled_sfs(model, data):
    """
    Optimially scale model sfs to data sfs.

    Returns a new scaled model sfs.
    """
    return optimal_sfs_scaling(model,data) * model

optimize(p0, data, model_func, pts, lower_bound=None, upper_bound=None, verbose=0, flush_delay=0.5, epsilon=0.001, gtol=1e-05, multinom=True, maxiter=None, full_output=False, func_args=[], func_kwargs={}, fixed_params=None, ll_scale=1, output_file=None)

Optimize params to fit model to data using the BFGS method.

This optimization method works well when we start reasonably close to the optimum. It is best at burrowing down a single minimum.

Parameters:

Name Type Description Default
p0 list[float]

Initial parameters.

required
data Spectrum

Spectrum with data.

required
model_func func

Function to evaluate model spectrum. Should take arguments (params, (n1,n2...), pts)

required
lower_bound list[float]

Lower bound on parameter values. If not None, must be of same length as p0.

None
upper_bound list[float]

Upper bound on parameter values. If not None, must be of same length as p0.

None
verbose int

If > 0, print optimization status every steps.

0
output_file str

Stream verbose output into this filename. If None, stream to standard out.

None
flush_delay float

Standard output will be flushed once every minutes. This is useful to avoid overloading I/O on clusters.

0.5
epsilon float

Step-size to use for finite-difference derivatives.

0.001
gtol float

Convergence criterion for optimization. For more info, see help(scipy.optimize.fmin_bfgs)

1e-05
multinom bool

If True, do a multinomial fit where model is optimially scaled to data at each step. If False, assume theta is a parameter and do no scaling.

True
maxiter int

Maximum iterations to run for.

None
full_output bool

If True, return full outputs as in described in help(scipy.optimize.fmin_bfgs)

False
func_args list

Additional arguments to model_func. It is assumed that model_func's first argument is an array of parameters to optimize, that its second argument is an array of sample sizes for the sfs, and that its last argument is the list of grid points to use in evaluation.

[]
func_kwargs list

Additional keyword arguments to model_func.

{}
fixed_params list[float]

If not None, should be a list used to fix model parameters at particular values. For example, if the model parameters are (nu1,nu2,T,m), then fixed_params = [0.5,None,None,2] will hold nu1=0.5 and m=2. The optimizer will only change T and m. Note that the bounds lists must include all parameters. Optimization will fail if the fixed values lie outside their bounds. A full-length p0 should be passed in; values corresponding to fixed parameters are ignored. (See help(dadi.Inference.optimize_log for examples of func_args and fixed_params usage.)

None
ll_scale float

The bfgs algorithm may fail if your initial log-likelihood is too large. (This appears to be a flaw in the scipy implementation.) To overcome this, pass ll_scale > 1, which will simply reduce the magnitude of the log-likelihood. Once in a region of reasonable likelihood, you'll probably want to re-optimize with ll_scale=1.

1
Source code in dadi/Inference.py
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
def optimize(p0, data, model_func, pts, lower_bound=None, upper_bound=None,
             verbose=0, flush_delay=0.5, epsilon=1e-3, 
             gtol=1e-5, multinom=True, maxiter=None, full_output=False,
             func_args=[], func_kwargs={}, fixed_params=None, ll_scale=1,
             output_file=None):
    """
    Optimize params to fit model to data using the BFGS method.

    This optimization method works well when we start reasonably close to the
    optimum. It is best at burrowing down a single minimum.

    Args:
        p0 (list[float]): Initial parameters.
        data (Spectrum): Spectrum with data.
        model_func (func): Function to evaluate model spectrum. Should take arguments
                        (params, (n1,n2...), pts)
        lower_bound (list[float]): Lower bound on parameter values. If not None, must be of same
                    length as p0.
        upper_bound (list[float]): Upper bound on parameter values. If not None, must be of same
                    length as p0.
        verbose (int): If > 0, print optimization status every <verbose> steps.
        output_file (str): Stream verbose output into this filename. If None, stream to
                    standard out.
        flush_delay (float): Standard output will be flushed once every <flush_delay>
                    minutes. This is useful to avoid overloading I/O on clusters.
        epsilon (float): Step-size to use for finite-difference derivatives.
        gtol (float): Convergence criterion for optimization. For more info, 
            see help(scipy.optimize.fmin_bfgs)
        multinom (bool): If True, do a multinomial fit where model is optimially scaled to
                data at each step. If False, assume theta is a parameter and do
                no scaling.
        maxiter (int): Maximum iterations to run for.
        full_output (bool): If True, return full outputs as in described in 
                    help(scipy.optimize.fmin_bfgs)
        func_args (list): Additional arguments to model_func. It is assumed that 
                model_func's first argument is an array of parameters to
                optimize, that its second argument is an array of sample sizes
                for the sfs, and that its last argument is the list of grid
                points to use in evaluation.
        func_kwargs (list): Additional keyword arguments to model_func.
        fixed_params (list[float]): If not None, should be a list used to fix model parameters at
                    particular values. For example, if the model parameters
                    are (nu1,nu2,T,m), then fixed_params = [0.5,None,None,2]
                    will hold nu1=0.5 and m=2. The optimizer will only change 
                    T and m. Note that the bounds lists must include all
                    parameters. Optimization will fail if the fixed values
                    lie outside their bounds. A full-length p0 should be passed
                    in; values corresponding to fixed parameters are ignored.
                    (See help(dadi.Inference.optimize_log for examples of func_args and 
                    fixed_params usage.)
        ll_scale (float): The bfgs algorithm may fail if your initial log-likelihood is
                too large. (This appears to be a flaw in the scipy
                implementation.) To overcome this, pass ll_scale > 1, which will
                simply reduce the magnitude of the log-likelihood. Once in a
                region of reasonable likelihood, you'll probably want to
                re-optimize with ll_scale=1.
    """
    if output_file:
        output_stream = open(output_file, 'w')
    else:
        output_stream = sys.stdout

    args = (data, model_func, pts, lower_bound, upper_bound, verbose,
            multinom, flush_delay, func_args, func_kwargs, fixed_params, 
            ll_scale, output_stream)

    p0 = _project_params_down(p0, fixed_params)
    outputs = scipy.optimize.fmin_bfgs(_object_func, p0, 
                                       epsilon=epsilon,
                                       args = args, gtol=gtol, 
                                       full_output=True,
                                       disp=False,
                                       maxiter=maxiter)
    xopt, fopt, gopt, Bopt, func_calls, grad_calls, warnflag = outputs
    xopt = _project_params_up(xopt, fixed_params)

    if output_file:
        output_stream.close()

    if not full_output:
        return xopt
    else:
        return xopt, fopt, gopt, Bopt, func_calls, grad_calls, warnflag

optimize_cons(p0, data, model_func, pts, eq_constraint=None, ieq_constraint=None, lower_bound=None, upper_bound=None, verbose=0, flush_delay=0.5, epsilon=0.0001, gtol=1e-05, multinom=True, maxiter=None, full_output=False, func_args=[], func_kwargs={}, fixed_params=None, ll_scale=1, output_file=None)

Optimize params to fit model to data using constrainted optimization.

This method will ensure parameter constraints are satisfied. For example, you might constrain than one parameter is larger than other, or that the sum of several parameters is a particular value.

Parameters:

Name Type Description Default
p0 list[float]

Initial parameters.

required
data Spectrum

Spectrum with data.

required
model_func func

Function to evaluate model spectrum. Should take arguments (params, (n1,n2...), pts)

required
eq_constraint func

Function that returns a 1D array in which each element must equal to 0 in a successful result. For example, to constraint p[1] + p[2] = 1 and p[3] - p[2] = 3, def eq_constraint(p): return [p[1]+p[2]-1, p[3]-p[2]-3]

None
ieq_constraint func

Function that returns a 1D array in which each element must greater than or equal to 0 in a successful result.

None
lower_bound list[float]

Lower bound on parameter values. If not None, must be of same length as p0.

None
upper_bound list[float]

Upper bound on parameter values. If not None, must be of same length as p0.

None
verbose int

If > 0, print optimization status every steps.

0
output_file str

Stream verbose output into this filename. If None, stream to standard out.

None
flush_delay float

Standard output will be flushed once every minutes. This is useful to avoid overloading I/O on clusters.

0.5
epsilon int

Step-size to use for finite-difference derivatives.

0.0001
gtol float

Convergence criterion for optimization. For more info, see help(scipy.optimize.fmin_bfgs)

1e-05
multinom bool

If True, do a multinomial fit where model is optimially scaled to data at each step. If False, assume theta is a parameter and do no scaling.

True
maxiter int

Maximum iterations to run for.

None
full_output bool

If True, return full outputs as in described in help(scipy.optimize.fmin_slsqp)

False
func_args list

Additional arguments to model_func. It is assumed that model_func's first argument is an array of parameters to optimize, that its second argument is an array of sample sizes for the sfs, and that its last argument is the list of grid points to use in evaluation. Using func_args. For example, you could define your model function as def func((p1,p2), ns, f1, f2, pts): .... If you wanted to fix f1=0.1 and f2=0.2 in the optimization, you would pass func_args = [0.1,0.2] (and ignore the fixed_params argument).

[]
func_kwargs list

Additional keyword arguments to model_func.

{}
fixed_params list[float]

If not None, should be a list used to fix model parameters at particular values. For example, if the model parameters are (nu1,nu2,T,m), then fixed_params = [0.5,None,None,2] will hold nu1=0.5 and m=2. The optimizer will only change T and m. Note that the bounds lists must include all parameters. Optimization will fail if the fixed values lie outside their bounds. A full-length p0 should be passed in; values corresponding to fixed parameters are ignored. For example, suppose your model function is def func((p1,f1,p2,f2), ns, pts): .... If you wanted to fix f1=0.1 and f2=0.2 in the optimization, you would pass fixed_params = [None,0.1,None,0.2] (and ignore the func_args argument).

None
ll_scale float

The bfgs algorithm may fail if your initial log-likelihood is too large. (This appears to be a flaw in the scipy implementation.) To overcome this, pass ll_scale > 1, which will simply reduce the magnitude of the log-likelihood. Once in a region of reasonable likelihood, you'll probably want to re-optimize with ll_scale=1.

1
Source code in dadi/Inference.py
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
def optimize_cons(p0, data, model_func, pts,
                  eq_constraint=None, ieq_constraint=None,
                  lower_bound=None, upper_bound=None, 
                  verbose=0, flush_delay=0.5, epsilon=1e-4,
                  gtol=1e-5, multinom=True, maxiter=None,
                  full_output=False, func_args=[], func_kwargs={},
                  fixed_params=None, ll_scale=1, output_file=None):
    """
    Optimize params to fit model to data using constrainted optimization.

    This method will ensure parameter constraints are satisfied.
    For example, you might constrain than one parameter is larger than other,
     or that the sum of several parameters is a particular value.

    Args:
        p0 (list[float]): Initial parameters.
        data (Spectrum): Spectrum with data.
        model_func (func): Function to evaluate model spectrum. Should take arguments
                        (params, (n1,n2...), pts)
        eq_constraint (func): Function that returns a 1D array in which each element must
                    equal to 0 in a successful result.
                    For example, to constraint p[1] + p[2] = 1 and p[3] - p[2] = 3,
                    def eq_constraint(p): return [p[1]+p[2]-1, p[3]-p[2]-3]
        ieq_constraint (func): Function that returns a 1D array in which each element must
                        greater than or equal to 0 in a successful result.
        lower_bound (list[float]): Lower bound on parameter values. If not None, must be of same
                    length as p0.
        upper_bound (list[float]): Upper bound on parameter values. If not None, must be of same
                    length as p0.
        verbose (int): If > 0, print optimization status every <verbose> steps.
        output_file (str): Stream verbose output into this filename. If None, stream to
                    standard out.
        flush_delay (float): Standard output will be flushed once every <flush_delay>
                    minutes. This is useful to avoid overloading I/O on clusters.
        epsilon (int): Step-size to use for finite-difference derivatives.
        gtol (float): Convergence criterion for optimization. For more info, 
            see help(scipy.optimize.fmin_bfgs)
        multinom (bool): If True, do a multinomial fit where model is optimially scaled to
                data at each step. If False, assume theta is a parameter and do
                no scaling.
        maxiter (int): Maximum iterations to run for.
        full_output (bool): If True, return full outputs as in described in 
                    help(scipy.optimize.fmin_slsqp)
        func_args (list): Additional arguments to model_func. It is assumed that 
                model_func's first argument is an array of parameters to
                optimize, that its second argument is an array of sample sizes
                for the sfs, and that its last argument is the list of grid
                points to use in evaluation.
                Using func_args.
                For example, you could define your model function as
                def func((p1,p2), ns, f1, f2, pts):
                    ....
                If you wanted to fix f1=0.1 and f2=0.2 in the optimization, you
                would pass func_args = [0.1,0.2] (and ignore the fixed_params 
                argument).
        func_kwargs (list): Additional keyword arguments to model_func.
        fixed_params (list[float]): If not None, should be a list used to fix model parameters at
                    particular values. For example, if the model parameters
                    are (nu1,nu2,T,m), then fixed_params = [0.5,None,None,2]
                    will hold nu1=0.5 and m=2. The optimizer will only change 
                    T and m. Note that the bounds lists must include all
                    parameters. Optimization will fail if the fixed values
                    lie outside their bounds. A full-length p0 should be passed
                    in; values corresponding to fixed parameters are ignored.
                    For example, suppose your model function is 
                    def func((p1,f1,p2,f2), ns, pts):
                        ....
                    If you wanted to fix f1=0.1 and f2=0.2 in the optimization, 
                    you would pass fixed_params = [None,0.1,None,0.2] (and ignore
                    the func_args argument).
        ll_scale (float): The bfgs algorithm may fail if your initial log-likelihood is
                too large. (This appears to be a flaw in the scipy
                implementation.) To overcome this, pass ll_scale > 1, which will
                simply reduce the magnitude of the log-likelihood. Once in a
                region of reasonable likelihood, you'll probably want to
                re-optimize with ll_scale=1.
    """
    if output_file:
        output_stream = open(output_file, 'w')
    else:
        output_stream = sys.stdout

    args = (data, model_func, pts, None, None, verbose, 
            multinom, flush_delay, func_args, func_kwargs, fixed_params, 
            ll_scale, output_stream)

    if lower_bound is None:
        lower_bound = [None] * len(p0)
    if upper_bound is None:
        upper_bound = [None] * len(p0)
    lower_bound = _project_params_down(lower_bound, fixed_params)
    upper_bound = _project_params_down(upper_bound, fixed_params)
    if (lower_bound is not None) and (upper_bound is not None):
        bnds = tuple(zip(lower_bound,upper_bound))

    p0 = _project_params_down(p0, fixed_params)

    outputs = scipy.optimize.fmin_slsqp(_object_func, 
        p0, bounds = bnds, args = args,
        f_eqcons = eq_constraint, f_ieqcons = ieq_constraint,
        epsilon = epsilon,
        iter = maxiter, full_output = True,
        disp = False)
    xopt, fopt, func_calls, grad_calls, warnflag = outputs

    xopt = _project_params_up(xopt, fixed_params)

    if output_file:
        output_stream.close()

    if not full_output:
        return xopt
    else:
        return xopt, fopt, func_calls, grad_calls, warnflag

optimize_grid(data, model_func, pts, grid, verbose=0, flush_delay=0.5, multinom=True, full_output=False, func_args=[], func_kwargs={}, fixed_params=None, output_file=None)

Optimize params to fit model to data using brute force search over a grid.

Search grids are specified using a dadi.Inference.index_exp object (which is an alias for numpy.index_exp). The grid is specified by passing a range of values for each parameter. For example, index_exp[0:1.1:0.3, 0.7:0.9:11j] will search over parameter 1 with values 0,0.3,0.6,0.9 and over parameter 2 with 11 points between 0.7 and 0.9 (inclusive). (Notice the 11j in the second parameter range specification.) Note that the grid list should include only parameters that are optimized over, not fixed parameter values.

Parameters:

Name Type Description Default
data Spectrum

Spectrum with data.

required
model_func func

Function to evaluate model spectrum. Should take arguments (params, (n1,n2...), pts)

required
pts list[int]

Grid points list for evaluating likelihoods

required
grid list[int]

Grid of parameter values over which to evaluate likelihood. See below for specification instructions.

required
verbose float

If > 0, print optimization status every steps.

0
output_file str

Stream verbose output into this filename. If None, stream to standard out.

None
flush_delay float

Standard output will be flushed once every minutes. This is useful to avoid overloading I/O on clusters.

0.5
multinom bool

If True, do a multinomial fit where model is optimially scaled to data at each step. If False, assume theta is a parameter and do no scaling.

True
full_output bool

If True, return popt, llopt, grid, llout, thetas. Here popt is the best parameter set found and llopt is the corresponding (composite) log-likelihood. grid is the array of parameter values tried, llout is the corresponding log-likelihoods, and thetas is the corresponding thetas. Note that the grid includes only the parameters optimized over, and that the order of indices is such that grid[:,0,2] would be a set of parameters if two parameters were optimized over. (Note the : in the first index.)

False
func_args list

Additional arguments to model_func. It is assumed that model_func's first argument is an array of parameters to optimize, that its second argument is an array of sample sizes for the sfs, and that its last argument is the list of grid points to use in evaluation.

[]
func_kwargs list

Additional keyword arguments to model_func.

{}
fixed_params list[float]

If not None, should be a list used to fix model parameters at particular values. For example, if the model parameters are (nu1,nu2,T,m), then fixed_params = [0.5,None,None,2] will hold nu1=0.5 and m=2. The optimizer will only change T and m. Note that the bounds lists must include all parameters. Optimization will fail if the fixed values lie outside their bounds. A full-length p0 should be passed in; values corresponding to fixed parameters are ignored. (See help(dadi.Inference.optimize_log for examples of func_args and fixed_params usage.)

None
Source code in dadi/Inference.py
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
def optimize_grid(data, model_func, pts, grid,
                  verbose=0, flush_delay=0.5,
                  multinom=True, full_output=False,
                  func_args=[], func_kwargs={}, fixed_params=None,
                  output_file=None):
    """
    Optimize params to fit model to data using brute force search over a grid.

    Search grids are specified using a dadi.Inference.index_exp object (which
    is an alias for numpy.index_exp). The grid is specified by passing a range
    of values for each parameter. For example, index_exp[0:1.1:0.3,
    0.7:0.9:11j] will search over parameter 1 with values 0,0.3,0.6,0.9 and
    over parameter 2 with 11 points between 0.7 and 0.9 (inclusive). (Notice
    the 11j in the second parameter range specification.) Note that the grid
    list should include only parameters that are optimized over, not fixed
    parameter values.

    Args:
        data (Spectrum): Spectrum with data.
        model_func (func): Function to evaluate model spectrum. Should take arguments
                    (params, (n1,n2...), pts)
        pts (list[int]): Grid points list for evaluating likelihoods
        grid (list[int]): Grid of parameter values over which to evaluate likelihood. See
            below for specification instructions.
        verbose (float): If > 0, print optimization status every <verbose> steps.
        output_file (str): Stream verbose output into this filename. If None, stream to
                    standard out.
        flush_delay (float): Standard output will be flushed once every <flush_delay>
                    minutes. This is useful to avoid overloading I/O on clusters.
        multinom (bool): If True, do a multinomial fit where model is optimially scaled to
                data at each step. If False, assume theta is a parameter and do
                no scaling.
        full_output (bool): If True, return popt, llopt, grid, llout, thetas. Here popt is
                    the best parameter set found and llopt is the corresponding
                    (composite) log-likelihood. grid is the array of parameter
                    values tried, llout is the corresponding log-likelihoods, and
                    thetas is the corresponding thetas. Note that the grid includes
                    only the parameters optimized over, and that the order of
                    indices is such that grid[:,0,2] would be a set of parameters
                    if two parameters were optimized over. (Note the : in the
                    first index.)
        func_args (list): Additional arguments to model_func. It is assumed that 
                model_func's first argument is an array of parameters to
                optimize, that its second argument is an array of sample sizes
                for the sfs, and that its last argument is the list of grid
                points to use in evaluation.
        func_kwargs (list): Additional keyword arguments to model_func.
        fixed_params (list[float]): If not None, should be a list used to fix model parameters at
                    particular values. For example, if the model parameters
                    are (nu1,nu2,T,m), then fixed_params = [0.5,None,None,2]
                    will hold nu1=0.5 and m=2. The optimizer will only change 
                    T and m. Note that the bounds lists must include all
                    parameters. Optimization will fail if the fixed values
                    lie outside their bounds. A full-length p0 should be passed
                    in; values corresponding to fixed parameters are ignored.
                    (See help(dadi.Inference.optimize_log for examples of func_args and 
                    fixed_params usage.)
    """
    if output_file:
        output_stream = open(output_file, 'w')
    else:
        output_stream = sys.stdout

    args = (data, model_func, pts, None, None, verbose,
            multinom, flush_delay, func_args, func_kwargs, fixed_params, 1.0,
            output_stream, full_output)

    if full_output:
        global _theta_store
        _theta_store = {}

    outputs = scipy.optimize.brute(_object_func, ranges=grid,
                                   args=args, full_output=full_output,
                                   finish=False)
    if full_output:
        xopt, fopt, grid, fout = outputs
        # Thetas are stored as a dictionary, because we can't guarantee
        # iteration order in brute(). So we have to iterate back over them
        # to produce the proper order to return.
        thetas = numpy.zeros(fout.shape)
        for indices, temp in numpy.ndenumerate(fout):
            # This is awkward, because we need to access grid[:,indices]
            grid_indices = tuple([slice(None,None,None)] + list(indices))
            thetas[indices] = _theta_store[tuple(grid[grid_indices])]
    else:
        xopt = outputs
    xopt = _project_params_up(xopt, fixed_params)

    if output_file:
        output_stream.close()

    if not full_output:
        return xopt
    else:
        return xopt, fopt, grid, fout, thetas

optimize_lbfgsb(p0, data, model_func, pts, lower_bound=None, upper_bound=None, verbose=0, flush_delay=0.5, epsilon=0.001, pgtol=1e-05, multinom=True, maxiter=100000.0, full_output=False, func_args=[], func_kwargs={}, fixed_params=None, ll_scale=1, output_file=None)

Optimize log(params) to fit model to data using the L-BFGS-B method.

This optimization method works well when we start reasonably close to the optimum. It is best at burrowing down a single minimum. This method is better than optimize_log if the optimum lies at one or more of the parameter bounds. However, if your optimum is not on the bounds, this method may be much slower.

Parameters:

Name Type Description Default
p0 list[float]

Initial parameters.

required
data Spectrum

Spectrum with data.

required
model_func float

Function to evaluate model spectrum. Should take arguments (params, (n1,n2...), pts)

required
lower_bound list[float]

Lower bound on parameter values. If not None, must be of same length as p0. A parameter can be declared unbound by assigning a bound of None.

None
upper_bound list[float]

Upper bound on parameter values. If not None, must be of same length as p0. A parameter can be declared unbound by assigning a bound of None.

None
verbose int

If > 0, print optimization status every steps.

0
output_file str

Stream verbose output into this filename. If None, stream to standard out.

None
flush_delay float

Standard output will be flushed once every minutes. This is useful to avoid overloading I/O on clusters.

0.5
epsilon float

Step-size to use for finite-difference derivatives.

0.001
pgtol float

Convergence criterion for optimization. For more info, see help(scipy.optimize.fmin_l_bfgs_b)

1e-05
multinom bool

If True, do a multinomial fit where model is optimially scaled to data at each step. If False, assume theta is a parameter and do no scaling.

True
maxiter int

Maximum algorithm iterations evaluations to run.

100000.0
full_output bool

If True, return full outputs as in described in help(scipy.optimize.fmin_bfgs)

False
func_args list

Additional arguments to model_func. It is assumed that model_func's first argument is an array of parameters to optimize, that its second argument is an array of sample sizes for the sfs, and that its last argument is the list of grid points to use in evaluation.

[]
func_kwargs list

Additional keyword arguments to model_func.

{}
fixed_params list[float]

If not None, should be a list used to fix model parameters at particular values. For example, if the model parameters are (nu1,nu2,T,m), then fixed_params = [0.5,None,None,2] will hold nu1=0.5 and m=2. The optimizer will only change T and m. Note that the bounds lists must include all parameters. Optimization will fail if the fixed values lie outside their bounds. A full-length p0 should be passed in; values corresponding to fixed parameters are ignored. (See help(dadi.Inference.optimize_log for examples of func_args and fixed_params usage.)

None
ll_scale float

The bfgs algorithm may fail if your initial log-likelihood is too large. (This appears to be a flaw in the scipy implementation.) To overcome this, pass ll_scale > 1, which will simply reduce the magnitude of the log-likelihood. Once in a region of reasonable likelihood, you'll probably want to re-optimize with ll_scale=1.

1
Citation

The L-BFGS-B method was developed by Ciyou Zhu, Richard Byrd, and Jorge Nocedal. The algorithm is described in:

  • R. H. Byrd, P. Lu and J. Nocedal. A Limited Memory Algorithm for Bound Constrained Optimization, (1995), SIAM Journal on Scientific and Statistical Computing , 16, 5, pp. 1190-1208.

  • C. Zhu, R. H. Byrd and J. Nocedal. L-BFGS-B: Algorithm 778: L-BFGS-B, FORTRAN routines for large scale bound constrained optimization (1997), ACM Transactions on Mathematical Software, Vol 23, Num. 4, pp. 550-560.

Source code in dadi/Inference.py
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
def optimize_lbfgsb(p0, data, model_func, pts, 
                    lower_bound=None, upper_bound=None,
                    verbose=0, flush_delay=0.5, epsilon=1e-3, 
                    pgtol=1e-5, multinom=True, maxiter=1e5, full_output=False,
                    func_args=[], func_kwargs={}, fixed_params=None, 
                    ll_scale=1, output_file=None):
    """
    Optimize log(params) to fit model to data using the L-BFGS-B method.

    This optimization method works well when we start reasonably close to the
    optimum. It is best at burrowing down a single minimum. This method is
    better than optimize_log if the optimum lies at one or more of the
    parameter bounds. However, if your optimum is not on the bounds, this
    method may be much slower.

    Args:
        p0 (list[float]): Initial parameters.
        data (Spectrum): Spectrum with data.
        model_func (float): Function to evaluate model spectrum. Should take arguments
                        (params, (n1,n2...), pts)
        lower_bound (list[float]): Lower bound on parameter values. If not None, must be of same
                    length as p0. A parameter can be declared unbound by assigning
                    a bound of None.
        upper_bound (list[float]): Upper bound on parameter values. If not None, must be of same
                    length as p0. A parameter can be declared unbound by assigning
                    a bound of None.
        verbose (int): If > 0, print optimization status every <verbose> steps.
        output_file (str): Stream verbose output into this filename. If None, stream to
                    standard out.
        flush_delay (float): Standard output will be flushed once every <flush_delay>
                    minutes. This is useful to avoid overloading I/O on clusters.
        epsilon (float): Step-size to use for finite-difference derivatives.
        pgtol (float): Convergence criterion for optimization. For more info, 
            see help(scipy.optimize.fmin_l_bfgs_b)
        multinom (bool): If True, do a multinomial fit where model is optimially scaled to
                data at each step. If False, assume theta is a parameter and do
                no scaling.
        maxiter (int): Maximum algorithm iterations evaluations to run.
        full_output (bool): If True, return full outputs as in described in 
                    help(scipy.optimize.fmin_bfgs)
        func_args (list): Additional arguments to model_func. It is assumed that 
                model_func's first argument is an array of parameters to
                optimize, that its second argument is an array of sample sizes
                for the sfs, and that its last argument is the list of grid
                points to use in evaluation.
        func_kwargs (list): Additional keyword arguments to model_func.
        fixed_params (list[float]): If not None, should be a list used to fix model parameters at
                    particular values. For example, if the model parameters
                    are (nu1,nu2,T,m), then fixed_params = [0.5,None,None,2]
                    will hold nu1=0.5 and m=2. The optimizer will only change 
                    T and m. Note that the bounds lists must include all
                    parameters. Optimization will fail if the fixed values
                    lie outside their bounds. A full-length p0 should be passed
                    in; values corresponding to fixed parameters are ignored.
                    (See help(dadi.Inference.optimize_log for examples of func_args and 
                    fixed_params usage.)
        ll_scale (float): The bfgs algorithm may fail if your initial log-likelihood is
                too large. (This appears to be a flaw in the scipy
                implementation.) To overcome this, pass ll_scale > 1, which will
                simply reduce the magnitude of the log-likelihood. Once in a
                region of reasonable likelihood, you'll probably want to
                re-optimize with ll_scale=1.

    Citation:
        The L-BFGS-B method was developed by Ciyou Zhu, Richard Byrd, and Jorge
        Nocedal. The algorithm is described in:

        * R. H. Byrd, P. Lu and J. Nocedal. A Limited Memory Algorithm for Bound
            Constrained Optimization, (1995), SIAM Journal on Scientific and
            Statistical Computing , 16, 5, pp. 1190-1208.

        * C. Zhu, R. H. Byrd and J. Nocedal. L-BFGS-B: Algorithm 778: L-BFGS-B,
            FORTRAN routines for large scale bound constrained optimization (1997),
            ACM Transactions on Mathematical Software, Vol 23, Num. 4, pp. 550-560.
    """
    if output_file:
        output_stream = open(output_file, 'w')
    else:
        output_stream = sys.stdout

    args = (data, model_func, pts, None, None, verbose,
            multinom, flush_delay, func_args, func_kwargs, fixed_params, 
            ll_scale, output_stream)

    # Make bounds list. For this method it needs to be in terms of log params.
    if lower_bound is None:
        lower_bound = [None] * len(p0)
    lower_bound = _project_params_down(lower_bound, fixed_params)
    if upper_bound is None:
        upper_bound = [None] * len(p0)
    upper_bound = _project_params_down(upper_bound, fixed_params)
    bounds = list(zip(lower_bound,upper_bound))

    p0 = _project_params_down(p0, fixed_params)

    outputs = scipy.optimize.fmin_l_bfgs_b(_object_func, 
                                           numpy.log(p0), bounds=bounds,
                                           epsilon=epsilon, args=args,
                                           iprint=-1, pgtol=pgtol,
                                           maxfun=maxiter, approx_grad=True)
    xopt, fopt, info_dict = outputs

    xopt = _project_params_up(xopt, fixed_params)

    if output_file:
        output_stream.close()

    if not full_output:
        return xopt
    else:
        return xopt, fopt, info_dict

optimize_log(p0, data, model_func, pts, lower_bound=None, upper_bound=None, verbose=0, flush_delay=0.5, epsilon=0.001, gtol=1e-05, multinom=True, maxiter=None, full_output=False, func_args=[], func_kwargs={}, fixed_params=None, ll_scale=1, output_file=None)

Optimize log(params) to fit model to data using the BFGS method.

This optimization method works well when we start reasonably close to the optimum. It is best at burrowing down a single minimum.

Because this works in log(params), it cannot explore values of params < 0. It should also perform better when parameters range over scales.

Parameters:

Name Type Description Default
p0 list[float]

Initial parameters.

required
data Spectrum

Spectrum with data.

required
model_func func

Function to evaluate model spectrum. Should take arguments (params, (n1,n2...), pts)

required
lower_bound list[float]

Lower bound on parameter values. If not None, must be of same length as p0.

None
upper_bound list[float]

Upper bound on parameter values. If not None, must be of same length as p0.

None
verbose int

If > 0, print optimization status every steps.

0
output_file str

Stream verbose output into this filename. If None, stream to standard out.

None
flush_delay float

Standard output will be flushed once every minutes. This is useful to avoid overloading I/O on clusters.

0.5
epsilon float

Step-size to use for finite-difference derivatives.

0.001
gtol float

Convergence criterion for optimization. For more info, see help(scipy.optimize.fmin_bfgs)

1e-05
multinom bool

If True, do a multinomial fit where model is optimially scaled to data at each step. If False, assume theta is a parameter and do no scaling.

True
maxiter inf

Maximum iterations to run for.

None
full_output bool

If True, return full outputs as in described in help(scipy.optimize.fmin_bfgs)

False
func_args list

Additional arguments to model_func. It is assumed that model_func's first argument is an array of parameters to optimize, that its second argument is an array of sample sizes for the sfs, and that its last argument is the list of grid points to use in evaluation. Using func_args. For example, you could define your model function as def func((p1,p2), ns, f1, f2, pts): .... If you wanted to fix f1=0.1 and f2=0.2 in the optimization, you would pass func_args = [0.1,0.2] (and ignore the fixed_params argument).

[]
func_kwargs list

Additional keyword arguments to model_func.

{}
fixed_params list[float]

If not None, should be a list used to fix model parameters at particular values. For example, if the model parameters are (nu1,nu2,T,m), then fixed_params = [0.5,None,None,2] will hold nu1=0.5 and m=2. The optimizer will only change T and m. Note that the bounds lists must include all parameters. Optimization will fail if the fixed values lie outside their bounds. A full-length p0 should be passed in; values corresponding to fixed parameters are ignored. For example, suppose your model function is def func((p1,f1,p2,f2), ns, pts): .... If you wanted to fix f1=0.1 and f2=0.2 in the optimization, you would pass fixed_params = [None,0.1,None,0.2] (and ignore the func_args argument).

None
ll_scale float

The bfgs algorithm may fail if your initial log-likelihood is too large. (This appears to be a flaw in the scipy implementation.) To overcome this, pass ll_scale > 1, which will simply reduce the magnitude of the log-likelihood. Once in a region of reasonable likelihood, you'll probably want to re-optimize with ll_scale=1.

1
Source code in dadi/Inference.py
 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
def optimize_log(p0, data, model_func, pts, lower_bound=None, upper_bound=None,
                 verbose=0, flush_delay=0.5, epsilon=1e-3, 
                 gtol=1e-5, multinom=True, maxiter=None, full_output=False,
                 func_args=[], func_kwargs={}, fixed_params=None, ll_scale=1,
                 output_file=None):
    """
    Optimize log(params) to fit model to data using the BFGS method.

    This optimization method works well when we start reasonably close to the
    optimum. It is best at burrowing down a single minimum.

    Because this works in log(params), it cannot explore values of params < 0.
    It should also perform better when parameters range over scales.

    Args:
        p0 (list[float]): Initial parameters.
        data (Spectrum): Spectrum with data.
        model_func (func): Function to evaluate model spectrum. Should take arguments
                        (params, (n1,n2...), pts)
        lower_bound (list[float]): Lower bound on parameter values. If not None, must be of same
                    length as p0.
        upper_bound (list[float]): Upper bound on parameter values. If not None, must be of same
                    length as p0.
        verbose (int): If > 0, print optimization status every <verbose> steps.
        output_file (str): Stream verbose output into this filename. If None, stream to
                    standard out.
        flush_delay (float): Standard output will be flushed once every <flush_delay>
                    minutes. This is useful to avoid overloading I/O on clusters.
        epsilon (float): Step-size to use for finite-difference derivatives.
        gtol (float): Convergence criterion for optimization. For more info, 
            see help(scipy.optimize.fmin_bfgs)
        multinom (bool): If True, do a multinomial fit where model is optimially scaled to
                data at each step. If False, assume theta is a parameter and do
                no scaling.
        maxiter (inf): Maximum iterations to run for.
        full_output (bool): If True, return full outputs as in described in 
                    help(scipy.optimize.fmin_bfgs)
        func_args (list): Additional arguments to model_func. It is assumed that 
                model_func's first argument is an array of parameters to
                optimize, that its second argument is an array of sample sizes
                for the sfs, and that its last argument is the list of grid
                points to use in evaluation.
                Using func_args.
                For example, you could define your model function as
                def func((p1,p2), ns, f1, f2, pts):
                    ....
                If you wanted to fix f1=0.1 and f2=0.2 in the optimization, you
                would pass func_args = [0.1,0.2] (and ignore the fixed_params 
                argument).
        func_kwargs (list): Additional keyword arguments to model_func.
        fixed_params (list[float]): If not None, should be a list used to fix model parameters at
                    particular values. For example, if the model parameters
                    are (nu1,nu2,T,m), then fixed_params = [0.5,None,None,2]
                    will hold nu1=0.5 and m=2. The optimizer will only change 
                    T and m. Note that the bounds lists must include all
                    parameters. Optimization will fail if the fixed values
                    lie outside their bounds. A full-length p0 should be passed
                    in; values corresponding to fixed parameters are ignored.
                    For example, suppose your model function is 
                    def func((p1,f1,p2,f2), ns, pts):
                        ....
                    If you wanted to fix f1=0.1 and f2=0.2 in the optimization, 
                    you would pass fixed_params = [None,0.1,None,0.2] (and ignore
                    the func_args argument).
        ll_scale (float): The bfgs algorithm may fail if your initial log-likelihood is
                too large. (This appears to be a flaw in the scipy
                implementation.) To overcome this, pass ll_scale > 1, which will
                simply reduce the magnitude of the log-likelihood. Once in a
                region of reasonable likelihood, you'll probably want to
                re-optimize with ll_scale=1.
    """
    if output_file:
        output_stream = open(output_file, 'w')
    else:
        output_stream = sys.stdout

    args = (data, model_func, pts, lower_bound, upper_bound, verbose,
            multinom, flush_delay, func_args, func_kwargs, fixed_params, 
            ll_scale, output_stream)

    p0 = _project_params_down(p0, fixed_params)
    outputs = scipy.optimize.fmin_bfgs(_object_func_log, 
                                       numpy.log(p0), epsilon=epsilon,
                                       args = args, gtol=gtol, 
                                       full_output=True,
                                       disp=False,
                                       maxiter=maxiter)
    xopt, fopt, gopt, Bopt, func_calls, grad_calls, warnflag = outputs
    xopt = _project_params_up(numpy.exp(xopt), fixed_params)

    if output_file:
        output_stream.close()

    if not full_output:
        return xopt
    else:
        return xopt, fopt, gopt, Bopt, func_calls, grad_calls, warnflag

optimize_log_fmin(p0, data, model_func, pts, lower_bound=None, upper_bound=None, verbose=0, flush_delay=0.5, multinom=True, maxiter=None, full_output=False, func_args=[], func_kwargs={}, fixed_params=None, output_file=None)

Optimize log(params) to fit model to data using Nelder-Mead.

This optimization method may work better than BFGS when far from a minimum. It is much slower, but more robust, because it doesn't use gradient information.

Because this works in log(params), it cannot explore values of params < 0. It should also perform better when parameters range over large scales.

Parameters:

Name Type Description Default
p0 list[float]

Initial parameters.

required
data Spectrum

Spectrum with data.

required
model_func func

Function to evaluate model spectrum. Should take arguments (params, (n1,n2...), pts)

required
lower_bound list[float]

Lower bound on parameter values. If not None, must be of same length as p0. A parameter can be declared unbound by assigning a bound of None.

None
upper_bound list[float]

Upper bound on parameter values. If not None, must be of same length as p0. A parameter can be declared unbound by assigning a bound of None.

None
verbose int

If True, print optimization status every steps.

0
output_file str

Stream verbose output into this filename. If None, stream to standard out.

None
flush_delay float

Standard output will be flushed once every minutes. This is useful to avoid overloading I/O on clusters.

0.5
multinom bool

If True, do a multinomial fit where model is optimially scaled to data at each step. If False, assume theta is a parameter and do no scaling.

True
maxiter int

Maximum iterations to run for.

None
full_output bool

If True, return full outputs as in described in help(scipy.optimize.fmin_bfgs)

False
func_args list

Additional arguments to model_func. It is assumed that model_func's first argument is an array of parameters to optimize, that its second argument is an array of sample sizes for the sfs, and that its last argument is the list of grid points to use in evaluation.

[]
func_kwargs list

Additional keyword arguments to model_func.

{}
fixed_params list[float]

If not None, should be a list used to fix model parameters at particular values. For example, if the model parameters are (nu1,nu2,T,m), then fixed_params = [0.5,None,None,2] will hold nu1=0.5 and m=2. The optimizer will only change T and m. Note that the bounds lists must include all parameters. Optimization will fail if the fixed values lie outside their bounds. A full-length p0 should be passed in; values corresponding to fixed parameters are ignored. (See help(dadi.Inference.optimize_log for examples of func_args and fixed_params usage.)

None
Source code in dadi/Inference.py
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
def optimize_log_fmin(p0, data, model_func, pts, 
                      lower_bound=None, upper_bound=None,
                      verbose=0, flush_delay=0.5, 
                      multinom=True, maxiter=None, 
                      full_output=False, func_args=[], 
                      func_kwargs={},
                      fixed_params=None, output_file=None):
    """
    Optimize log(params) to fit model to data using Nelder-Mead. 

    This optimization method may work better than BFGS when far from a
    minimum. It is much slower, but more robust, because it doesn't use
    gradient information.

    Because this works in log(params), it cannot explore values of params < 0.
    It should also perform better when parameters range over large scales.

    Args:
        p0 (list[float]): Initial parameters.
        data (Spectrum): Spectrum with data.
        model_func (func): Function to evaluate model spectrum. Should take arguments
                        (params, (n1,n2...), pts)
        lower_bound (list[float]): Lower bound on parameter values. If not None, must be of same
                    length as p0. A parameter can be declared unbound by assigning
                    a bound of None.
        upper_bound (list[float]): Upper bound on parameter values. If not None, must be of same
                    length as p0. A parameter can be declared unbound by assigning
                    a bound of None.
        verbose (int): If True, print optimization status every <verbose> steps.
        output_file (str): Stream verbose output into this filename. If None, stream to
                    standard out.
        flush_delay (float): Standard output will be flushed once every <flush_delay>
                    minutes. This is useful to avoid overloading I/O on clusters.
        multinom (bool): If True, do a multinomial fit where model is optimially scaled to
                data at each step. If False, assume theta is a parameter and do
                no scaling.
        maxiter (int): Maximum iterations to run for.
        full_output (bool): If True, return full outputs as in described in 
                    help(scipy.optimize.fmin_bfgs)
        func_args (list): Additional arguments to model_func. It is assumed that 
                model_func's first argument is an array of parameters to
                optimize, that its second argument is an array of sample sizes
                for the sfs, and that its last argument is the list of grid
                points to use in evaluation.
        func_kwargs (list): Additional keyword arguments to model_func.
        fixed_params (list[float]): If not None, should be a list used to fix model parameters at
                    particular values. For example, if the model parameters
                    are (nu1,nu2,T,m), then fixed_params = [0.5,None,None,2]
                    will hold nu1=0.5 and m=2. The optimizer will only change 
                    T and m. Note that the bounds lists must include all
                    parameters. Optimization will fail if the fixed values
                    lie outside their bounds. A full-length p0 should be passed
                    in; values corresponding to fixed parameters are ignored.
                    (See help(dadi.Inference.optimize_log for examples of func_args and
                    fixed_params usage.)
    """
    if output_file:
        output_stream = open(output_file, 'w')
    else:
        output_stream = sys.stdout

    args = (data, model_func, pts, lower_bound, upper_bound, verbose,
            multinom, flush_delay, func_args, func_kwargs, fixed_params, 1.0,
            output_stream)

    p0 = _project_params_down(p0, fixed_params)
    outputs = scipy.optimize.fmin(_object_func_log, numpy.log(p0), args = args,
                                  disp=False, maxiter=maxiter, full_output=True)
    xopt, fopt, iter, funcalls, warnflag = outputs
    xopt = _project_params_up(numpy.exp(xopt), fixed_params)

    if output_file:
        output_stream.close()

    if not full_output:
        return xopt
    else:
        return xopt, fopt, iter, funcalls, warnflag

optimize_log_lbfgsb(p0, data, model_func, pts, lower_bound=None, upper_bound=None, verbose=0, flush_delay=0.5, epsilon=0.001, pgtol=1e-05, multinom=True, maxiter=100000.0, full_output=False, func_args=[], func_kwargs={}, fixed_params=None, ll_scale=1, output_file=None)

Optimize log(params) to fit model to data using the L-BFGS-B method.

This optimization method works well when we start reasonably close to the optimum. It is best at burrowing down a single minimum. This method is better than optimize_log if the optimum lies at one or more of the parameter bounds. However, if your optimum is not on the bounds, this method may be much slower.

Because this works in log(params), it cannot explore values of params < 0. It should also perform better when parameters range over scales.

Parameters:

Name Type Description Default
p0 list[float]

Initial parameters.

required
data Spectrum

Spectrum with data.

required
model_func func

Function to evaluate model spectrum. Should take arguments (params, (n1,n2...), pts)

required
lower_bound list[float]

Lower bound on parameter values. If not None, must be of same length as p0. A parameter can be declared unbound by assigning a bound of None.

None
upper_bound list[float]

Upper bound on parameter values. If not None, must be of same length as p0. A parameter can be declared unbound by assigning a bound of None.

None
verbose int

If > 0, print optimization status every steps.

0
output_file str

Stream verbose output into this filename. If None, stream to standard out.

None
flush_delay float

Standard output will be flushed once every minutes. This is useful to avoid overloading I/O on clusters.

0.5
epsilon float

Step-size to use for finite-difference derivatives.

0.001
pgtol float

Convergence criterion for optimization. For more info, see help(scipy.optimize.fmin_l_bfgs_b)

1e-05
multinom bool

If True, do a multinomial fit where model is optimially scaled to data at each step. If False, assume theta is a parameter and do no scaling.

True
maxiter int

Maximum algorithm iterations to run.

100000.0
full_output bool

If True, return full outputs as in described in help(scipy.optimize.fmin_bfgs)

False
func_args list

Additional arguments to model_func. It is assumed that model_func's first argument is an array of parameters to optimize, that its second argument is an array of sample sizes for the sfs, and that its last argument is the list of grid points to use in evaluation.

[]
func_kwargs list

Additional keyword arguments to model_func.

{}
fixed_params list[float]

If not None, should be a list used to fix model parameters at particular values. For example, if the model parameters are (nu1,nu2,T,m), then fixed_params = [0.5,None,None,2] will hold nu1=0.5 and m=2. The optimizer will only change T and m. Note that the bounds lists must include all parameters. Optimization will fail if the fixed values lie outside their bounds. A full-length p0 should be passed in; values corresponding to fixed parameters are ignored. (See help(dadi.Inference.optimize_log for examples of func_args and fixed_params usage.)

None
ll_scale float

The bfgs algorithm may fail if your initial log-likelihood is too large. (This appears to be a flaw in the scipy implementation.) To overcome this, pass ll_scale > 1, which will simply reduce the magnitude of the log-likelihood. Once in a region of reasonable likelihood, you'll probably want to re-optimize with ll_scale=1.

1
Citation

The L-BFGS-B method was developed by Ciyou Zhu, Richard Byrd, and Jorge Nocedal. The algorithm is described in:

  • R. H. Byrd, P. Lu and J. Nocedal. A Limited Memory Algorithm for Bound Constrained Optimization, (1995), SIAM Journal on Scientific and Statistical Computing , 16, 5, pp. 1190-1208.

  • C. Zhu, R. H. Byrd and J. Nocedal. L-BFGS-B: Algorithm 778: L-BFGS-B, FORTRAN routines for large scale bound constrained optimization (1997), ACM Transactions on Mathematical Software, Vol 23, Num. 4, pp. 550-560.

Source code in dadi/Inference.py
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
def optimize_log_lbfgsb(p0, data, model_func, pts, 
                        lower_bound=None, upper_bound=None,
                        verbose=0, flush_delay=0.5, epsilon=1e-3, 
                        pgtol=1e-5, multinom=True, maxiter=1e5, 
                        full_output=False,
                        func_args=[], func_kwargs={}, fixed_params=None, 
                        ll_scale=1, output_file=None):
    """
    Optimize log(params) to fit model to data using the L-BFGS-B method.

    This optimization method works well when we start reasonably close to the
    optimum. It is best at burrowing down a single minimum. This method is
    better than optimize_log if the optimum lies at one or more of the
    parameter bounds. However, if your optimum is not on the bounds, this
    method may be much slower.

    Because this works in log(params), it cannot explore values of params < 0.
    It should also perform better when parameters range over scales.

    Args:
        p0 (list[float]): Initial parameters.
        data (Spectrum): Spectrum with data.
        model_func (func): Function to evaluate model spectrum. Should take arguments
                        (params, (n1,n2...), pts)
        lower_bound (list[float]): Lower bound on parameter values. If not None, must be of same
                    length as p0. A parameter can be declared unbound by assigning
                    a bound of None.
        upper_bound (list[float]): Upper bound on parameter values. If not None, must be of same
                    length as p0. A parameter can be declared unbound by assigning
                    a bound of None.
        verbose (int): If > 0, print optimization status every <verbose> steps.
        output_file (str): Stream verbose output into this filename. If None, stream to
                    standard out.
        flush_delay (float): Standard output will be flushed once every <flush_delay>
                    minutes. This is useful to avoid overloading I/O on clusters.
        epsilon (float): Step-size to use for finite-difference derivatives.
        pgtol (float): Convergence criterion for optimization. For more info, 
            see help(scipy.optimize.fmin_l_bfgs_b)
        multinom (bool): If True, do a multinomial fit where model is optimially scaled to
                data at each step. If False, assume theta is a parameter and do
                no scaling.
        maxiter (int): Maximum algorithm iterations to run.
        full_output (bool): If True, return full outputs as in described in 
                    help(scipy.optimize.fmin_bfgs)
        func_args (list): Additional arguments to model_func. It is assumed that 
                model_func's first argument is an array of parameters to
                optimize, that its second argument is an array of sample sizes
                for the sfs, and that its last argument is the list of grid
                points to use in evaluation.
        func_kwargs (list): Additional keyword arguments to model_func.
        fixed_params (list[float]): If not None, should be a list used to fix model parameters at
                    particular values. For example, if the model parameters
                    are (nu1,nu2,T,m), then fixed_params = [0.5,None,None,2]
                    will hold nu1=0.5 and m=2. The optimizer will only change 
                    T and m. Note that the bounds lists must include all
                    parameters. Optimization will fail if the fixed values
                    lie outside their bounds. A full-length p0 should be passed
                    in; values corresponding to fixed parameters are ignored. 
                    (See help(dadi.Inference.optimize_log for examples of func_args and 
                    fixed_params usage.)
        ll_scale (float): The bfgs algorithm may fail if your initial log-likelihood is
                too large. (This appears to be a flaw in the scipy
                implementation.) To overcome this, pass ll_scale > 1, which will
                simply reduce the magnitude of the log-likelihood. Once in a
                region of reasonable likelihood, you'll probably want to
                re-optimize with ll_scale=1.

    Citation:
        The L-BFGS-B method was developed by Ciyou Zhu, Richard Byrd, and Jorge
        Nocedal. The algorithm is described in:

        * R. H. Byrd, P. Lu and J. Nocedal. A Limited Memory Algorithm for Bound
            Constrained Optimization, (1995), SIAM Journal on Scientific and
            Statistical Computing , 16, 5, pp. 1190-1208.

        * C. Zhu, R. H. Byrd and J. Nocedal. L-BFGS-B: Algorithm 778: L-BFGS-B,
            FORTRAN routines for large scale bound constrained optimization (1997),
            ACM Transactions on Mathematical Software, Vol 23, Num. 4, pp. 550-560.

    """
    if output_file:
        output_stream = open(output_file, 'w')
    else:
        output_stream = sys.stdout

    args = (data, model_func, pts, None, None, verbose,
            multinom, flush_delay, func_args, func_kwargs, fixed_params, 
            ll_scale, output_stream)

    # Make bounds list. For this method it needs to be in terms of log params.
    if lower_bound is None:
        lower_bound = [None] * len(p0)
    else:
        lower_bound = numpy.log(lower_bound)
        lower_bound[numpy.isnan(lower_bound)] = None
    lower_bound = _project_params_down(lower_bound, fixed_params)
    if upper_bound is None:
        upper_bound = [None] * len(p0)
    else:
        upper_bound = numpy.log(upper_bound)
        upper_bound[numpy.isnan(upper_bound)] = None
    upper_bound = _project_params_down(upper_bound, fixed_params)
    bounds = list(zip(lower_bound,upper_bound))

    p0 = _project_params_down(p0, fixed_params)

    outputs = scipy.optimize.fmin_l_bfgs_b(_object_func_log, 
                                           numpy.log(p0), bounds = bounds,
                                           epsilon=epsilon, args = args,
                                           iprint = -1, pgtol=pgtol,
                                           maxfun=maxiter, approx_grad=True)
    xopt, fopt, info_dict = outputs

    xopt = _project_params_up(numpy.exp(xopt), fixed_params)

    if output_file:
        output_stream.close()

    if not full_output:
        return xopt
    else:
        return xopt, fopt, info_dict

optimize_log_powell(p0, data, model_func, pts, lower_bound=None, upper_bound=None, verbose=0, flush_delay=0.5, multinom=True, maxiter=None, full_output=False, func_args=[], func_kwargs={}, fixed_params=None, output_file=None)

Optimize log(params) to fit model to data using Powell's method.

Because this works in log(params), it cannot explore values of params < 0.

Parameters:

Name Type Description Default
p0 list[float]

Initial parameters.

required
data Spectrum

Spectrum with data.

required
model_func func

Function to evaluate model spectrum. Should take arguments (params, (n1,n2...), pts)

required
lower_bound list[float]

Lower bound on parameter values. If not None, must be of same length as p0. A parameter can be declared unbound by assigning a bound of None.

None
upper_bound list[float]

Upper bound on parameter values. If not None, must be of same length as p0. A parameter can be declared unbound by assigning a bound of None.

None
verbose int

If True, print optimization status every steps.

0
output_file str

Stream verbose output into this filename. If None, stream to standard out.

None
flush_delay float

Standard output will be flushed once every minutes. This is useful to avoid overloading I/O on clusters. multinom: If True, do a multinomial fit where model is optimially scaled to data at each step. If False, assume theta is a parameter and do no scaling.

0.5
maxiter int

Maximum iterations to run for.

None
full_output bool

If True, return full outputs as in described in help(scipy.optimize.fmin_bfgs)

False
func_args list

Additional arguments to model_func. It is assumed that model_func's first argument is an array of parameters to optimize, that its second argument is an array of sample sizes for the sfs, and that its last argument is the list of grid points to use in evaluation.

[]
func_kwargs list

Additional keyword arguments to model_func.

{}
fixed_params list[float]

If not None, should be a list used to fix model parameters at particular values. For example, if the model parameters are (nu1,nu2,T,m), then fixed_params = [0.5,None,None,2] will hold nu1=0.5 and m=2. The optimizer will only change T and m. Note that the bounds lists must include all parameters. Optimization will fail if the fixed values lie outside their bounds. A full-length p0 should be passed in; values corresponding to fixed parameters are ignored. (See help(dadi.Inference.optimize_log for examples of func_args and fixed_params usage.)

None
Source code in dadi/Inference.py
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
def optimize_log_powell(p0, data, model_func, pts,
                      lower_bound=None, upper_bound=None,
                      verbose=0, flush_delay=0.5,
                      multinom=True, maxiter=None,
                      full_output=False, func_args=[],
                      func_kwargs={},
                      fixed_params=None, output_file=None):
    """
    Optimize log(params) to fit model to data using Powell's method.

    Because this works in log(params), it cannot explore values of params < 0.

    Args:
        p0 (list[float]): Initial parameters.
        data (Spectrum): Spectrum with data.
        model_func (func): Function to evaluate model spectrum. Should take arguments
            (params, (n1,n2...), pts)
        lower_bound (list[float]): Lower bound on parameter values. If not None, must be of same
            length as p0. A parameter can be declared unbound by assigning
            a bound of None.
        upper_bound (list[float]): Upper bound on parameter values. If not None, must be of same
            length as p0. A parameter can be declared unbound by assigning
            a bound of None.
        verbose (int): If True, print optimization status every <verbose> steps.
        output_file (str): Stream verbose output into this filename. If None, stream to
            standard out.
        flush_delay (float): Standard output will be flushed once every <flush_delay>
            minutes. This is useful to avoid overloading I/O on clusters.
            multinom: If True, do a multinomial fit where model is optimially scaled to
            data at each step. If False, assume theta is a parameter and do
            no scaling.
        maxiter (int): Maximum iterations to run for.
        full_output (bool): If True, return full outputs as in described in
            help(scipy.optimize.fmin_bfgs)
        func_args (list): Additional arguments to model_func. It is assumed that
            model_func's first argument is an array of parameters to
            optimize, that its second argument is an array of sample sizes
            for the sfs, and that its last argument is the list of grid
            points to use in evaluation.
        func_kwargs (list): Additional keyword arguments to model_func.
        fixed_params (list[float]): If not None, should be a list used to fix model parameters at
            particular values. For example, if the model parameters
            are (nu1,nu2,T,m), then fixed_params = [0.5,None,None,2]
            will hold nu1=0.5 and m=2. The optimizer will only change
            T and m. Note that the bounds lists must include all
            parameters. Optimization will fail if the fixed values
            lie outside their bounds. A full-length p0 should be passed
            in; values corresponding to fixed parameters are ignored.
            (See help(dadi.Inference.optimize_log for examples of func_args and
            fixed_params usage.)
    """
    if output_file:
        output_stream = open(output_file, 'w')
    else:
        output_stream = sys.stdout

    args = (data, model_func, pts, lower_bound, upper_bound, verbose,
            multinom, flush_delay, func_args, func_kwargs, fixed_params, 1.0,
            output_stream)

    p0 = _project_params_down(p0, fixed_params)
    outputs = scipy.optimize.fmin_powell(_object_func_log, numpy.log(p0), args = args,
                                  disp=False, maxiter=maxiter, full_output=True)
    xopt, fopt, direc, iter, funcalls, warnflag = outputs
    xopt = _project_params_up(numpy.exp(xopt), fixed_params)

    if output_file:
        output_stream.close()

    if not full_output:
        return xopt
    else:
        return xopt, fopt, direc, iter, funcalls, warnflag

optimize_log_resid(p0, data, model_func, target_resid, pts, lower_bound=None, upper_bound=None, verbose=0, flush_delay=0.5, epsilon=0.001, gtol=1e-05, multinom=True, maxiter=None, full_output=False, func_args=[], func_kwargs={}, fixed_params=None, ll_scale=1, output_file=None)

Optimize log(params) to fit model to data using the BFGS method.

This optimization method works well when we start reasonably close to the optimum. It is best at burrowing down a single minimum.

Because this works in log(params), it cannot explore values of params < 0. It should also perform better when parameters range over scales.

Parameters:

Name Type Description Default
p0 list[float]

Initial parameters.

required
data Spectrum

Spectrum with data.

required
model_func func

Function to evaluate model spectrum. Should take arguments (params, (n1,n2...), pts)

required
target_resid Spectrum

The residual sfs that we want to match, obtained from the synonymous fits.

required
lower_bound list[float]

Lower bound on parameter values. If not None, must be of same length as p0.

None
upper_bound list[float]

Upper bound on parameter values. If not None, must be of same length as p0.

None
verbose int

If > 0, print optimization status every steps.

0
output_file str

Stream verbose output into this filename. If None, stream to standard out.

None
flush_delay float

Standard output will be flushed once every minutes. This is useful to avoid overloading I/O on clusters.

0.5
epsilon float

Step-size to use for finite-difference derivatives.

0.001
gtol float

Convergence criterion for optimization. For more info, see help(scipy.optimize.fmin_bfgs)

1e-05
multinom bool

If True, do a multinomial fit where model is optimially scaled to data at each step. If False, assume theta is a parameter and do no scaling.

True
maxiter int

Maximum iterations to run for.

None
full_output bool

If True, return full outputs as in described in help(scipy.optimize.fmin_bfgs)

False
func_args list

Additional arguments to model_func. It is assumed that model_func's first argument is an array of parameters to optimize, that its second argument is an array of sample sizes for the sfs, and that its last argument is the list of grid points to use in evaluation. Using func_args. For example, you could define your model function as def func((p1,p2), ns, f1, f2, pts): .... If you wanted to fix f1=0.1 and f2=0.2 in the optimization, you would pass func_args = [0.1,0.2] (and ignore the fixed_params argument).

[]
func_kwargs list

Additional keyword arguments to model_func.

{}
fixed_params list[float]

If not None, should be a list used to fix model parameters at particular values. For example, if the model parameters are (nu1,nu2,T,m), then fixed_params = [0.5,None,None,2] will hold nu1=0.5 and m=2. The optimizer will only change T and m. Note that the bounds lists must include all parameters. Optimization will fail if the fixed values lie outside their bounds. A full-length p0 should be passed in; values corresponding to fixed parameters are ignored. For example, suppose your model function is def func((p1,f1,p2,f2), ns, pts): .... If you wanted to fix f1=0.1 and f2=0.2 in the optimization, you would pass fixed_params = [None,0.1,None,0.2] (and ignore the func_args argument).

None
ll_scale float

The bfgs algorithm may fail if your initial log-likelihood is too large. (This appears to be a flaw in the scipy implementation.) To overcome this, pass ll_scale > 1, which will simply reduce the magnitude of the log-likelihood. Once in a region of reasonable likelihood, you'll probably want to re-optimize with ll_scale=1.

1
Source code in dadi/Inference.py
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
def optimize_log_resid(p0, data, model_func, target_resid, pts, lower_bound=None, upper_bound=None,
                 verbose=0, flush_delay=0.5, epsilon=1e-3, 
                 gtol=1e-5, multinom=True, maxiter=None, full_output=False,
                 func_args=[], func_kwargs={}, fixed_params=None, ll_scale=1,
                 output_file=None):
    """
    Optimize log(params) to fit model to data using the BFGS method.

    This optimization method works well when we start reasonably close to the
    optimum. It is best at burrowing down a single minimum.

    Because this works in log(params), it cannot explore values of params < 0.
    It should also perform better when parameters range over scales.

    Args:
        p0 (list[float]): Initial parameters.
        data (Spectrum): Spectrum with data.
        model_func (func): Function to evaluate model spectrum. Should take arguments
                        (params, (n1,n2...), pts)
        target_resid (Spectrum): The residual sfs that we want to match, obtained from the 
                    synonymous fits.
        lower_bound (list[float]): Lower bound on parameter values. If not None, must be of same
                    length as p0.
        upper_bound (list[float]): Upper bound on parameter values. If not None, must be of same
                    length as p0.
        verbose (int): If > 0, print optimization status every <verbose> steps.
        output_file (str): Stream verbose output into this filename. If None, stream to
                    standard out.
        flush_delay (float): Standard output will be flushed once every <flush_delay>
                    minutes. This is useful to avoid overloading I/O on clusters.
        epsilon (float): Step-size to use for finite-difference derivatives.
        gtol (float): Convergence criterion for optimization. For more info, 
            see help(scipy.optimize.fmin_bfgs)
        multinom (bool): If True, do a multinomial fit where model is optimially scaled to
                data at each step. If False, assume theta is a parameter and do
                no scaling.
        maxiter (int): Maximum iterations to run for.
        full_output (bool): If True, return full outputs as in described in 
                    help(scipy.optimize.fmin_bfgs)
        func_args (list): Additional arguments to model_func. It is assumed that 
                model_func's first argument is an array of parameters to
                optimize, that its second argument is an array of sample sizes
                for the sfs, and that its last argument is the list of grid
                points to use in evaluation.
                Using func_args.
                For example, you could define your model function as
                def func((p1,p2), ns, f1, f2, pts):
                    ....
                If you wanted to fix f1=0.1 and f2=0.2 in the optimization, you
                would pass func_args = [0.1,0.2] (and ignore the fixed_params 
                argument).
        func_kwargs (list): Additional keyword arguments to model_func.
        fixed_params (list[float]): If not None, should be a list used to fix model parameters at
                    particular values. For example, if the model parameters
                    are (nu1,nu2,T,m), then fixed_params = [0.5,None,None,2]
                    will hold nu1=0.5 and m=2. The optimizer will only change 
                    T and m. Note that the bounds lists must include all
                    parameters. Optimization will fail if the fixed values
                    lie outside their bounds. A full-length p0 should be passed
                    in; values corresponding to fixed parameters are ignored.
                    For example, suppose your model function is 
                    def func((p1,f1,p2,f2), ns, pts):
                        ....
                    If you wanted to fix f1=0.1 and f2=0.2 in the optimization, 
                    you would pass fixed_params = [None,0.1,None,0.2] (and ignore
                    the func_args argument).
        ll_scale (float): The bfgs algorithm may fail if your initial log-likelihood is
                too large. (This appears to be a flaw in the scipy
                implementation.) To overcome this, pass ll_scale > 1, which will
                simply reduce the magnitude of the log-likelihood. Once in a
                region of reasonable likelihood, you'll probably want to
                re-optimize with ll_scale=1.
    """
    if output_file:
        output_stream = open(output_file, 'w')
    else:
        output_stream = sys.stdout

    args = (data, model_func, target_resid, pts, lower_bound, upper_bound, verbose,
            multinom, flush_delay, func_args, func_kwargs, fixed_params, 
            ll_scale, output_stream)

    p0 = _project_params_down(p0, fixed_params)
    outputs = scipy.optimize.fmin_bfgs(_object_func_log_resid, 
                                       numpy.log(p0), epsilon=epsilon,
                                       args = args, gtol=gtol, 
                                       full_output=True,
                                       disp=False,
                                       maxiter=maxiter)
    xopt, fopt, gopt, Bopt, func_calls, grad_calls, warnflag = outputs
    xopt = _project_params_up(numpy.exp(xopt), fixed_params)

    if output_file:
        output_stream.close()

    if not full_output:
        return xopt
    else:
        return xopt, fopt, gopt, Bopt, func_calls, grad_calls, warnflag