def main(argc, argv): ampl = AMPL(Environment(r'C:\Users\etjones\Desktop\AI OPS\AMPL\amplide.mswin64')) os.chdir(os.path.dirname(__file__) or os.curdir) try: if argc > 1: ampl.setOption('solver', argv[1]) # Read the model and data files. #modelDirectory = argv[2] if argc == 3 else os.path.join('..', 'models') #ampl.read(os.path.join(modelDirectory, 'diet/diet.mod')) #ampl.readData(os.path.join(modelDirectory, 'diet/diet.dat')) ampl.read(r'C:\Users\etjones\Desktop\AI OPS\AMPL\custom_models\transp.mod') ampl.readData(r'C:\Users\etjones\Desktop\AI OPS\AMPL\custom_models\transp.dat') # Solve print('\n' + "AMPL MODEL:" + '\n') ampl.solve() totalcost = ampl.getObjective('Total_Cost') print("Minimum Cost:", totalcost.value()) print('\n' + "Optimal Flow:") ampl.display('Trans') print('\n' + "Compare pdf flow to the above table to confirm optmial flows") except Exception as e: print(e) raise
def main(argc, argv): from amplpy import AMPL os.chdir(os.path.dirname(__file__) or os.curdir) try: # Create an AMPL instance ampl = AMPL(Environment('C:/xampp/htdocs/python/ampl/ampl.mswin64')) """ # If the AMPL installation directory is not in the system search path: from amplpy import Environment ampl = AMPL( Environment('C:/xampp/htdocs/python/ampl/ampl.mswin64')) """ if argc > 1: ampl.setOption('solver', argv[1]) # Read the model and data files. modelDirectory = argv[2] if argc == 3 else os.path.join('..', 'models') ampl.read(os.path.join(modelDirectory, 'diet/diet.mod')) ampl.readData(os.path.join(modelDirectory, 'diet/diet.dat')) # Solve ampl.solve() # Get objective entity by AMPL name totalcost = ampl.getObjective('Total_Cost') # Print it print("Objective is:", totalcost.value()) # Reassign data - specific instances cost = ampl.getParameter('cost') cost.setValues({'BEEF': 5.01, 'HAM': 4.55}) print("Increased costs of beef and ham.") # Resolve and display objective ampl.solve() print("New objective value:", totalcost.value()) # Reassign data - all instances elements = [3, 5, 5, 6, 1, 2, 5.01, 4.55] cost.setValues(elements) print("Updated all costs.") # Resolve and display objective ampl.solve() print("New objective value:", totalcost.value()) # Get the values of the variable Buy in a dataframe object buy = ampl.getVariable('Buy') df = buy.getValues() # Print them print(df) # Get the values of an expression into a DataFrame object df2 = ampl.getData('{j in FOOD} 100*Buy[j]/Buy[j].ub') # Print them print(df2) except Exception as e: print(e) raise
def solver(alpha, n_intersections, C, g_i_inbound, g_i_outbound, delta, verbose=True): """ Solves the linear problem for the given set of parameters :param alpha: :type alpha: :param n_intersections: :type n_intersections: :param C: :type C: :param g_i_inbound: :type g_i_inbound: :param g_i_outbound: :type g_i_outbound: :param delta: :type delta: :return: :rtype: """ ampl = AMPL(Environment(path)) # Set the solver ampl.setOption('solver', path + '/cplex') # Read the model file ampl.read('lp.mod') # Set parameters values ampl.param['alpha'] = alpha ampl.param['N'] = n_intersections ampl.param['C'] = C ampl.param['g_incoming'] = g_i_inbound ampl.param['g_outgoing'] = g_i_outbound ampl.param['delta'] = delta if verbose == True: print("alpha: {}".format(alpha)) print("N: {}".format(n_intersections)) print("C: {}".format(C)) print("g_incoming: {}".format(g_i_inbound)) print("g_outgoing: {}".format(g_i_outbound)) print("delta: {}".format(delta)) # Resolve and display objective ampl.solve() bandwidth = ampl.getObjective('bandwidth').value() # Display the variables b_incoming = ampl.getVariable('b_incoming').value() b_outgoing = ampl.getVariable('b_outgoing').value() wl = ampl.getVariable('w').getValues() if verbose == True: print("New objective value: {}".format(bandwidth)) print("New offsets: {}".format(list(wl.toPandas()['w.val']))) print("Incoming bandwidth: {}".format(b_incoming)) print("Outgoing bandwidth: {}".format(b_outgoing)) # return bandwidths and offset values return b_incoming, b_outgoing, list(wl.toPandas()['w.val'])
def test_environment(self): from amplpy import Environment, AMPL env1 = Environment() env2 = Environment(os.curdir) self.assertEqual(env2.get_bin_dir(), os.curdir) env1.set_bin_dir(env2.get_bin_dir()) self.assertEqual(env1.get_bin_dir(), env1.get_bin_dir()) self.assertEqual(len(dict(env1)), len(list(env1))) self.assertEqual(list(sorted(dict(env1).items())), list(sorted(env1))) env1["MyEnvVar"] = "TEST" self.assertEqual(env1["MyEnvVar"], "TEST") self.assertEqual(env2["MyEnvVar"], None) d = dict(env1) self.assertEqual(d["MyEnvVar"], "TEST") ampl = AMPL(Environment()) ampl.close()
def calculate(*args): try: ampl = AMPL(Environment('/Users/zintun/Downloads/amplide.macosx64')) ##path has to change accordingly ampl.setOption('solver', 'gurobi') ampl.read('Y3_Elementals.mod') ampl.readData('Y3_data.dat') day_val = int(day.get()) print(day_val) T = ampl.getParameter('T') T.set(day_val) ampl.solve() v1 = ampl.getVariable('X').getValues() c = v1.toList() rows = [[int(column) for column in row] for row in c] org_mat = [] dest_mat = [] mod_mat = [] value_mat = [] for i in range(len(rows)): element = rows[i] origin = element[0] dest = element[1] mode = element[2] value = element[3] org_mat.append(origin) dest_mat.append(dest) mod_mat.append(mode) value_mat.append(value) N = ampl.getParameter('N').getValues() N1 = N.toList() N_rows = [[int(column) for column in row] for row in N1] count = 0 exist = [] while(count < len(N_rows)): if(N_rows[count][3] or N_rows[count+1][3] or N_rows[count+2][3] or N_rows[count+3][3]): exist.extend([1, 1, 1,1]) else: exist.extend([0, 0, 0,0]) count = count + 4 cost = ampl.getObjective('Cost').value() drawGraph1(org_mat,dest_mat,mod_mat,value_mat,exist,cost) except ValueError: pass
def solver(alpha, n_intersections, C, g_i_inbound, g_i_outbound, delta, print_=True): """ Solves the linear problem for the given set of parameters :param alpha: :type alpha: :param n_intersections: :type n_intersections: :param C: :type C: :param g_i_inbound: :type g_i_inbound: :param g_i_outbound: :type g_i_outbound: :param delta: :type delta: :return: :rtype: """ ampl = AMPL(Environment(path)) # Set the solver ampl.setOption('solver', path + '/cplex') # Read the model file ampl.read('lp.mod') # Set parameters values ampl.param['alpha'] = alpha ampl.param['N'] = n_intersections ampl.param['C'] = C ampl.param['g_incoming'] = g_i_inbound ampl.param['g_outgoing'] = g_i_outbound ampl.param['delta'] = delta # Resolve and display objective ampl.solve() bandwidth = ampl.getObjective('bandwidth').value() # Display the variables b_incoming = ampl.getVariable('b_incoming').value() b_outgoing = ampl.getVariable('b_outgoing').value() w_relative = ampl.getVariable('w').getValues() w_relative = [w[1] for w in w_relative] if print_ == True: print("New objective value: {}".format(bandwidth)) print("Incoming bandwidth: {}".format(b_incoming)) print("Outgoing bandwidth: {}".format(b_outgoing)) print("Incoming offsets: {}".format(w_relative)) # return bandwidths and offset values return b_incoming, b_outgoing, w_relative
def solve_sscfl_instance(mod_file, sscfl_instance, ampl_folder): print('### AMPL SOLUTION ###') if ampl_folder is None: primal_pl = AMPL() else: primal_pl = AMPL(Environment(ampl_folder)) primal_pl.read('ampl_mod_files/' + mod_file) primal_pl.setOption('solver', 'cplex') primal_pl = write_ampl_sscfl_dat_file(primal_pl, sscfl_instance) primal_pl.solve() f = primal_pl.getObjective('f') print('\nZ = ', '%.5f' % (f.value())) return f.value()
def compute_defense(att_stg, prod_dist, num_of_hp=args.fix_honeypots, rationality=args.fix_rationality): # production ports and attacker"s strategy df = DataFrame('P') ports = getRelPorts(att_stg, prod_dist, num=25) df.setColumn('P', list(ports)) #ports = getAllPorts(att_stg, prod_dist) #print(('Considered ports are: ', ports)) att = [att_stg.get(x, 0) for x in ports] prod = [prod_dist.get(x, 0) for x in ports] #print(('Attack ports: ', att, len(att))) #print(('Dist ports: ', prod, len(prod))) df.addColumn('s', prod) df.addColumn('p', att) ampl = AMPL(Environment(args.ampl)) ampl.setOption('solver', args.solver) # ampl.setOption('verbosity', 'terse') # Read the model file ampl.read(args.model) # Assign data to s ampl.setData(df, 'P') ampl.eval('let L := {}; let rat := {};'.format(num_of_hp, rationality)) #print(df) # Solve the model with suppress_stdout(): ampl.solve() reward = ampl.getObjective("reward").value() hp_stg = ampl.getData("{j in P} h[j]") output = dict() stg_json = list() for k, v in hp_stg.toDict().items(): stg_json.append({"port": int(k), "prob": v}) output.update({"stg": stg_json}) output.update({"reward": reward}) output.update({"rationality": rationality}) output.update({"num_of_hp": num_of_hp}) output.update({"used_hps": ampl.getData("tot").toDict().popitem()[1]}) ampl.close() return output
def run_ampl_model(data, minW=0.01, maxW=0.6, ex=0, K=3): dir = os.path.dirname(__file__) dir = 'C:\\Biblioteki\\AMPL\\ampl.mswin64' # dir=dir.replace('/','\\') # ampl = AMPL() ampl = AMPL(Environment(dir)) if ex < 1: ampl.read('omg3.txt') data_file = generate_temp_data_file(data, minW=minW, maxW=maxW) ampl.setOption('solver', dir + '\minos.exe') elif ex == 2: ampl.read('omg_lmt.txt') data_file = generate_temp_data_file_lmt(data, minW=minW, maxW=maxW, K=K) ampl.setOption('solver', dir + '\cplex.exe') elif ex == 3: # ampl.read('omg_lmt.txt') ampl.read('omg4.txt') data_file = generate_temp_data_file_lmt(data, minW=minW, maxW=maxW, K=K) ampl.setOption('solver', dir + '\cplex.exe') else: ampl.read('eomg.txt') data_file = generate_temp_data_file_ex(data, minW=minW, maxW=maxW) ampl.setOption('solver', dir + '\minos.exe') # data_file=open('data_pattern.txt') ampl.readData(data_file.name) # ampl.readData('data_test.dat') data_file.close() ampl.solve() x = get_np_array_from_variable(ampl, 'x') # x=ampl.getVariable('x').getValues().toPandas() v0 = ampl.getVariable('v0').getValues().toPandas() sol = [] for i in range(x.shape[1]): sol.append(x.iloc[0, i] / v0.iloc[0, 0]) return sol
import random from functools import reduce import matplotlib.pyplot as plt import subprocess import time from amplpy import AMPL, Environment import numpy as np #start 10:10 end 10:18 ampl = AMPL(Environment('/home/asino/Downloads/ampl_linux-intel64/')) ampl.setOption("solver", "/home/asino/Downloads/ampl_linux-intel64/cplex") random.seed(7) np.random.seed(7) players = {} playersList = [] bidders = {} biddersList = [] NBIDDERS = 8 BUDGET = 500 INCREMENT = 1 PLAYERS_PER_ROLE = {"A": 30, "C": 50, "D": 50, "P": 20} VAR_PER_ROLE = {"A": 5, "C": 3, "D": 2, "P": 1} for role, number in PLAYERS_PER_ROLE.items(): for i in range(number): player = {} player["name"] = role + str(i) player["perf"] = np.random.normal( scale=VAR_PER_ROLE[role]) #random.random()
import amplpy import pandas as pd from string import ascii_lowercase from amplpy import AMPL, Environment # In[2]: print("Enter the kind of puzzle you want to solve : \n") puzzle = int(input("Enter 1 for 3-In-A-Row, or 2 for ABC-Path: ")) ampl = AMPL(Environment("C:/Users/mayan/OneDrive/Documents/AMPL/ampl_mswin64")) ampl.setOption("solver", "cplex") if puzzle == 1: ampl.reset() ampl.read('p2t05mod3.mod') ampl.readData('p2t05dat3.dat') #ask for user input for 3 in a row size = int(input("Enter the size of the grid (that is number of rows or columns in the grid) : \n")) invalid = int(input("Enter the number of minimum invalid consecutive cells : \n")) lst = []
from amplpy import AMPL, Environment import sys import os ampl = AMPL( Environment( 'C:/Users/Meyerhofer/Desktop/UNI/OTDM/SVM-project/ampl_mswin64')) size = range(-5, 9) #for each nu: def main(): for i in range(-5, 9): f = open("data/nu.txt", "w") nu = 2**i print("----------------------------------------") print("nu= " + str(nu)) f.write(str(nu)) f.close() os.system("ampl_mswin64\\ampl primal.run") f = open("output/primal/acc_train.txt", "r") acc_train = f.read() acc_trainValue = acc_train.split(" = ")[1].split("\n")[0] print("Train accuracy= " + str(acc_trainValue)) f.close() f = open("output/primal/acc_test.txt", "r") acc_test = f.read() acc_testValue = acc_test.split(" = ")[1].split("\n")[0] print("Test accuracy= " + str(acc_testValue))
from amplpy import AMPL, Environment import os import sys sys.path.append(os.getcwd()) from env_path import ENV_PATH experiment_name = "zero_sum" ampl = AMPL(Environment(ENV_PATH)) ampl.read(os.path.join(os.getcwd(), experiment_name, experiment_name + '.mod')) ampl.readData( os.path.join(os.getcwd(), experiment_name, experiment_name + '.dat')) ampl.solve() totalcost = ampl.getObjective('Max_cost') print("Difference in objectives is:", totalcost.value()) u = ampl.getVariable('u') u = u.getValues() t = ampl.getVariable('t') t = t.getValues() print("Objectives are {}, {}".format(u, t)) x = ampl.getVariable('p') x = x.getValues() y = ampl.getVariable('q') y = y.getValues() print(x, y)
distance_matrix[(d, r)] = abs(r - base) if weeks == 1 and 0.5 in course_frequency.values(): raise ValueError( "Creating a one-week schedule with courses with frequency of 0.5 is not possible. Please review the data") # sys.exit() print("Optimized Room Assignment Tool") print("Setup") print("Expected Number of Courses: ", sum(list(course_frequency.values()))) environment = os.environ.get("AMPL_PATH", "ampl") ampl = AMPL(Environment(environment)) ampl.setOption('solver', 'cplex') amplcode = AmplCode.from_file('room_assignment.txt') # print("Parameters from AMPL Code:") # print(amplcode.get_params()) amplcode.set_param("DpW", data=DpW) amplcode.set_param("TpD", data=TpD) amplcode.set_param("weeks", data=weeks) # amplcode.set_set('rooms', '{' + ','.join(map(str, rooms)) + '}') amplcode.set_set('rooms', '{' + ','.join(map(str, rooms)) + '}') amplcode.set_set('courses', '{1..%i}' % course_count) amplcode.set_set('departments', list(departmentHQ.keys()))
def testEnvironment(self): from amplpy import Environment, AMPL env1 = Environment() env2 = Environment(os.curdir) self.assertEqual(env2.getBinDir(), os.curdir) env1.setBinDir(env2.getBinDir()) self.assertEqual(env1.getBinDir(), env1.getBinDir()) self.assertEqual(len(dict(env1)), len(list(env1))) self.assertEqual(list(sorted(dict(env1).items())), list(sorted(env1))) env1['MyEnvVar'] = 'TEST' self.assertEqual(env1['MyEnvVar'], 'TEST') self.assertEqual(env2['MyEnvVar'], None) d = dict(env1) self.assertEqual(d['MyEnvVar'], 'TEST') ampl = AMPL(Environment()) ampl.close()
training_dat = "phase2_training.dat"#input("What's the directory of your training .dat file?") validating_dir = "Validation_Dataset.csv" #input("What's the directory of your validating set?") model_dir = "phase2_lasso.mod" #input("What's the directory of your model?") ampl_dir = "/home/nub3ar/AMPL" #input("Where is ampl installed on your computer?") #"E:\ampl_mswin64" validating_data = pd.read_csv(open(validating_dir)) #dimensions of the data dv1,dv2 = validating_data.shape print(dv1, dv2) #column names col_names_va = validating_data.columns.values #x/y variable separation y_va = validating_data.loc[0::,'Label'].values.tolist() x_va = validating_data.loc[0::,'Item'::] ############AMPL################# ampl = AMPL(Environment(ampl_dir)) index_list = [] Accuracy_list = [] for index in (range 1:1000) ampl.reset() tuning = ampl.getParameter("tuning") tuning.SetValues(0.00001*index) ampl.read(model_dir) ampl.readData(training_dat) ampl.solve() a = ampl.getVariable('a').getValues().toList() b = ampl.getVariable('b').value() #parsing the coefficients a_list = []
from amplpy import AMPL, Environment from tree import * amplPATH = 'C:\\Users\\jose_\\Documents\\USM\\USM\\2020-2\\GIO\\tareas\\Tarea1\\ampl_mswin64' ampl = AMPL(Environment(amplPATH)) def feasible(restrictions): # restrictions = [] valids = 0 for r in restrictions: if r: valids += 1 return valids == len(restrictions) def simplex(): print("-------------------------------") print("Comenzando algoritmo simplex") print("-------------------------------") # Interpret the two files print("leyendo mod.mod...") ampl.read('ampl/mod.mod') print("leyendo dat.dat...") ampl.readData('dat.dat') print("resolviendo el problema...") ampl.solve()
#Global variables (The paths must be changed by the user). #--------------------------------------------------------- #Folder where AMPL is located on the computer. ampl_path = '/home/victor/ampl_linux-intel64' #If the .py is saved in the same folder of gensvmdat, change path to "". #Otherwise put the correct folder path and the new files will be stored there. path = '/home/victor/Escritorio/Matlab/OM/ProjecteSVM' #Epsilon used to avoid problems of precision with floating points. #It is recommended to not change this value. epsilon = 1e-05 #--------------------------------------------------------- #Functions that allow the set-up the connection between python and AMPL. ampl = AMPL(Environment('/home/victor/ampl_linux-intel64')) #If another solver than cplex wants to be used, modify that parameter with #the name of the desired solver. ampl.setOption('solver', 'cplex') #--------------------------------------------------------- #Auxiliar function to generate data with the swiss function. def swiss_generation(num_points,seed,test): A,y = ds.make_swiss_roll(num_points,2,seed) #aux = statistics.median(y) aux = np.mean(y) for i in range(num_points): if(y[i] < aux): y[i] = -1 else: y[i] = 1 wr = np.matrix(A); ite = np.matrix(y); ite = ite.reshape(ite.size,1); write = np.c_[wr,ite];
def main(argc, argv): from amplpy import AMPL, Environment ampl = AMPL( Environment(r'C:\Users\etjones\Desktop\AI OPS\AMPL\amplide.mswin64')) os.chdir(os.path.dirname(__file__) or os.curdir) try: if argc > 1: ampl.setOption('solver', argv[1]) # Read the model and data files. #modelDirectory = argv[2] if argc == 3 else os.path.join('..', 'models') #ampl.read(os.path.join(modelDirectory, 'diet/diet.mod')) #ampl.readData(os.path.join(modelDirectory, 'diet/diet.dat')) ampl.read( r'C:\Users\etjones\Desktop\AI OPS\AMPL\custom_models\transp.mod') ampl.readData( r'C:\Users\etjones\Desktop\AI OPS\AMPL\custom_models\transp.dat') # Solve ampl.solve() totalcost = ampl.getObjective('Total_Cost') print("Minimum Cost:", totalcost.value()) #a = ampl.getVariable('Trans') #print("Objective is:", a.value()) # Get objective entity by AMPL name #totalcost = ampl.getObjective('total_cost') # Print it #print("Objective is:", totalcost.value()) # Reassign data - specific instances # cost = ampl.getParameter('cost') # cost.setValues({'BEEF': 5.01, 'HAM': 4.55}) # print("Increased costs of beef and ham.") # Resolve and display objective # ampl.solve() # print("New objective value:", totalcost.value()) # Reassign data - all instances # elements = [3, 5, 5, 6, 1, 2, 5.01, 4.55] # cost.setValues(elements) # print("Updated all costs.") # Resolve and display objective # ampl.solve() # print("New objective value:", totalcost.value()) # Get the values of the variable Buy in a dataframe object # buy = ampl.getVariable('Buy') # df = buy.getValues() # Print them # print(df) # Get the values of an expression into a DataFrame object # df2 = ampl.getData('{j in FOOD} 100*Buy[j]/Buy[j].ub') # # Print them # print(df2) except Exception as e: print(e) raise
# 2nd paper 2. Monte Carlo simulation # forecasted solar data : real data # real data to simulate : sampling from real data # Call the AMPL-Phthon API to Python from amplpy import AMPL, DataFrame, Environment # Call some packages import numpy as np import pandas as pd # Determine the path of the directory where AMPL is installed. ampl = AMPL(Environment('path of AMPL')) # Call energy scheduling model file and data file from the path of the directory where AMPL files are located ampl.read('Energy_Scheduling.mod') ampl.readData('Energy_Scheduling.dat') # Determine the solver from AMPL ampl.setOption('solver','C:/Users/David_Cho/Desktop/ampl_mswin64/cplex') # Define variables to calculate yearly data results global d_loss_sim d_loss_sim = 0 decide_running = 0
import sys import os import pandas as pd from amplpy import AMPL, Environment # Holds dataframe of output. output = None try: # Binary path to AMPL install location. ampl = AMPL(environment=Environment(binaryDirectory=r'C:\Program Files\AMPL')) # Integer programming solver. ampl.setOption('solver', 'gurobi') # Read in AMPL files. ampl.read('wings.mod') ampl.readData('wings.dat') # Insert cost as column. output = ampl.param['cost'].getValues().toPandas() output.index = pd.to_numeric(output.index, downcast='integer') output.index.name = 'wings' # Solve for multiple target values. Can't solve for less than 4 wings. MAX_TARGET_TO_SOLVE = 400 for target in range(4, MAX_TARGET_TO_SOLVE + 1): # Show progress. print('Processing target of {}...'.format(target))
def test_environment_initialization(self): from amplpy import Environment env = Environment("binary_directory") self.assertEqual("binary_directory", env.get_bin_dir()) env = Environment("binary_directory", "binary_name") self.assertEqual("binary_directory", env.get_bin_dir()) self.assertEqual("binary_name", env.get_bin_name()) env.set_bin_dir("binary_directory_2") self.assertEqual("binary_directory_2", env.get_bin_dir()) env.set_bin_name("binary_name_2") self.assertEqual("binary_name_2", env.get_bin_name())
from amplpy import AMPL, Environment ampl = AMPL(Environment(r'C:\Users\diego\Documents\Diego_Aldunate\iPre\AMPL')) ampl.read(r'C:\Users\diego\Documents\Diego_Aldunate\iPre\AMPL/models/diet.mod') ampl.readData( r'C:\Users\diego\Documents\Diego_Aldunate\iPre\AMPL/models/diet.dat') ampl.solve() # Get objective entity by AMPL name totalcost = ampl.getObjective('total_cost') # Print it print("Objective is:", totalcost.value()) # Reassign data - specific instances cost = ampl.getParameter('cost') cost.setValues({'BEEF': 5.01, 'HAM': 4.55}) print("Increased costs of beef and ham.") print(cost.getValues()) # Resolve and display objective ampl.solve() print("New objective value:", totalcost.value()) # Reassign data - all instances cost.setValues([3, 5, 5, 6, 1, 2, 5.01, 4.55]) #se actualizan valores de los parametros print("Updated all costs.") print(cost.getValues()) # Resolve and display objective
# -*- coding: utf-8 -*- """ Created on Sat Aug 11 17:20:23 2018 @author: donja """ from amplpy import AMPL, Environment ampl = AMPL(Environment('D:\\amplide.mswin64\\amplide.mswin64')) ampl.option['solver'] = 'cplexamp' ampl.read('example.mod') #read the model ampl.eval('objective z; solve;') ampl.display('z', 'roth', 'traditional', 'surplus') pstring = """ objective function = {z} bi-weekly roth contribution = ${roth} bi-weekly traditional contribution = ${traditional} surplus (amount left after optimal allocation) = ${surplus} total (without surplus) = ${total} total (with surplus) = ${totalS} """ z = ampl.getValue('z') roth = ampl.getValue('roth') traditional = ampl.getValue('traditional') surplus = ampl.getValue('surplus') annual_roth_amt = roth * 12 * 2 annual_traditional_amt = traditional * 12 * 2
def run_one_experiment(ampl, obj = 5, ppl = 5): generate(obj = obj, ppl = ppl) ampl.reset() ampl.read('/home/jon/Berkeley/ieor169/project/169projectPEnvy.mod') ampl.readData("/home/jon/Berkeley/ieor169/project/random_data/{}ppl{}obj.dat".format(ppl, obj)) ampl.setOption('solver', 'cplex') start_time = time.time() ampl.solve() finish_time = time.time() p_envy = ampl.getObjective('p_envy').value() return p_envy, finish_time-start_time ampl = AMPL(Environment("/home/jon/Berkeley/amplide.linux64")) count = 0 with open('penvy.csv', 'a', newline='') as csvfile: fieldnames = ['Number of People', 'Number of Items', 'Optimal P-Envy', 'Wall Clock Time'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for i in range(1,10): for j in range(1,10): for _ in range(30): p_envy, run_time = run_one_experiment(ampl, i, j) out = {'Number of People': j, 'Number of Items': i, 'Optimal P-Envy': p_envy, 'Wall Clock Time': run_time} print(out)
ampl.reset() ampl.read('/Users/jonathan/Desktop/169projectPEnvy.mod') ampl.readData( "/Users/jonathan/Desktop/random_data/{}ppl{}obj_heuristic.dat".format( ppl, obj)) ampl.setOption('solver', 'cplex') start_time = time.time() ampl.solve() finish_time = time.time() p_envy = ampl.getObjective('p_envy').value() return p_envy, finish_time - start_time ampl = AMPL( Environment( "/Users/jonathan/Documents/files/amplide.macosx64/amplide.macosx64")) with open('part4.csv', 'a', newline='') as csvfile: fieldnames = [ 'Number of People', 'Number of Items', 'Optimal P-Envy', 'Wall Clock Time' ] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for i in range(1, 11): for j in range(1, 11): for _ in range(30): p_envy, run_time = run_one_experiment(ampl, i, j) out = { 'Number of People': j, 'Number of Items': i,
from amplpy import AMPL, Environment import functions as fun import numpy as np import random import time import sys import os # Path donde está AMPL en nuestro ordenador ampl = AMPL(Environment('/home/alex/AMPL/ampl_linux-intel64')) #ampl = AMPL(Environment('/home/elias/Escritorio/uni/2º/OM/ampl_linux-intel64')) # Escogemos el solver cplex ampl.setOption('solver', 'cplex') ''' PARÁMETROS: - option: nos indica que tipo de problema vamos a resolver 1: primal 2: dual con kernel lineal 3: dual con kernel gaussiano - num_points: número de puntos - seed: semilla para la generación aleatoria del dataset - nu: parámetro de la formulación del problema SVM - data_type: indica si generamos los puntos con el algoritmo proporcionado por el profesor (gensvmdat), con el algoritmo del swiss roll (brazo de gitano) de sklearn o usamos la base de datos "skin" 1: Para generarlos con gensvmdat (datos linealmente separables) 2: Para generarlos con sklearn swiss_roll (datos no separables linealmente) 3: Para usar la base de datos "skin" ''' #try: option = int(sys.argv[1])