def test_optimised_trajectories_groups(setup_param_groups_prime): """ Tests that the optimisation problem gives the same answer as the brute force problem (for small values of `k_choices` and `N`) with groups """ N = 11 param_file = setup_param_groups_prime problem = read_param_file(param_file) num_levels = 4 k_choices = 4 num_params = problem['num_vars'] groups = compute_groups_matrix(problem['groups'], num_params) input_sample = _sample_groups(problem, N, num_levels) # From gurobi optimal trajectories strategy = GlobalOptimisation() actual = strategy.sample(input_sample, N, num_params, k_choices, groups) brute_strategy = BruteForce() desired = brute_strategy.sample(input_sample, N, num_params, k_choices, groups) assert_equal(actual, desired)
def print_indices(S, problem, calc_second_order, file): # taken from the SAlib source code and modified to print to file # https://github.com/SALib/SALib/blob/3bc2ddfb50f091e5e5dd1ed4e7fae05853f150e5/SALib/analyze/sobol.py#L240 # Output to console if not problem.get('groups'): title = 'Parameter' names = problem['names'] D = problem['num_vars'] else: title = 'Group' _, names = compute_groups_matrix(problem['groups']) D = len(names) print('%s S1 S1_conf ST ST_conf' % title, file=file) for j in range(D): print('%s %f %f %f %f' % (names[j], S['S1'][ j], S['S1_conf'][j], S['ST'][j], S['ST_conf'][j]), file=file) if calc_second_order: print('\n%s_1 %s_2 S2 S2_conf' % (title, title), file=file) for j in range(D): for k in range(j + 1, D): print("%s %s %f %f" % (names[j], names[k], S['S2'][j, k], S['S2_conf'][j, k]), file=file)
def _sample_groups(problem, N, num_levels, grid_jump): """Generate trajectories for groups Returns an :math:`N(g+1)`-by-:math:`k` array of `N` trajectories, where :math:`g` is the number of groups and :math:`k` is the number of factors Arguments --------- problem : dict The problem definition N : int The number of trajectories to generate num_levels : int The number of grid levels grid_jump : int The grid jump size Returns ------- numpy.ndarray """ group_membership, _ = compute_groups_matrix(problem['groups']) if group_membership is None: raise ValueError("Please define the matrix group_membership.") if not isinstance(group_membership, np.matrixlib.defmatrix.matrix): raise TypeError("Matrix group_membership should be formatted \ as a numpy matrix") num_params = group_membership.shape[0] num_groups = group_membership.shape[1] sample = np.zeros((N * (num_groups + 1), num_params)) sample = np.array([ generate_trajectory(group_membership, num_levels, grid_jump) for n in range(N) ]) return sample.reshape((N * (num_groups + 1), num_params))
def _sample_morris(problem: Dict, number_trajectories: int, num_levels: int = 4) -> np.ndarray: """Generate trajectories for groups Returns an :math:`N(g+1)`-by-:math:`k` array of `N` trajectories, where :math:`g` is the number of groups and :math:`k` is the number of factors Parameters --------- problem : dict The problem definition number_trajectories : int The number of trajectories to generate num_levels : int, default=4 The number of grid levels Returns ------- numpy.ndarray """ groups = _check_groups(problem) group_membership, _ = compute_groups_matrix(groups) _check_group_membership(group_membership) num_params = group_membership.shape[0] num_groups = group_membership.shape[1] sample_morris = [_generate_trajectory(group_membership, num_levels) for _ in range(number_trajectories)] sample_morris = np.array(sample_morris) return sample_morris.reshape((number_trajectories * (num_groups + 1), num_params))
def test_compute_groups_from_parameter_file(): ''' Tests that a group file is read correctly ''' actual_matrix, actual_unique_names = \ compute_groups_matrix(['Group 1', 'Group 2', 'Group 2'], 3) assert_equal(actual_matrix, np.matrix('1,0;0,1;0,1', dtype=np.int)) assert_equal(actual_unique_names, ['Group 1', 'Group 2'])
def test_compute_groups_from_parameter_file(): ''' Tests that a group file is read correctly ''' actual_matrix, actual_unique_names = \ compute_groups_matrix(['Group 1', 'Group 2', 'Group 2']) assert_equal(actual_matrix, np.array( [[1, 0], [0, 1], [0, 1]], dtype=np.int)) assert_equal(actual_unique_names, ['Group 1', 'Group 2'])
def test_compute_groups_from_parameter_file(): """ Tests that a group file is read correctly """ actual_matrix, actual_unique_names = \ compute_groups_matrix(['Group 1', 'Group 2', 'Group 2']) assert_equal(actual_matrix, np.array([[1, 0], [0, 1], [0, 1]], dtype=np.int)) assert_equal(actual_unique_names, ['Group 1', 'Group 2'])
def test_group_in_param_file_read(setup_param_file_with_groups): ''' Tests that groups in a parameter file are read correctly ''' parameter_file = setup_param_file_with_groups problem = read_param_file(parameter_file) groups, group_names = compute_groups_matrix(problem['groups']) assert_equal(problem['names'], ["Test 1", "Test 2", "Test 3"]) assert_equal(groups, np.array([[1, 0], [1, 0], [0, 1]], dtype=np.int)) assert_equal(group_names, ['Group 1', 'Group 2'])
def test_group_in_param_file_read(setup_param_file_with_groups): ''' Tests that groups in a parameter file are read correctly ''' parameter_file = setup_param_file_with_groups problem = read_param_file(parameter_file) groups, group_names = compute_groups_matrix( problem['groups']) assert_equal(problem['names'], ["Test 1", "Test 2", "Test 3"]) assert_equal(groups, np.array([[1, 0], [1, 0], [0, 1]], dtype=np.int)) assert_equal(group_names, ['Group 1', 'Group 2'])
def test_group_in_param_file_read(): ''' Tests that groups in a parameter file are read correctly ''' parameter_file = setup_param_file_with_groups() problem = read_param_file(parameter_file) groups, group_names = compute_groups_matrix(problem['groups'], problem['num_vars']) assert_equal(problem['names'], ["Test 1", "Test 2", "Test 3"]) assert_equal(groups, np.matrix('1,0;1,0;0,1', dtype=np.int)) assert_equal(group_names, ['Group 1', 'Group 2'])
def _sample_groups(problem, N, num_levels=4): """Generate trajectories for groups Returns an :math:`N(g+1)`-by-:math:`k` array of `N` trajectories, where :math:`g` is the number of groups and :math:`k` is the number of factors Arguments --------- problem : dict The problem definition N : int The number of trajectories to generate num_levels : int, default=4 The number of grid levels Returns ------- numpy.ndarray """ if len(problem['groups']) != problem['num_vars']: raise ValueError("Groups do not match to number of variables") group_membership, _ = compute_groups_matrix(problem['groups']) if group_membership is None: raise ValueError("Please define the 'group_membership' matrix") if not isinstance(group_membership, np.ndarray): raise TypeError("Argument 'group_membership' should be formatted \ as a numpy ndarray") num_params = group_membership.shape[0] num_groups = group_membership.shape[1] sample = np.zeros((N * (num_groups + 1), num_params)) sample = np.array([generate_trajectory(group_membership, num_levels) for n in range(N)]) return sample.reshape((N * (num_groups + 1), num_params))
def _sample_groups(problem, N, num_levels, grid_jump): """Generate trajectories for groups Returns an :math:`N(g+1)`-by-:math:`k` array of `N` trajectories, where :math:`g` is the number of groups and :math:`k` is the number of factors Arguments --------- problem : dict The problem definition N : int The number of trajectories to generate num_levels : int The number of grid levels grid_jump : int The grid jump size Returns ------- numpy.ndarray """ group_membership, _ = compute_groups_matrix(problem['groups']) if group_membership is None: raise ValueError("Please define the matrix group_membership.") if not isinstance(group_membership, np.matrixlib.defmatrix.matrix): raise TypeError("Matrix group_membership should be formatted \ as a numpy matrix") num_params = group_membership.shape[0] num_groups = group_membership.shape[1] sample = np.zeros((N * (num_groups + 1), num_params)) sample = np.array([generate_trajectory(group_membership, num_levels, grid_jump) for n in range(N)]) return sample.reshape((N * (num_groups + 1), num_params))
conf_level=0.95, print_to_console=False, num_levels=4, grid_jump=2, num_resamples=1000) Si_CumulativeCO2 = morris.analyze(problem, param_values, Morris_Objectives[:, 1], conf_level=0.95, print_to_console=False, num_levels=4, grid_jump=2, num_resamples=1000) num_vars = problem['num_vars'] groups, unique_group_names = compute_groups_matrix(problem['groups'], num_vars) number_of_groups = len(unique_group_names) print("{0:<30} {1:>10} {2:>10} {3:>15} {4:>10}".format("Parameter", "Mu_Star", "Mu", "Mu_Star_Conf", "Sigma")) for j in list(range(number_of_groups)): print("{0:30} {1:10.3f} {2:10.3f} {3:15.3f} {4:10.3f}".format( Si_OF['names'][j], Si_OF['mu_star'][j], Si_OF['mu'][j], Si_OF['mu_star_conf'][j], Si_OF['sigma'][j])) import csv line1 = Si_OF['mu_star'] line2 = Si_OF['mu_star_conf'] line3 = Si_CumulativeCO2['mu_star'] line4 = Si_CumulativeCO2['mu_star_conf'] with open('MMResults.csv', 'w') as f: writer = csv.writer(f, delimiter=',')