예제 #1
0
    def run(self):
        t_s = time.time()

        # set SALib problem
        names = []
        bounds = []
        for parameter in self.problem.parameters:
            names.append(parameter['name'])
            bounds.append(parameter['bounds'])

        self.sa_problem = {
            'num_vars': len(self.problem.parameters),
            'names': names,
            'bounds': bounds
        }

        # generate samples
        if self.options["method"] == "rbd_fast":
            self.samples_x = latin_sample(self.sa_problem,
                                          self.options["samples"])
        elif self.options["method"] == "fast":
            self.samples_x = fast_sample(self.sa_problem,
                                         self.options["samples"])
        elif self.options["method"] == "morris":
            self.samples_x = morris_sample(self.sa_problem,
                                           self.options["samples"],
                                           num_levels=4)
        elif self.options["method"] == "sobol":
            self.samples_x = sobol_sample(self.sa_problem,
                                          self.options["samples"])
        elif self.options["method"] == "delta":
            self.samples_x = latin_sample(self.sa_problem,
                                          self.options["samples"])
        elif self.options["method"] == "ff":
            self.samples_x = ff_sample(self.sa_problem,
                                       self.options["samples"])

        individuals = []
        for vector in self.samples_x:
            individuals.append(Individual(vector))

        # append to problem
        for individual in individuals:
            self.problem.individuals.append(individual)

        # evaluate individuals
        self.evaluate(individuals)

        for individual in individuals:
            self.samples_y.append(individual.costs[0])  # TODO: fix index [0]
        self.samples_y = np.array(self.samples_y)

        t = time.time() - t_s
        self.problem.logger.info("Sensitivity: elapsed time: {} s".format(t))

        # sync changed individual informations
        self.problem.data_store.sync_all()
예제 #2
0
def populate():
    # 'parameters' dictionary stores each line in the model
    par_keys = list(parameters.keys())

    # init problem definiton
    seed = int(opts['seed'])
    levels = int(opts['p_levels'])

    problem = {
        'names': opts['par_name'],
        'num_vars': len(opts['par_name']),
        'bounds': [],
    }

    # define bounds following the model configuration
    for line in range(len(par_keys)):
        if parameters[line][0] == 'par':
            if parameters[line][3] == 'range':
                lower = float(parameters[par_keys[line]][4])
                upper = float(parameters[par_keys[line]][5])
            if parameters[line][3] == 'factor':
                lower = float(parameters[line][2]) * (
                    1 - float(parameters[par_keys[line]][4]))
                upper = float(parameters[line][2]) * (
                    1 + float(parameters[par_keys[line]][5]))
            problem['bounds'].append([lower, upper])

    # create samples to simulate
    if opts['method'] == 'sobol':
        models = saltelli.sample(problem=problem,
                                 N=levels,
                                 calc_second_order=True,
                                 seed=seed)
    elif opts['method'] == 'fast':
        models = fast_sampler.sample(problem=problem, N=levels, seed=seed)
    elif opts['method'] == 'rbd-fast' or opts['method'] == 'delta' or opts[
            'method'] == 'dgsm':
        models = latin.sample(problem=problem, N=levels, seed=seed)
    elif opts['method'] == 'morris':
        models = morris_sample(problem=problem, N=levels)
    elif opts['method'] == 'frac':
        models = ff_sample(problem, seed=seed)
    else:
        error_msg = 'Wrong method name.'
        print(error_msg)
        raise ValueError(error_msg)

    population = {}
    # add samples to population dict
    population['problem', 'samples'] = models
    # add problem definition to population dict
    population['problem', 'definition'] = problem

    return population
예제 #3
0
    param_values = saltelli.sample(problem, sample_number)
    parm = (param_values + 1) * 7e10
elif method_flag == 2:
    param_values = latin.sample(problem, sample_number)
    parm = (param_values + 1) * 7e10
