Tyche Module¶
tyche.DecisionGUI¶
Interactive exploration of a technology.
- class tyche.DecisionGUI.DecisionWindow(evaluator)[source]¶
Bases:
object
Class for displaying an interactive interface to explore cost-benefit tradeoffs for a technology.
- reevaluate(next=<function DecisionWindow.<lambda>>, delay=200)[source]¶
Recalculate the results after a delay.
- Parameters:
next (function) – The operation to perform after completing the recalculation.
delay (int) – The number of milliseconds to delay before the recalculation.
tyche.Designs¶
Designs for technologies.
- class tyche.Designs.Designs(path=None, name='technology.xlsx', uncertain=True)[source]¶
Bases:
object
Designs for a technology.
- indices¶
The indices table.
- Type:
DataFrame
- functions¶
The functions table.
- Type:
DataFrame
- designs¶
The designs table.
- Type:
DataFrame
- parameters¶
The parameters table.
- Type:
DataFrame
- results¶
The results table.
- Type:
DataFrame
- evaluate(technology, sample_count=1)[source]¶
Evaluate the performance of a technology.
- Parameters:
technology (str) – The name of the technology.
sample_count (int) – The number of random samples.
- evaluate_tranche_impacts(sample_count=1)[source]¶
Evaluate tranchess.
- Parameters:
sample_count (int) – The number of random samples.
tyche.Distributions¶
Utilities for probability distributions.
- tyche.Distributions.choice(a, size=None, replace=True, p=None)¶
Generates a random sample from a given 1-D array
New in version 1.7.0.
Note
New code should use the ~numpy.random.Generator.choice method of a ~numpy.random.Generator instance instead; please see the random-quick-start.
- Parameters:
a (1-D array-like or int) – If an ndarray, a random sample is generated from its elements. If an int, the random sample is generated as if it were
np.arange(a)
size (int or tuple of ints, optional) – Output shape. If the given shape is, e.g.,
(m, n, k)
, thenm * n * k
samples are drawn. Default is None, in which case a single value is returned.replace (boolean, optional) – Whether the sample is with or without replacement. Default is True, meaning that a value of
a
can be selected multiple times.p (1-D array-like, optional) – The probabilities associated with each entry in a. If not given, the sample assumes a uniform distribution over all entries in
a
.
- Returns:
samples – The generated random samples
- Return type:
single item or ndarray
- Raises:
ValueError – If a is an int and less than zero, if a or p are not 1-dimensional, if a is an array-like of size 0, if p is not a vector of probabilities, if a and p have different lengths, or if replace=False and the sample size is greater than the population size
See also
randint
,shuffle
,permutation
random.Generator.choice
which should be used in new code
Notes
Setting user-specified probabilities through
p
uses a more general but less efficient sampler than the default. The general sampler produces a different sample than the optimized sampler even if each element ofp
is 1 / len(a).Sampling random rows from a 2-D array is not possible with this function, but is possible with Generator.choice through its
axis
keyword.Examples
Generate a uniform random sample from np.arange(5) of size 3:
>>> np.random.choice(5, 3) array([0, 3, 4]) # random >>> #This is equivalent to np.random.randint(0,5,3)
Generate a non-uniform random sample from np.arange(5) of size 3:
>>> np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0]) array([3, 3, 0]) # random
Generate a uniform random sample from np.arange(5) of size 3 without replacement:
>>> np.random.choice(5, 3, replace=False) array([3,1,0]) # random >>> #This is equivalent to np.random.permutation(np.arange(5))[:3]
Generate a non-uniform random sample from np.arange(5) of size 3 without replacement:
>>> np.random.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0]) array([2, 3, 0]) # random
Any of the above can be repeated with an arbitrary array-like instead of just integers. For instance:
>>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher'] >>> np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3]) array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'], # random dtype='<U11')
- tyche.Distributions.constant(value)[source]¶
The constant distribution.
- Parameters:
value (float) – The constant value.
tyche.EpsilonConstraints¶
Epsilon-constraint optimization.
- class tyche.EpsilonConstraints.EpsilonConstraintOptimizer(evaluator, scale=1000000.0)[source]¶
Bases:
object
An epsilon-constration multi-objective optimizer.
- evaluator¶
The technology evaluator.
- Type:
tyche.Evaluator
- scale¶
The scaling factor for output.
- Type:
float
- opt_diffev(metric, sense=None, max_amount=None, total_amount=None, eps_metric=None, statistic=<function mean>, strategy='best1bin', seed=2, tol=0.01, maxiter=75, init='latinhypercube', verbose=0)[source]¶
Maximize the objective function using the differential_evoluaion algorithm.
- Parameters:
metric (str) – Name of metric to maximize. The objective function.
sense (str) –
- Optimization sense (‘min’ or ‘max’). If no value is provided to
this method, the sense value used to create the EpsilonConstraintOptimizer object is used instead.
max_amount (Series) – Maximum investment amounts by R&D category. The index (research area) order must follow that of self.evaluator.max_amount.index
total_amount (float) – Upper limit on total investments summed across all R&D categories.
eps_metric (Dict) – RHS of the epsilon constraint(s) on one or more metrics. Keys are metric names, and the values are dictionaries of the form {‘limit’: float, ‘sense’: str}. The sense defines whether the epsilon constraint is a lower or an upper bound, and the value must be either ‘upper’ or ‘lower’.
statistic (function) – Summary statistic used on the sample evaluations; the metric measure that is fed to the optimizer.
strategy (str) – Which differential evolution strategy to use. ‘best1bin’ is the default. See algorithm docs for full list.
seed (int) – Sets the random seed for optimization by creating a new RandomState instance. Defaults to 1. Not setting this parameter means the solutions will not be reproducible.
init (str or array-like) – Type of population initialization. Default is Latin hypercube; alternatives are ‘random’ or specifying every member of the initial population in an array of shape (popsize, len(variables)).
tol (float) – Relative tolerance for convergence
maxiter (int) – Upper limit on generations of evolution (analogous to algorithm iterations)
verbose (int) – Verbosity level returned by this outer function and the differential_evolution algorithm. verbose = 0 No messages verbose = 1 Objective function value at every algorithm iteration verbose = 2 Investment constraint status, metric constraint status, and objective function value verbose = 3 Decision variable values, investment constraint status, metric constraint status, and objective function value verbose > 3 All metric values, decision variable values, investment constraint status, metric constraint status, and objective function value
- opt_milp(metric, sense=None, max_amount=None, total_amount=None, eps_metric=None, statistic=<function mean>, sizelimit=1000000.0, verbose=0)[source]¶
Maximize the objective function using a piecewise linear representation to create a mixed integer linear program.
- Parameters:
metric (str) – Name of metric to maximize
sense (str) – Optimization sense (‘min’ or ‘max’). If no value is provided to this method, the sense value used to create the EpsilonConstraintOptimizer object is used instead.
max_amount (Series) – Maximum investment amounts by R&D category. The index (research area) order must follow that of self.evaluator.max_amount.index
total_amount (float) – Upper limit on total investments summed across all R&D categories.
eps_metric (Dict) – RHS of the epsilon constraint(s) on one or more metrics. Keys are metric names, and the values are dictionaries of the form {‘limit’: float, ‘sense’: str}. The sense defines whether the epsilon constraint is a lower or an upper bound, and the value must be either ‘upper’ or ‘lower’.
statistic (function) – Summary statistic (metric measure) fed to evaluator_corners_wide method in Evaluator
total_amount – Upper limit on total investments summed across all R&D categories
sizelimit (int) – Maximum allowed number of binary variables. If the problem size exceeds this limit, pwlinear_milp will exit before building or solving the model.
verbose (int) – A value greater than zero will save the optimization model as a .lp file A value greater than 1 will print out status messages
- Returns:
Optimum – exit_code exit_message amounts (None, if no solution found) metrics (None, if no solution found) solve_time opt_sense
- Return type:
NamedTuple
- opt_shgo(metric, sense=None, max_amount=None, total_amount=None, eps_metric=None, statistic=<function mean>, tol=0.01, maxiter=None, sampling_method='simplicial', verbose=0)[source]¶
Maximize the objective function using the shgo global optimization algorithm.
- Parameters:
metric (str) – Name of metric to maximize.
sense (str) – Optimization sense (‘min’ or ‘max’). If no value is provided to this method, the sense value used to create the EpsilonConstraintOptimizer object is used instead.
max_amount (Series) – Maximum investment amounts by R&D category. The index (research area) order must follow that of self.evaluator.max_amount.index
total_amount (float) – Upper metric_limit on total investments summed across all R&D categories.
eps_metric (Dict) – RHS of the epsilon constraint(s) on one or more metrics. Keys are metric names, and the values are dictionaries of the form {‘limit’: float, ‘sense’: str}. The sense defines whether the epsilon constraint is a lower or an upper bound, and the value must be either ‘upper’ or ‘lower’.
statistic (function) – Summary metric_statistic used on the sample evaluations; the metric measure that is fed to the optimizer.
tol (float) – Objective function tolerance in stopping criterion.
maxiter (int) – Upper metric_limit on iterations that can be performed. Defaults to None. Specifying this parameter can cause shgo to stall out instead of solving.
sampling_method (str) – Allowable values are ‘sobol and ‘simplicial’. Simplicial is default, uses less memory, and guarantees convergence (theoretically). Sobol is faster, uses more memory and does not guarantee convergence. Per documentation, Sobol is better for “easier” problems.
verbose (int) – Verbosity level returned by this outer function and the SHGO algorithm. verbose = 0 No messages verbose = 1 Convergence messages from SHGO algorithm verbose = 2 Investment constraint status, metric constraint status, and convergence messages verbose = 3 Decision variable values, investment constraint status, metric constraint status, and convergence messages verbose > 3 All metric values, decision variable values, investment constraint status, metric constraint status, and convergence messages
- opt_slsqp(metric, sense=None, max_amount=None, total_amount=None, eps_metric=None, statistic=<function mean>, initial=None, tol=1e-08, maxiter=50, verbose=0)[source]¶
Optimize the objective function using the fmin_slsqp algorithm.
- Parameters:
metric (str) – Name of metric to maximize.
sense (str) – Optimization sense (‘min’ or ‘max’). If no value is provided to this method, the sense value used to create the EpsilonConstraintOptimizer object is used instead.
max_amount (Series) – Maximum investment amounts by R&D category. The index (research area) order must follow that of self.evaluator.max_amount.index
total_amount (float) – Upper limit on total investments summed across all R&D categories.
eps_metric (Dict) – RHS of the epsilon constraint(s) on one or more metrics. Keys are metric names, and the values are dictionaries of the form {‘limit’: float, ‘sense’: str}. The sense defines whether the epsilon constraint is a lower or an upper bound, and the value must be either ‘upper’ or ‘lower’.
statistic (function) – Summary statistic used on the sample evaluations; the metric measure that is fed to the optimizer.
initial (array of float) – Initial value of decision variable(s) fed to the optimizer.
tol (float) – Search tolerance fed to the optimizer.
maxiter (int) – Maximum number of iterations the optimizer is permitted to execute.
verbose (int) – Verbosity level returned by the optimizer and this outer function. Defaults to 0. verbose = 0 No messages verbose = 1 Summary message when fmin_slsqp completes verbose = 2 Status of each algorithm iteration and summary message verbose = 3 Investment constraint status, metric constraint status, status of each algorithm iteration, and summary message verbose > 3 All metric values, decision variable values, investment constraint status, metric constraint status, status of each algorithm iteration, and summary message
- optimum_metrics(max_amount=None, total_amount=None, sense=None, statistic=<function mean>, tol=1e-08, maxiter=50, verbose=0)[source]¶
Maximum value of metrics.
- Parameters:
max_amount (DataFrame) – The maximum amounts that can be invested in each category.
total_amount (float) – The maximum amount that can be invested in toto.
sense (Dict or str) – Optimization sense for each metric. Must be ‘min’ or ‘max’. If None, then the sense provided to the EpsilonConstraintOptimizer class is used for all metrics. If string, the sense is used for all metrics.
statistic (function) – The statistic used on the sample evaluations.
tol (float) – The search tolerance.
maxiter (int) – The maximum iterations for the search.
verbose (int) – Verbosity level.
tyche.Evaluator¶
Fast evaluation of technology investments.
- class tyche.Evaluator.Evaluator(tranches)[source]¶
Bases:
object
Evalutate technology investments using a response surface.
- amounts¶
Cost of tranches.
- Type:
DataFrame
- categories¶
Categories of investment.
- Type:
DataFrame
- metrics¶
Metrics for technologies.
- Type:
DataFrame
- units¶
Units of measure for metrics.
- Type:
DataFrame
- interpolators¶
Interpolation functions for technology metrics.
- Type:
DataFrame
- evaluate(amounts)[source]¶
Sample the distribution for an investment.
- Parameters:
amounts (DataFrame) – The investment levels.
- evaluate_corners_semilong(statistic=<function mean>)[source]¶
Return a dataframe indexed my investment amounts in each category, with columns for each metric.
- Parameters:
statistic (function) – The statistic to evaluate.
- evaluate_corners_wide(statistic=<function mean>)[source]¶
Return a dataframe indexed my investment amounts in each category, with columns for each metric.
- Parameters:
statistic (function) – The statistic to evaluate.
tyche.IO¶
I/O utilities for Tyche.
- tyche.IO.check_tables(path, name)[source]¶
Perform validity checks on input datasets.
All checks are run before this method terminates; that is, data errors are found all at once rather than one at a time from several calls to this method. A list of errors found is printed if any check fails. The errors include a summary of the check and identify the dataset that needs to be changed.
- Parameters:
path (str) – Path to directory of datasets
name (str) – Name of datasets file (XLSX)
- Returns:
Boolean
- Return type:
True if data is valid, False otherwise
tyche.Investments¶
Investments in technologies.
- class tyche.Investments.Investments(path=None, name='technology.xlsx', uncertain=False, tranches='tranches', investments='investments')[source]¶
Bases:
object
Investments in a technology.
- tranches¶
The tranches table.
- Type:
DataFrame
- investments¶
The investments table.
- Type:
DataFrame
- evaluate_investments(designs, tranche_results=None, sample_count=1)[source]¶
Evaluate the investments for a design.
- Parameters:
designs (tyche.Designs) – The designs.
tranche_results (tyche.Evaluations) – Output of evaluate_tranches method. Necessary only if the investment amounts contain uncertainty.
sample_count (int) – The number of random samples.
tyche.Types¶
Data types for Tyche.
- class tyche.Types.Evaluations(amounts, metrics, summary, uncertain)¶
Bases:
tuple
Named tuple type for rows in the evaluations table.
- amounts¶
Alias for field number 0
- metrics¶
Alias for field number 1
- summary¶
Alias for field number 2
- uncertain¶
Alias for field number 3
- class tyche.Types.Functions(style, capital, fixed, production, metric)¶
Bases:
tuple
Name tuple type for rows in the functions table.
- capital¶
Alias for field number 1
- fixed¶
Alias for field number 2
- metric¶
Alias for field number 4
- production¶
Alias for field number 3
- style¶
Alias for field number 0
- class tyche.Types.Indices(capital, input, output, metric)¶
Bases:
tuple
Name tuple type for rows in the indices table.
- capital¶
Alias for field number 0
- input¶
Alias for field number 1
- metric¶
Alias for field number 3
- output¶
Alias for field number 2
- class tyche.Types.Inputs(lifetime, scale, input, input_efficiency, input_price, output_efficiency, output_price)¶
Bases:
tuple
Named tuple type for rows in the inputs table.
- input¶
Alias for field number 2
- input_efficiency¶
Alias for field number 3
- input_price¶
Alias for field number 4
- lifetime¶
Alias for field number 0
- output_efficiency¶
Alias for field number 5
- output_price¶
Alias for field number 6
- scale¶
Alias for field number 1
- class tyche.Types.Optimum(exit_code, exit_message, amounts, metrics, solve_time, opt_sense)¶
Bases:
tuple
Named tuple type for optimization results.
- amounts¶
Alias for field number 2
- exit_code¶
Alias for field number 0
- exit_message¶
Alias for field number 1
- metrics¶
Alias for field number 3
- opt_sense¶
Alias for field number 5
- solve_time¶
Alias for field number 4
Module contents¶
Tyche: a Python package for R&D pathways analysis and evaluation.