def ejecuta(self): for f in self.ficheros: print(f) g = Greedy(f, self.semilla) antes = time.time() gs = g.greedy() despues = time.time() self.tiempos.append(despues - antes) self.valores.append(g.evalua_sol(gs)) self.imprime()
def test_sum_by_profit(self): ksf = KnapsackFile("test.txt") lines = ksf.getlines() items = Greedy.create_items(lines) weight_items = Greedy.sum_by_value(limit=6, list_of_items=items, func=lambda item: item.profit) self.assertIs(len(weight_items), 1) weight_items = Greedy.sum_by_value(limit=7, list_of_items=items, func=lambda item: item.profit) self.assertIs(len(weight_items), 2) weight_items = Greedy.sum_by_value(limit=9, list_of_items=items, func=lambda item: item.profit) self.assertIs(len(weight_items), 3)
def preorderDTLsort(DTLReconGraph, ParasiteRoot): """This takes in a DTL dictionary and parasite root and returns a sorted list, orderedKeysL, that is ordered by level from smallest to largest, where level 0 is the root and the highest level has tips.""" keysL = Greedy.orderDTL(DTLReconGraph, ParasiteRoot) uniqueKeysL = Greedy.sortHelper(DTLReconGraph, keysL) orderedKeysL = [] levelCounter = 0 while len(orderedKeysL) < len(uniqueKeysL): for mapping in uniqueKeysL: if mapping[-1] == levelCounter: orderedKeysL = orderedKeysL + [mapping] levelCounter += 1 return orderedKeysL
def main(): """Main function""" # Dictionary that stores all the nodes of the graph # in which the keys are the nodes' IDs dataNodes = {} # Readin data readInput(dataNodes) # Using Greedy algorithm Greedy.greedySearch(dataNodes, INITIAL_NODE, FINAL_NODE) # Using A* algorithm AStar.aStarSearch(dataNodes, INITIAL_NODE, FINAL_NODE)
def main(): """ Main function. Calls initailizing functions and then calls the requested Algorithm Args: None Returns: None Globals: None Called By: cmd.exe Calls: init() Greedy.init() """ instanceDir = init() if instanceDir == -1: return -1 for file in os.listdir(instanceDir): instance = Utility.init(instanceDir, file) result = Greedy.main(instance) Utility.outputFileGenerator(result, file)
def pre_process(self) -> dict: # obtain D2 greedy = Greedy.Greedy(self.G, INF, self.rho2, self.rho2, self.heuristic) greedy.run() self.D2 = greedy.D2 # print (self.D2) # gernerate subgraph for each node in D2 dic = {} for u in self.D2: sub = self.sub_graph(u) g = Greedy.Greedy(sub, INF, self.rho1, self.rho1, self.heuristic) g.run() # obtain D1 (actually D2 in Greedy output) dic[u] = g.D2 return dic
def test_sort_by_efficiency(self): ksf = KnapsackFile("test.txt") lines = ksf.getlines() items = Greedy.create_items(lines) items = Greedy.sort_by_efficiency(items, descending=True) last = 0.0 for i in items: if last is not 0.0: self.assertTrue(i.efficiency < last) last = i.efficiency items = Greedy.sort_by_efficiency(items, descending=False) last = 0.0 for i in items: if last is not 0.0: self.assertTrue(i.efficiency > last) last = i.efficiency
def test_item_creation(self): ksf = KnapsackFile("test.txt") lines = ksf.getlines() items = Greedy.create_items(lines) for i in items: self.assertIsInstance(i, Greedy.Item, "i is Not an Item object") self.assertIsNotNone(i, "Item creation failed.")
def main(): xDB = readJSON('res/xDB.json') bmDir = 'bm/fun' designers = [] designers.append(Greedy.GreedyDesigner(xDB, 'maxHeavy')) # MCDesigner # ... (avgD, minD, maxD) = getXDBStat() # Process all benchmarks for charFile in glob.glob(bmDir + '/*.csv'): with open(charFile, 'r') as file: pts = [[float(n) for n in re.split(', *| *', l.strip())] for l in file.read().split('\n')] spec = {'coms': pts} npts = np.asarray(pts) # Use total length/avgD as heuristic. avgD is average xDB pair distance targetLen = int(np.ceil(sum(np.linalg.norm(npts-np.roll(npts, 1, axis=0), axis=1)) / avgD)) for designer in designers: designerName = designer.__class__.__name__ print 'Benchmarking {} on {}, target length={}'.format( designerName, charFile, targetLen) startTime = time.clock() (nodes,shape,score) = designer.design(spec, targetLen) print "{:.2f}s, score: {}".format(time.clock() - startTime, score) makePdbFromNodes(xDB, nodes, 'res/centered_pdb/pair', charFile.replace('.csv', '_' + designerName + '_FUN.pdb'))
def estado_estadisticas(vista): global campo lim = 2000 carpeta = "IA_80" victorias = [] for i in range(0, lim + 1, 50): print(str(i)) network = import_network(carpeta + "/IA_java_" + str(i) + ".txt") contador_nn = 0 for j in range(200): campo = mdl.Campo() campo.rellenar(mdl.training_2, mdl.training_1) ia_greedy = Greedy.IA("T2", campo, 0.5) ia_nn = IA(network, "T1", campo, 0.5) tiempo = 0 while True: dt = 200 tiempo += dt campo.actualizar(dt / 1000) if campo.revisarDerrota("T1"): break elif campo.revisarDerrota("T2"): contador_nn += 1 break if tiempo > 600000: print("SE METIO EN UN LOOP") break ia_greedy.jugar(dt) ia_nn.jugar(dt) victorias.append(contador_nn) print(str(victorias)) return "menu"
def output_2(self, heu): # fix d datas_greedy = [['ER07', 'ER47', 'SF', 'NSM2', 'NSM10']] datas_R1 = [['ER07', 'ER47', 'SF', 'NSM2', 'NSM10']] datas_R2 = [['ER07', 'ER47', 'SF', 'NSM2', 'NSM10']] d = 10 for rho1 in range(1, 11): for rho2 in range(1, 11): avg_greedy = [0.0, 0.0, 0.0, 0.0, 0.0] avg_R1 = [0.0, 0.0, 0.0, 0.0, 0.0] avg_R2 = [0.0, 0.0, 0.0, 0.0, 0.0] for i in range(0, 5): er07 = self.ER(1000, 0.01) er47 = self.ER(1000, 0.04) sf = self.SF(1000) sm02 = self.SM(2) sm10 = self.SM(10) dic = {0: er07, 1: er47, 2: sf, 3: sm02, 4: sm10} for j in range(0, 5): g = Greedy.Greedy(dic[j], d, rho1, rho2, heu) g.run() avg_greedy[j] += len(g.D1) r1 = Replacement.ReplacementA(dic[j], d, rho1, rho2, heu) r1.run() avg_R1[j] += len(r1.D1) r2 = Replacement.ReplacementB(dic[j], d, rho1, rho2, heu) r2.run() avg_R2[j] += len(r2.D1) print(i) for j in range(0, 5): avg_greedy[j] = avg_greedy[j] / 10 avg_R1[j] = avg_R1[j] / 10 avg_R2[j] = avg_R2[j] / 10 datas_greedy.append(avg_greedy) datas_R1.append(avg_R1) datas_R2.append(avg_R2) with open('2_greedy_' + heu + '.csv', 'w', newline='') as f: writer = csv.writer(f) for row in datas_greedy: writer.writerow(row) with open('2_r1_' + heu + '.csv', 'w', newline='') as f: writer = csv.writer(f) for row in datas_R1: writer.writerow(row) with open('2_r2_' + heu + '.csv', 'w', newline='') as f: writer = csv.writer(f) for row in datas_R2: writer.writerow(row)
def preorderDTLsort(DTL, ParasiteRoot): """This takes in a DTL reconciliation graph and parasite root and returns a sorted list, orderedKeysL, that is ordered by level from largest to smallest, where level 0 is the root and the highest level has tips.""" keysL = Greedy.orderDTL(DTL, ParasiteRoot) uniqueKeysL = Greedy.sortHelper(DTL, keysL) orderedKeysL = [] levelCounter = 0 while len(orderedKeysL) < len(keysL): for mapping in keysL: if mapping[-1] == levelCounter: orderedKeysL = orderedKeysL + [mapping] levelCounter += 1 lastLevel = orderedKeysL[-1][1] return orderedKeysL
def runGreedy(nbmanchots, run, iterations): for i in range(run): tabMachines = creerManchots(nbmanchots) nbiterations2.append(i+1) gains2.append(g.Greedy(iterations, tabMachines)) print(gains2) return nbiterations2, gains2
def preorderDTLsort(DTL, ParasiteRoot): """This takes in a DTL reconciliation graph and parasite root and returns a sorted list, orderedKeysL, that is ordered by level from largest to smallest, where level 0 is the root and the highest level has tips.""" keysL = Greedy.orderDTL(DTL, ParasiteRoot) uniqueKeysL = Greedy.sortHelper(DTL, keysL) orderedKeysL = [] levelCounter = 0 while len(orderedKeysL) < len(keysL): for mapping in keysL: if mapping[-1] == levelCounter: orderedKeysL = orderedKeysL + [mapping] levelCounter += 1 lastLevel = orderedKeysL[-1][1] return orderedKeysL
def run_test(algorithm, dataset): if algorithm == "BruteForce": result = BruteForce.BruteForce(dataset[1]) test_result = TestResult(result[0], dataset[0][0], dataset[0][1], dataset[0][2], dataset[0][3], dataset[0][4], result[3], result[1], 1).get_result() elif algorithm == "BranchNBound": result = BranchNBound.BranchNBound(dataset[1]) test_result = TestResult(result[0], dataset[0][0], dataset[0][1], dataset[0][2], dataset[0][3], dataset[0][4], result[3], result[1], 1).get_result() elif algorithm == "Greedy": #bb_result = BranchNBound.BranchNBound(dataset[1]) result = Greedy.better_greedy(dataset[1]) test_result = TestResult(result[0], dataset[0][0], dataset[0][1], dataset[0][2], dataset[0][3], dataset[0][4], result[3], result[1], result[1]).get_result() elif algorithm == "Randomized": #bb_result = BranchNBound.BranchNBound(dataset[1]) result = Randomized.better_result_of_randomized(dataset[1]) test_result = TestResult(result[0], dataset[0][0], dataset[0][1], dataset[0][2], dataset[0][3], dataset[0][4], result[3], result[1], result[1]).get_result() elif algorithm == "MinSpanTree": #bb_result = BranchNBound.BranchNBound(dataset[1]) result = MinSpanTree.MinSpanTree(dataset[1]) test_result = TestResult(result[0], dataset[0][0], dataset[0][1], dataset[0][2], dataset[0][3], dataset[0][4], result[3], result[1], result[1]).get_result() elif algorithm == "EA_hillclimbing": #bb_result = BranchNBound.BranchNBound(dataset[1]) result = EA_hillclimbing.hillclimbing_algorithm(dataset[1], dataset[0][0]) test_result = TestResult(result[0], dataset[0][0], dataset[0][1], dataset[0][2], dataset[0][3], dataset[0][4], result[3], result[1], result[1]).get_result() elif algorithm == "Genetic": #bb_result = BranchNBound.BranchNBound(dataset[1]) result = GA.genetic_algorithm(dataset[1], dataset[0][0]) test_result = TestResult(result[0], dataset[0][0], dataset[0][1], dataset[0][2], dataset[0][3], dataset[0][4], result[3], result[1], result[1]).get_result() elif algorithm == "TwoOpt": #bb_result = BranchNBound.BranchNBound(dataset[1]) result = TwoOpt.two_opt(dataset[1]) test_result = TestResult(result[0], dataset[0][0], dataset[0][1], dataset[0][2], dataset[0][3], dataset[0][4], result[3], result[1], result[1]).get_result() else: raise Exception("Wrong algorithm chosen!") return test_result
def rootGenerator(DTLReconGraph, parasiteTree): """Generates a list of the roots in a DTL graph""" parasiteRoot = Greedy.findRoot(parasiteTree) preOrder = preorderDTLsort(DTLReconGraph, parasiteRoot) rootList = [] for key in preOrder: if key[1] == 0: rootList.append(key[0]) return rootList
def get_up(CityNum, Dist): """ 函数名:get_up(CityNum,Dist) 函数功能: 通过贪心算法求取目标函数的上界 输入 1 CityNum:城市数量 2 Dist:城市间距离矩阵 输出 1 Path_Up:分支界限法的上界 其他说明:无 """ Path_Up = Greedy.GreedyMethond(CityNum, Dist)[0] return Path_Up
def estadoEntrenamiento(vista): global campo clock = pygame.time.Clock() network = import_network("IA_50_50_50/IA_java_3550.txt") #network = Network(50, [300, 100, 20]) seguir = True contador_greedy = 0 contador_nn = 0 while seguir: campo = mdl.Campo() campo.rellenar(mdl.training_2, mdl.training_1) ia_greedy = Greedy.IA("T2", campo, 0.5) ia_nn = IA(network, "T1", campo, 0.5) vista.setCampo(campo) vista.setJugador(jugador) termino = False while True: dt = 200 #dt=clock.tick(60) for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_SPACE: seguir = False campo.actualizar(dt / 1000) ver = False if ver: vista.dibujarCampoEntrenamiento() pygame.display.flip() if campo.revisarDerrota("T1"): #ia_greedy.escribir_jugadas("jugadas.txt") contador_greedy += 1 termino = True elif campo.revisarDerrota("T2"): #ia_nn.escribir_jugadas("jugadas.txt") contador_nn += 1 termino = True if termino: break ia_greedy.jugar(dt) ia_nn.jugar(dt) #jugadas=ia_greedy.get_jugadas() #ia_nn.entrenar_greedy(jugadas,10,0.0002) #ia_nn.entrenar_jugadas(10,0.0002) #network.export_network("IA_java2.txt") print("greedy: " + str(contador_greedy)) print("nn: " + str(contador_nn)) return "menu"
def pre_process(self) -> dict: # obtain D1 (actually D2 in Greedy output) greedy = Greedy.Greedy(self.G, INF, self.rho1, self.rho1, self.heuristic) greedy.run() self.D1 = greedy.D2 # print(self.D1) # gernerate subgraph for each node in V dic = {} for v in self.G.nodes(): dic[v] = self.cover_nodes(v) return dic
def run_test(fileName, max_k): cache_dir = './cache' D = 2. T = 3. L = 1. host, paras, phi = newickFormatReader.getInput(fileName) if not os.path.exists(cache_dir): os.makedirs(cache_dir) f = open('%s/README' % cache_dir, 'w') f.write( 'This directory holds a cache of reconciliation graph for the TreeLife data set' ) f.close() cache_location = '%s/%s.graph' % (cache_dir, os.path.split(fileName)[1]) if not os.path.isfile(cache_location): print >> sys.stderr, 'A reconciliation graph has not been built yet for this newick file' print >> sys.stderr, 'Doing so now and caching it in {%s}...' % cache_location DictGraph, numRecon = DP.DP(host, paras, phi, D, T, L) f = open(cache_location, 'w+') f.write(repr(DictGraph)) f.close() print >> sys.stderr, 'Loading reonciliation graph from cache' f = open(cache_location) DictGraph = eval(f.read()) f.close() scoresList, dictReps = Greedy.Greedy(DictGraph, paras) print >> sys.stderr, 'Found cluster representatives using point-collecting' graph = ReconGraph.ReconGraph(DictGraph) setReps = [ ReconGraph.dictRecToSetRec(graph, dictRep) for dictRep in dictReps ] random.seed(0) extra_reps = [KMeans.get_template(graph) for i in xrange(max_k)] representatives = setReps + extra_reps print >> sys.stderr, 'Starting K Means algorithm ... ' print >> sys.stderr, 'Printing Average and Maximum cluster radius at each step' for i in xrange(1, max_k + 1): print 'k = %d' % i KMeans.k_means(graph, 10, i, 0, representatives[:i])
def preparaJuego(vista): global campo global jugador global ia global ia2 campo = mdl.Campo() tipoIA = escogerTipoIA() campo.rellenar(tipoJugador, tipoIA) jugador = Jugador.Jugador(campo, tipoJugador) vista.setCampo(campo) vista.setJugador(jugador) ia2 = Greedy.IA(tipoIA.nombre, campo, 0.8) network = import_network("IA_50_50_50/IA_java_3550.txt") ia = IA(network, tipoIA.nombre, campo, 2)
def output_4(self, heu): # fix d datas_greedy = [['Real1']] datas_R1 = [['Real1']] datas_R2 = [['Real1']] d = 10 for rho1 in range (1,11): for rho2 in range(1, 11): avg_greedy = 0.0 avg_R1 = 0.0 avg_R2 = 0.0 for i in range(0, 5): G = self.College() g = Greedy.Greedy(G, d, rho1, rho2, heu) g.run() avg_greedy += len(g.D1) r1 = Replacement.ReplacementA(G, d, rho1, rho2, heu) r1.run() avg_R1 += len(r1.D1) r2 = Replacement.ReplacementB(G, d, rho1, rho2, heu) r2.run() avg_R2 += len(r2.D1) print(i) avg_greedy = avg_greedy / 10 avg_R1 = avg_R1 / 10 avg_R2 = avg_R2 / 10 datas_greedy.append(avg_greedy) datas_R1.append(avg_R1) datas_R2.append(avg_R2) with open('2_greedy_' + heu + '.csv', 'w', newline='') as f: writer = csv.writer(f) for row in datas_greedy: writer.writerow(row) with open('2_r1_' + heu + '.csv', 'w', newline='') as f: writer = csv.writer(f) for row in datas_R1: writer.writerow(row) with open('2_r2_' + heu + '.csv', 'w', newline='') as f: writer = csv.writer(f) for row in datas_R2: writer.writerow(row)
def Reconcile(argList): """Takes command-line arguments of a .newick file, duplication, transfer, and loss costs, the type of scoring desired and possible switch and loss ranges. Creates Files for the host, parasite, and reconciliations""" fileName = argList[1] #.newick file D = float(argList[2]) # Duplication cost T = float(argList[3]) # Transfer cost L = float(argList[4]) # Loss cost freqType = argList[5] # Frequency type # Optional inputs if freqType == xscape switchLo = float(argList[6]) # Switch lower boundary switchHi = float(argList[7]) # Switch upper boundary lossLo = float(argList[8]) # Loss lower boundary lossHi = float(argList[9]) # Loss upper boundary host, paras, phi = newickFormatReader.getInput(fileName) hostRoot = cycleCheckingGraph.findRoot(host) hostv = cycleCheckingGraph.treeFormat(host) Order = orderGraph.date(hostv) # Default scoring function (if freqtype== Frequency scoring) DTLReconGraph, numRecon = DP.DP(host, paras, phi, D, T, L) print DTLReconGraph, numRecon #uses xScape scoring function if freqType == "xscape": DTLReconGraph = calcCostscapeScore.newScoreWrapper(fileName, switchLo, \ switchHi, lossLo, lossHi, D, T, L) #uses Unit scoring function elif freqType == "unit": DTLReconGraph = unitScoreDTL(host, paras, phi, D, T, L) DTLGraph = copy.deepcopy(DTLReconGraph) scoresList, rec = Greedy.Greedy(DTLGraph, paras) for n in range(len(rec)): graph = cycleCheckingGraph.buildReconciliation(host, paras, rec[n]) currentOrder = orderGraph.date(graph) if currentOrder == "timeTravel": rec[n], currentOrder = detectCycles.detectCyclesWrapper( host, paras, rec[n]) currentOrder = orderGraph.date(currentOrder) hostOrder = hOrder(hostv, currentOrder) hostBranchs = branch(hostv, hostOrder) if n == 0: newickToVis.convert(fileName, hostBranchs, n, 1) else: newickToVis.convert(fileName, hostBranchs, n, 0) # filename[:-7] is the file name minus the .newick reconConversion.convert(rec[n], DTLReconGraph, paras, fileName[:-7], n)
def freqSummation(argList): """Takes as input an argument list containing a newick file of host and parasite trees as well as their phi mapping, duplication, transfer, and loss costs, the type of frequency scoring to be used, as well as switch and loss cost ranges for xscape scoring, and returns a file containing the list of scores for each individual reconciliation, the sum of the those scores, the total cost of those reconciliations and the number of reconciliations of those trees.""" newickFile = argList[1] D = float(argList[2]) T = float(argList[3]) L = float(argList[4]) freqType = argList[5] switchLo = float(argList[6]) switchHi = float(argList[7]) lossLo = float(argList[8]) lossHi = float(argList[9]) fileName = newickFile[:-7] f = open(fileName + "freqFile.txt", 'w') host, paras, phi = newickFormatReader.getInput(newickFile) DTL, numRecon = DP.DP(host, paras, phi, D, T, L) if freqType == "Frequency": newDTL = DTL elif freqType == "xscape": newDTL = calcCostscapeScore.newScoreWrapper(newickFile, switchLo, switchHi, lossLo, lossHi, D, T, L) elif freqType == "unit": newDTL = MasterReconciliation.unitScoreDTL(host, paras, phi, D, T, L) scoresList, reconciliation = Greedy.Greedy(newDTL, paras) totalSum = 0 for score in scoresList: totalSum += score for index in reconciliation: totalCost = 0 for key in index: if index[key][0] == "L": totalCost += L elif index[key][0] == "T": totalCost += T elif index[key][0] == "D": totalCost += D f.write(str(scoresList) + '\n') f.write(str(totalSum) + '\n') f.write(str(totalCost) + '\n') f.write(str(numRecon)) f.close()
def SFpp(layout, s_d, rank, n): ub = 100 cont = 0 for r in rank: while True: (s, pos) = search_highest(layout, r, ub, s_d) if layout.sorted_elements[s] > len(layout.stacks[s]) + pos: break #element is sorted c = force_move(layout, s, pos, s_d) ub = r cont += 1 if cont == n: return if r == c: break while cont < n: Greedy.SF_move_d(layout, s_d) cont += 1
def eden(i): bfs = BFS.main("./labyrinths/" + i) print("---") ids = IDS.main("./labyrinths/" + i) print("---") dfs = DFS.main("./labyrinths/" + i) print("---") tss = TSS.main("./labyrinths/" + i) print("---") ast = AStar.main("./labyrinths/" + i) print("---") dijkstra = Dijkstra.main("./labyrinths/" + i) print("---") greedy = Greedy.main("./labyrinths/" + i) print("---") greedyHeuristics = GreedyHeuristics.main("./labyrinths/" + i) print("###########################################################################")
def main(): xDB = readJSON('res/xDB.json') bmDir = 'bm/l10' designers = [] designers.append(Greedy.GreedyDesigner(xDB, 'maxHeavy')) # MCDesigner # ... # Process all benchmarks for jsonFile in glob.glob(bmDir + '/*.json'): spec = readJSON(jsonFile) targetLen = len(spec['nodes']) for designer in designers: designerName = designer.__class__.__name__ inputName = jsonFile.replace('.json', '') print 'Benchmarking {} on {}, target length={}'.format( designerName, inputName, targetLen) startTime = time.clock() (nodes,shape,score,fRot) = designer.design(inputName, spec, targetLen) print "{:.2f}s, score: {}".format(time.clock() - startTime, score) if nodes == spec['nodes']: print 'Pass' else: print 'Failed' pauseCode() makePdbFromNodes(xDB, nodes, 'res/centered_pdb/pair', jsonFile.replace('.json', suffixPdb( designerName, 'PCT', 1.0, targetLen)), fRot)
def preorder_dtl_sort(dtl_recon_graph, parasite_root): """ :param dtl_recon_graph: one of the outputs from DP, directly outputted by buildDTLReconGraph (see top of file for structure of the DTLReconGraph) :param parasite_root: The root node of the parasite tree, represented as a string :return: an ordered list of tuples, in order of increasing level. Each element is of the form ((P, H), L), where P is a parasite node and H is a host node, and the parasite node is mapped onto the host node in the first tuple in the overarching tuple. The second element is the level in the tree at which the (P,H) tuple occurs. Note level 0 is the root and the highest level represents tips. """ keys_l = Greedy.orderDTL(dtl_recon_graph, parasite_root) ordered_keys_l = [ ] # We could marginally improve efficiency here by locking list length, but we don't do that here level_counter = 0 while len(ordered_keys_l) < len(keys_l): to_add = [] for mapping in keys_l: if mapping[-1] == level_counter: to_add += [mapping] ordered_keys_l += to_add level_counter += 1 return ordered_keys_l
def Reconcile(argList): """Takes command-line arguments of a .newick file, duplication, transfer, and loss costs, the type of scoring desired and possible switch and loss ranges. Creates Files for the host, parasite, and reconciliations""" fileName = argList[1] #.newick file D = float(argList[2]) # Duplication cost T = float(argList[3]) # Transfer cost L = float(argList[4]) # Loss cost freqType = argList[5] # Frequency type # Optional inputs if freqType == xscape switchLo = float(argList[6]) # Switch lower boundary switchHi = float(argList[7]) # Switch upper boundary lossLo = float(argList[8]) # Loss lower boundary lossHi = float(argList[9]) # Loss upper boundary host, paras, phi = newickFormatReader.getInput(fileName) hostRoot = ReconciliationGraph.findRoot(host) # Default scoring function (if freqtype== Frequency scoring) DTLReconGraph, numRecon = DP.DP(host, paras, phi, D, T, L) #uses xScape scoring function # if freqType == "xscape": # DTLReconGraph = calcCostscapeScore.newScoreWrapper(fileName, switchLo, \ # switchHi, lossLo, lossHi, D, T, L) #uses Unit scoring function if freqType == "unit": DTLReconGraph = unitScoreDTL(host, paras, phi, D, T, L) DTLGraph = copy.deepcopy(DTLReconGraph) scoresList, recs = Greedy.Greedy(DTLGraph, paras) infeasible_recs = [] for rec in recs: if orderGraph.date(ReconciliationGraph.buildReconciliation(host, paras, rec)) == False: infeasible_recs.append(rec) return infeasible_recs, recs
def reducer(self, key, dataset): config = configparser.ConfigParser() config_file = ops.get_local_path('ConfigFile.ini') config.read(config_file) i = 0 data_set = {} # Prepare the data for the greedy for data in dataset: i += 1 for axe in data: data_set[i] = data[axe] i += 1 medoids = Greedy.greedy(data_set, int(config['DEFAULT']['GREEDY_2'])) # Yield all the medoids for medoid in medoids.values(): data_str = "" for axe in medoid: if data_str == "": data_str = str(axe) else: data_str = data_str + " " + str(axe) yield "", data_str
def main(): xDB = readJSON('res/xDB.json') bmDir = 'bm/l10' designers = [] designers.append(Greedy.GreedyDesigner(xDB, 'maxHeavy')) # MCDesigner # ... # Process all benchmarks for jsonFile in glob.glob(bmDir + '/*.json'): spec = readJSON(jsonFile) # we add one point between each pair of com coms = np.asarray(spec['coms']) targetLen = len(coms) mids = np.asarray([np.mean(p, axis=0) for p in zip(coms, np.roll(coms, -1, axis=0))[0:-1]]) spec['coms'] = np.append([val for p in zip(coms, mids) for val in p], [coms[-1]], axis=0) for designer in designers: designerName = designer.__class__.__name__ print 'Benchmarking {} on {}, target length={}'.format( designerName, jsonFile, targetLen) startTime = time.clock() (nodes,shape,score) = designer.design(spec, targetLen) print "{:.2f}s, score: {}".format(time.clock() - startTime, score) if nodes == spec['nodes']: print 'Pass' else: print 'Failed' # pauseCode() makePdbFromNodes(xDB, nodes, 'res/centered_pdb/pair', jsonFile.replace('.json', '_' + designerName + '_LV2.pdb'))