elif method_flag == 3:
    param_values = finite_diff.sample(problem, sample_number, delta=0.001)
    parm = (param_values + 1) * 7e10
elif method_flag == 4:
    param_values = fast_sampler.sample(problem, sample_number)
    parm = (param_values + 1) * 7e10
elif method_flag == 5:
    param_values = ff_sample(problem)
    parm = (param_values[:, :21] + 1) * 7e10
elif method_flag == 6:
    param_values = morris_sample(problem, N=sample_number, num_levels=4, grid_jump=2, \
                      optimal_trajectories=None)
    parm = (param_values + 1) * 7e10
elif method_flag == 7:
    param_values = saltelli.sample(problem, sample_number)
    parm = (param_values + 1) * 7e10

## Run model (example)
FEM_freq = uncertainty_analysis.uncertainty_analysis.random_freq_run(
    analysis=analysis1, parm=parm, target='E', index=index)

## Statistical model

##Compare test data and FEM data
#fig, ax = plt.subplots()
#ax.scatter(test_freq[:,3],test_freq[:,5],marker='o',label='Nominal test data')
#ax.scatter(FEM_freq[:1000:10,3],FEM_freq[:1000:10,5],marker='x',label='Initial data')
예제 #4
0
def populate():
    # 'parameters' dictionary stores each line in the model
    par_keys = list(parameters.keys())

    # init problem definiton
    seed = int(opts['seed'])
    levels = int(opts['p_levels'])
    problem = {
        'names': opts['par_name'],
        'num_vars': len(opts['par_name']),
        'bounds': [],
    }

    # define bounds following the model configuration
    for line in range(len(par_keys)):
        if parameters[line][0] == 'par':
            if parameters[line][3] == 'range':
                lower = float(parameters[par_keys[line]][4])
                upper = float(parameters[par_keys[line]][5])
            if parameters[line][3] == 'factor':
                lower = float(parameters[line][2]) * (
                    1 - float(parameters[par_keys[line]][4]))
                upper = float(parameters[line][2]) * (
                    1 + float(parameters[par_keys[line]][5]))
            problem['bounds'].append([lower, upper])

    # create samples to simulate
    if opts['method'] == 'sobol':
        models = saltelli.sample(problem=problem,
                                 N=levels,
                                 calc_second_order=True,
                                 seed=seed)
    elif opts['method'] == 'fast':
        models = fast_sampler.sample(problem=problem, N=levels, seed=seed)
    elif opts['method'] == 'rbd-fast' or opts['method'] == 'delta' or opts[
            'method'] == 'dgsm':
        models = latin.sample(problem=problem, N=levels, seed=seed)
    elif opts['method'] == 'morris':
        models = morris_sample(problem=problem, N=levels)
    elif opts['method'] == 'frac':
        models = ff_sample(problem, seed=seed)
    else:
        error_msg = 'Wrong method name.'
        print(error_msg)
        raise ValueError(error_msg)

    # add samples to population dict
    population = {}
    population['problem', 'samples'] = models

    # write models
    model_string = 'level{:0' + str(len(str(len(models)))) + 'd}'

    for model_index, model in enumerate(models):
        model_key = model_string.format(model_index + 1)
        population[model_key, 'model'] = model_key
        for par_index, par_name in enumerate(opts['par_name']):
            population[model_key, par_name] = models[model_index][par_index]

    # generate a kappa file per model
    par_string = '%var: \'{:s}\' {:.' + opts['par_prec'] + '}\n'

    if opts['continue'] == '1':
        for model in sorted(population.keys()):
            if model[1] == 'model':
                for simulation in range(opts['nsims']):
                    model_key = model[0]
                    model_name = population[model_key, 'model']

                    # define pertubation to the kappa model that indicates KaSim to calculates the Dinamic Influence Network
                    #if opts['type'] == 'total':
                    if opts['syntax'] == '4':
                        flux = '%mod: [T] > {:s} do $DIN \"flux_{:s}_{:03d}.json\" [true];\n'.format(
                            opts['tmin'], model_key, simulation)
                        flux += '%mod: [T] > {:s} do $DIN \"flux_{:s}_{:03d}.json\" [false];'.format(
                            opts['tmax'], model_key, simulation)
                    else:  # kappa3.5 uses $FLUX instead of $DIN
                        flux = '%mod: [T] > {:s} do $FLUX \"flux_{:s}_{:03d}.json\" [true]\n'.format(
                            opts['tmin'], model_key, simulation)
                        flux += '%mod: [T] > {:s} do $FLUX \"flux_{:s}_{:03d}.json\" [false]'.format(
                            opts['tmax'], model_key, simulation)

                #else: # sliced global sensitivity analysis
                #if opts['syntax'] == '4':
                #flux = '%mod: repeat (([T] > DIM_clock) && (DIM_tick > (DIM_length - 1))) do $DIN "flux_".(DIM_tick - DIM_length).".json" [false] until [false];'
                #else: # kappa3.5 uses $FLUX instead of $DIN
                #flux = '\n# Added to calculate a sliced global sensitivity analysis\n'
                #flux += '%var: \'DIN_beat\' {:s}\n'.format(opts['beat'])
                #flux += '%var: \'DIN_length\' {:s}\n'.format(opts['size'])
                #flux += '%var: \'DIN_tick\' {:s}\n'.format(opts['tick'])
                #flux += '%var: \'DIN_clock\' {:s}\n'.format(opts['tmin'])
                #flux += '%mod: repeat (([T] > DIN_clock) && (DIN_tick > (DIN_length - 1))) do '
                #flux += '$FLUX \"flux_{:s}\".(DIN_tick - DIN_length).\".json\" [false] until [false]\n'.format(model_key)
                #flux += '%mod: repeat ([T] > DIN_clock) do '
                #flux += '$FLUX "flux_{:s}".DIN_tick.".json" "probability" [true] until ((((DIN_tick + DIN_length) + 1) * DIN_beat) > [Tmax])\n'.format(model_key)
                #flux += '%mod: repeat ([T] > DIN_clock) do $UPDATE DIN_clock (DIN_clock + DIN_beat); $UPDATE DIN_tick (DIN_tick + 1) until [false]'

                    model_path = './model_{:s}_{:03d}.kappa'.format(
                        model_name, simulation)
                    if not os.path.exists(model_path):
                        with open(model_path, 'w') as file:
                            for line in par_keys:
                                if parameters[line][0] == 'par':
                                    file.write(
                                        par_string.format(
                                            parameters[line][1],
                                            population[model_key,
                                                       parameters[line][1]]))
                                else:
                                    file.write(parameters[line])
                            # add the DIN perturbation at the end of the kappa file
                            file.write(flux)

    # add problem definition to population dict
    population['problem', 'definition'] = problem

    return population
예제 #5
0
from SALib.sample import saltelli
from SALib.sample.morris import sample as morris_sample
from SALib.analyze import sobol
from SALib.analyze import morris
from optimize.optimisation import fitness_booth_function
import numpy as np

problem = {'num_vars': 2, 'names': ['x', 'y'], 'bounds': [[0, 10], [0, 10]]}

param_sample_sobol = saltelli.sample(problem, 1000)

Y_sobol = np.zeros(param_sample_sobol.shape[0])

for index, X in enumerate(param_sample_sobol):
    Y_sobol[index] = fitness_booth_function(X)

Si = sobol.analyze(problem, Y_sobol, print_to_console=True)

param_sample_morris = morris_sample(problem, 1000)

Y_morris = np.zeros(param_sample_morris.shape[0])

for index, X in enumerate(param_sample_morris):
    Y_morris[index] = fitness_booth_function(X)

print()
print('Morris\n')

morris.analyze(problem, param_sample_morris, Y_morris, print_to_console=True)