def neugamma(mgamma, pneu, alpha, beta): mgamma = -mgamma if (0 <= mgamma) and (mgamma < 1e-4): return pneu / (1e-4) + (1 - pneu) * Selection.gamma_dist( -mgamma, alpha, beta) else: return Selection.gamma_dist(-mgamma, alpha, beta) * (1 - pneu)
def main(self, option): overall_bestfit = [] print("Please enter the maximum number of runs:") maxruns = int(input()) print("Please enter desired number of generations: ") gens = int(input()) print("Enter Population size") self.population_size = int(input()) capacity = 30 run_fitnesses = [] best_ind = [] ks_run_values = [] ks_run_weights = [] ks_run_fitness = [] for run in range(int(maxruns)): # print("Run Number %i" % run) generation = self.createPopulation(self.population_size, self.len_of_ind) #print(generation) run_fitnesses.clear() ks_weights, ks_values = self.initKnapSackVals() ks_run_weights += [ks_weights] ks_run_values += [ks_values] ks_final_fitness = [] for gen in range(int(gens)): #print("---------------------------------------------------------------") fitness_values = fit.generation_fitness_func(generation) # KnapSack part of the problem ks_fitness = Knapsack.calc_fitness_dynamic( ks_weights, ks_values, generation, self.population_size, capacity) if option == "tournament": generation = select.tournament_select( generation, self.population_size) if option == "linear": generation = select.linear_rank_select( generation, fitness_values, self.population_size) if option == 'proportionate': generation = select.proportionate_selection( generation, fitness_values, self.population_size) generation = Crossover.random_crossover( generation, self.len_of_ind, self.population_size) generation = self.mutation(generation, self.pm) ks_fitness = Knapsack.calc_fitness_dynamic( ks_weights, ks_values, generation, self.population_size) ks_final_fitness = ks_fitness #print("Knapsack Fitness Values : \n{0}".format(ks_final_fitness)) ks_run_fitness += [ks_final_fitness] print("-----------------------------------") print("Knapsack Capacity is {}".format(capacity)) print("Weights over {} runs".format(maxruns)) for i in range(len(ks_run_weights)): print(ks_run_weights[i]) print("Values over {} runs".format(maxruns)) for i in range(len(ks_run_values)): print(ks_run_values[i]) print("Fitness over {} runs".format(maxruns)) for i in range(len(ks_run_fitness)): print(ks_run_fitness[i])
def permute_methods(runs: int): tour2 = Selection.Tournament(2) tour3 = Selection.Tournament(3) cyclic = Crossover.DictCrossover(Crossover.cyclicCrossover) pmx = Crossover.DictCrossover(Crossover.PMX) selections = [Selection.GoodRoulette, tour2.run, tour3.run] crossovers = [cyclic.run, pmx.run] reinsertions = [Selection.BestsInParentsAndChildren, Selection.Elitism] for select in selections: for crossover in crossovers: for reinsertion in reinsertions: GA.SELECT = select GA.CROSSOVER = crossover GA.REINSERTION = reinsertion logging.info(' METHODS') logging.info('Selection: %s', select.__doc__) logging.info( 'Crossover: %s', ' Cyclic ' if crossover == cyclic.run else ' PMX ') logging.info('Reinsertion: %s', reinsertion.__doc__) before = time.time() parallel_run(GA.StandardGA, runs) after = time.time() logging.info('TIME: %s\n', round(after - before, 2))
def neugamma(mgamma, pneu, pgamma, alpha, beta): mgamma=-mgamma #assume anything with gamma<1e-4 is neutral if (0 <= mgamma) and (mgamma < 1e-4): return pneu/(1e-4) + pgamma*Selection.gamma_dist(-mgamma, alpha, beta) else: return Selection.gamma_dist(-mgamma, alpha, beta) * pgamma
def foldChange(self,groups,mode="g",f=None): if isinstance(groups,str): groups = [groups] values = [] samples = [] peptides = self.peptides if mode == "g": for i in groups: sel = self.selectCols(i) nsel = self.selectCols(i,opposite=True) if f==None: sel = sel.mergeCols() nsel = sel.mergeCols() values.append(sel.values/nsel.values) else: values.append(f(sel.values,nsel.values)) samples.append(i) if mode == "i": for i in groups: sel = self.selectCols(i) nsel = self.selectCols(i,opposite=True) for j,v in enumerate(sel.samples): sel_i = sel[j] # should be 1 column if f==None: nsel = nsel.mergeCols() values.append(sel_i.values/nsel.values) # the values for sample i else: values.append(f(sel_i.values,nsel.values)) samples.append(v) # the sample name for sample i return ChipData(samples,peptides,np.hstack(values))
def main(): """ creates a poly-glycine variant of a pdbfile by removing all sidechains """ parser = OptionParser() parser.add_option("-p", dest="pdbfile", help="pdbfile") parser.add_option("-o", dest="outfile", help="outfile") parser.add_option("-r", dest="replace", help="replace", action="store_true") parser.set_description(main.__doc__) (options, args) = parser.parse_args() if not options.pdbfile or not options.outfile: parser.print_help() sys.exit() selection = Selection() selection.makeSelection("BB") protein = Molecule() protein.readPDB(options.pdbfile) newmol = selection.apply_selection(protein) for chain in newmol.chain: for res in chain.residue: res.name = "GLY" newmol.writePDB(options.outfile)
def test002_CouponCodesProductsOrder(self): Selection.Categories_QP(self,"Air Filter") Selection.SubCategories_options(self,"Air-Filters") FunctionCommon.my_wait_element(self,"//img[@alt=\'View Products\']") self.selenium.click("//img[@alt=\'View Products\']") Selection.Products(self) AddCart.AddCart(self,"1") Selection.couponcode(self,"EN7XQ9WF9HV")
def test001_CouponCodesCatesOrder(self): Selection.Year(self,"2010") Selection.Make(self,"GMC") Selection.Categories_QP(self,"Tonneau Covers") Selection.SubCategories_options(self,"Inverse Snap Tonneau") Selection.Products(self) AddCart.AddCart(self,"1") Selection.couponcode(self,"UE9A62C227T")
def main(): """ reads in a pdbfile and writes out the protein sequence """ parser = OptionParser() parser.add_option("-p", dest="pdbfile", help="pdbfile") parser.add_option("-P", dest="pdblist", help="pdblist") parser.add_option("-t", dest="transpose", help="transpose", action="store_true") parser.add_option("-n", dest="number", help="number", action="store_true") parser.add_option("-r", dest="range", help="range") parser.add_option("-s", dest="selection", help="selection") parser.set_description(main.__doc__) (options, args) = parser.parse_args() pdbfiles = [] if options.pdblist: pdbfiles = files_from_list(options.pdblist) elif options.pdbfile: pdbfiles.append(options.pdbfile) else: parser.print_help() sys.exit() if options.selection: sele = Selection() sele.makeSelection(options.selection) seq_min = 1 seq_max = 1 if options.range: (min, max) = string.split(arg, "-") seq_min = int(min) seq_max = int(max) protein = Molecule() Seq = "" for pdb in pdbfiles: protein.readPDB(pdb) if options.selection: newmol = sele.apply_selection(protein) Seq = newmol.sequence() else: Seq = protein.sequence() if options.range: Seq = Seq[seq_min:seq_max] if options.transpose: for i in range(len(Seq)): print Seq[i] else: print Seq protein.clear()
def main(): """ list the hydrogen bonds in a protein that have a score less than a given threshold """ parser = OptionParser() parser.add_option("-p", dest="pdbfile", help="pdbfile") parser.add_option("-P", dest="pdblist", help="pdblist") parser.add_option("-s", dest="selection", help="selection") parser.add_option("-S", dest="summary", help="summary", action="store_true") parser.add_option("-x", dest="cutoff", help="cutoff", default=-0.3) parser.set_description(main.__doc__) (options, args) = parser.parse_args() pdbfiles = [] if options.pdblist: pdbfiles = files_from_list(options.pdblist) elif options.pdbfile: pdbfiles.append(options.pdbfile) else: parser.print_help() sys.exit() sele = Selection() if options.selection: sele.makeSelection(options.selection) protein = Enzyme() HBN = HBnetwork() for pdbfile in pdbfiles: protein.readPDB(pdbfile) newprot = protein if options.selection: newprot = sele.apply_selection(protein) HBN.createNetwork(newprot) HBN.findHbonds(cutoff=float(options.cutoff)) found = False if options.summary: print pdbfile, len(HBN.hbonds) found = True else: for hb in HBN.hbonds: print pdbfile, hb found = True if not found: print pdbfile, "NONE" protein.clear() HBN.clear()
def main(): """ reports the distance between two selected atoms in a pdbfile """ parser = OptionParser() parser.add_option("-p", dest="pdbfile", help="pdbfile") parser.add_option("-P", dest="pdblist", help="pdblist") parser.add_option("--s1", dest="selection1", help="selection1") parser.add_option("--s2", dest="selection2", help="selection2") parser.set_description(main.__doc__) (options, args) = parser.parse_args() pdbfiles = [] if options.pdblist: pdbfiles = files_from_list(options.pdblist) elif options.pdbfile: pdbfiles.append(options.pdbfile) else: parser.print_help() sys.exit() if not options.selection1 or not options.selection2: parser.print_help() sys.exit() sele1 = Selection() sele2 = Selection() sele1.makeSelection(options.selection1) sele2.makeSelection(options.selection2) protein = Enzyme() for pdbfile in pdbfiles: protein.readPDB(pdbfile) mol1 = sele1.apply_selection(protein) mol2 = sele2.apply_selection(protein) alist1 = mol1.atomList() alist2 = mol2.atomList() if len(alist1) != 1: print "selection 1 does not specify 1 atom" print alist1 sys.exit() if len(alist2) != 1: print "selection 2 does not specify 1 atom" sys.exit() atm1 = alist1[0] atm2 = alist2[0] dist = atm1.distance(atm2) print pdbfile, ":", atm1.name, "->", atm2.name, ":", dist protein.clear()
def main(): """ given a match output file creates an output file of the catalytic site only """ parser = OptionParser() parser.add_option("-p", dest="pdbfile", help="pdbfile") parser.add_option("-o", dest="outfile", help="outfile") parser.set_description(main.__doc__) (options, args) = parser.parse_args() if not options.outfile or not options.pdbfile: parser.print_help() sys.exit() # read remark remark = re.compile("REMARK") try: pdb = open(options.pdbfile) except: print "unable to open pdbfile" sys.exit() resline = "resi=" read = False for line in pdb.readlines(): if remark.match(line): cols = line.split() resi = cols[5] if read: resline += "," resline += resi read = True pdb.close() selection = Selection() selection.makeSelection(resline) # --- extract out the residue selections --- # protein = Molecule() protein.readPDB(options.pdbfile) newmol = selection.apply_selection(protein) selection.clear() # --- extract out the hetero atoms --- # selection.makeSelection("type=HETATM") hetatm = selection.apply_selection(protein) reslist = hetatm.residueList() newchain = newmol.newChain() newchain.addResidueList(reslist) newmol.writePDB("dumb.pdb")
def main(): """ trims a grid for a given selection and cutoff values """ parser = OptionParser() parser.add_option("-p", dest="pdbfile", help="pdbfile") parser.add_option("-s", dest="sele", help="sele") parser.add_option("-g", dest="grid", help="grid") parser.add_option("-o", dest="outfile", help="outfile") parser.add_option("-r", dest="replace", help="replace", action="store_true") parser.add_option("-e", dest="exclude", help="exclude", action="store_true") parser.add_option("-c", dest="cutoff", help="cutoff", default=3.0) (options, args) = parser.parse_args() if not options.pdbfile or not options.grid: parser.print_help() sys.exit() if options.outfile: outgrid = options.outfile elif options.replace: outgrid = options.grid else: parser.print_help() sys.exit() protein = Molecule() protein.readPDB(options.pdbfile) if options.sele: selection = Selection() selection.makeSelection(options.sele) newmol = selection.apply_selection(protein) else: newmol = protein.clone() mygrid = grid() mygrid.read(options.grid) atomlist = newmol.atomList() if options.exclude: gridTrimExclude(mygrid, atomlist, float(options.cutoff)) else: gridTrimInclude(mygrid, atomlist, float(options.cutoff)) mygrid.write(outgrid)
def main(): """ performs a simple clash check (hard spheres) """ parser = OptionParser() parser.add_option("-p", dest="pdbfile", help="pdbfile") parser.add_option("-P", dest="pdblist", help="pdblist") parser.add_option("-s", dest="scale", help="scale (0.60)", default=0.60) parser.add_option("-S", dest="sele", help="selection") parser.set_description(main.__doc__) (options, args) = parser.parse_args() pdbfiles = [] if options.pdbfile: pdbfiles.append(options.pdbfile) elif options.pdblist: pdbfiles = files_from_list(options.pdblist) else: parser.print_help() sys.exit() myscale = float(options.scale) mymol = Enzyme() sele = None if options.sele: sele = Selection() sele.makeSelection(options.sele) for pdbfile in pdbfiles: mymol.readPDB(pdbfile) if options.sele: reslist = sele.apply_selection(mymol).residueList() else: reslist = mymol.residueList() nres = len(reslist) bFail = False for i in range(nres): for j in range(i + 1, nres): if (bResidue_Residue_clash_check(reslist[i], reslist[j], myscale)): print pdbfile, reslist[i].file_id, reslist[ j].file_id, "FAIL" bFail = True break if bFail: break mymol.clear()
def __init__(self, params): self.epochs = params['epochs'] self.Crossover = Crossover(params['crossover_type'], params['crossover_prob']) self.Population = Population(booth_function, params['population_size'], 2, -10, 10, params['population_precision']) self.Mutation = Mutation(params['mutation_type'], params['mutation_prob']) self.Inversion = Inversion(params['inversion_type'], params['inversion_prob']) self.Selection = Selection(params['selection_type'], params['selection_prob']) self.EliteStrategy = EliteStrategy(params['elite_prob'])
def MagTimePlot(Db, Mag0=[], Mag1=[], Year0=[], Year1=[], CompTable=[], OutFile=[]): if not Mag0: Mag0 = min(Db.Extract('MagSize')) if not Mag1: Mag1 = max(Db.Extract('MagSize')) if not Year0: Year0 = min(Db.Extract('Year')) if not Year1: Year1 = max(Db.Extract('Year')) DbS = Sel.MagRangeSelect(Db, Mag0, Mag1, Owrite=0, TopEdge=True) DbS = Sel.TimeSelect(DbS, Year0, Year1, Owrite=0) X = DbS.Extract('Year') Y = DbS.Extract('MagSize') plt.figure(figsize=(7, 4)) plt.plot(X, Y, 'o',markersize=3, color=[0,0,0], markeredgecolor=[0,0,0], markeredgewidth=1.5) # Plot completeness if CompTable: PlotCompTable(CompTable) plt.gca().yaxis.grid(color='0.',linestyle='-') plt.gca().xaxis.grid(color='0.65',linestyle='--') plt.gca().xaxis.set_ticks_position('none') plt.gca().yaxis.set_ticks_position('none') plt.title('Time-Magnitude Distribution', fontsize=14, fontweight='bold') plt.xlabel('Years', fontsize=14, fontweight='bold') plt.ylabel('Magnitude', fontsize=14, fontweight='bold') plt.axis([Year0, Year1, Mag0, Mag1]) # plt.tight_layout() plt.show(block=False) if OutFile: plt.savefig(OutFile, bbox_inches='tight', dpi=150)
def load_specra_and_demog(next_N): demog_loaded = True if (not demog_loaded): demog_params, theta_ns = fit_demog() else: demog_params = numpy.load('popt_' + str(next_N) + '.npy') theta_ns = numpy.load('theta_' + str(next_N) + '.npy') n_people = next_N ns = numpy.array([n_people]) base_pts = int(n_people) pts_l = [base_pts, int(base_pts * 1.2), int(base_pts * 1.4)] gamma_bounds = (1e-5, 500) spectra_loaded = True if (not spectra_loaded): spectra = Selection.spectra(demog_params, ns, two_epoch_sel, pts_l=pts_l, int_bounds=gamma_bounds, Npts=30, echo=True, mp=True) pickle.dump(spectra, open('spectra.pkl', 'wb')) else: spectra = pickle.load(open('spectra.pkl', "rb")) return theta_ns, spectra
def fit_sel_params(next_N, prefix, theta_ns, integrate_fun, loaded_sfs=False, save=False): if (not loaded_sfs): create_sfs_files(next_N, prefix, 4) sel_params_opt = {} sel_params = [0.2, 1000.] lower_bound = [1e-3, 1e-2] upper_bound = [1, 50000.] p0 = dadi.Misc.perturb_params(sel_params, lower_bound=lower_bound, upper_bound=upper_bound) for i in range(4): my_strat = str(i) data = dadi.Spectrum.from_file('sfs/sfs_' + my_strat + '.txt') popt = Selection.optimize_log(p0, data, integrate_fun, Selection.gamma_dist, theta_ns, lower_bound=lower_bound, upper_bound=upper_bound, verbose=len(sel_params), maxiter=30) sel_params_opt[my_strat] = popt[1].tolist() if (save): with open('sel_params_' + str(next_N) + '.json', 'w') as fp: json.dump(sel_params_opt, fp) return sel_params_opt
def find_nearest_neighbors(query, points_list, k=n): distances = [] for i in range(5): for j in range(len(points_list[i])): distances.append( (calculate_manhattan_distance(query, points_list[i][j]), i)) return Selection.select(distances, k)
def main(): """ builds new atoms onto existing pdbfiles. EXPERIMENTAL AND UNTESTED """ parser = OptionParser() parser.add_option("-p", dest="pdbfile", help="pdbfile") parser.add_option("-o", dest="outfile", help="outfile") parser.add_option("--dist", dest="distance", help="distance") parser.add_option("--ang", dest="angle", help="angle") parser.add_option("--tor", dest="torsion", help="torsion") parser.add_option("-s", "--selection", dest="selection", help="selection") parser.add_option("-b", "--build", dest="build", help="build") parser.set_description(main.__doc__) (options, args) = parser.parse_args() if not options.pdbfile or not options.selection: parser.print_help() sys.exit() if not options.outfile: parser.print_help() sys.exit() mol = Molecule() mol.readPDB(options.pdbfile) selector = Selection() selector.makeSelection(options.selection) mysel = selector.apply_selection(mol) builder = Builder() atomlist = mysel.atomList() if len(atomlist) != 3: print "must select three atoms. ", len(atomlist) newatom = Atom() newatom.name = "new" dist = float(options.distance) ang = float(options.angle) tor = float(options.torsion) builder.buildAtom(newatom, atomlist[0], atomlist[1], atomlist[2], dist, ang, tor) mol.chain[0].residue[0].addAtom(newatom) mol.writePDB(options.outfile)
def main(): """ prints a list of unsatisfied hydrogen bonds in a protein """ parser = OptionParser() parser.add_option("-p", dest="pdbfile", help="pdbfile") parser.add_option("-P", dest="pdblist", help="pdblist") parser.add_option("-s", dest="selection", help="selection") parser.set_description(main.__doc__) (options, args) = parser.parse_args() pdbfiles = [] if options.pdblist: pdbfiles = files_from_list(options.pdblist) elif options.pdbfile: pdbfiles.append(options.pdbfile) else: parser.print_help() sys.exit() protein = Molecule() HBN = HBnetwork() sele = None if options.selection: sele = Selection() sele.makeSelection(options.selection) for pdbfile in pdbfiles: protein.readPDB(pdbfile) HBN.createNetwork(protein) HBN.findHbonds() unsat = HBN.unsatisfiedHbonds() if options.selection: atmlist = sele.apply_selection(protein, return_mol=False) for atm in unsat: if atm in atmlist: print atm else: for atm in unsat: print atm protein.clear() HBN.clear()
def test3(): print("Input random(0,{}). Lista di {} elementi.\n".format(amount, amount)) basel = [randint(0, amount) for i in range(amount)] # @UnusedVariable l = list(basel) start = time() res = Selection.sortSelect(l, k) elapsed = time() - start print("sortSelect takes {} seconds. Selected element in position {} is {}".format(elapsed, k, res)) l = list(basel) start = time() res = Selection.heapSelect(l, k) elapsed = time() - start print("heapSelect takes {} seconds. Selected element in position {} is {}".format(elapsed, k, res)) l = list(basel) start = time() res = Selection.quickSelectRand(l, k) elapsed = time() - start print("quickSelectRand takes {} seconds. Selected element in position {} is {}".format(elapsed, k, res)) l = list(basel) minLen = 0 start = time() res = Selection.quickSelectDet(l, k, minLen) elapsed = time() - start print("quickSelectDet (with minLen={}) takes {} seconds. Selected element in position {} is {}".format(minLen, elapsed, k, res)) l = list(basel) minLen = 5 start = time() res = Selection.quickSelectDet(l, k, minLen) elapsed = time() - start print("quickSelectDet (with minLen={}) takes {} seconds. Selected element in position {} is {}".format(minLen, elapsed, k, res)) l = list(basel) minLen = 30 start = time() res = Selection.quickSelectDet(l, k, minLen) elapsed = time() - start print("quickSelectDet (with minLen={}) takes {} seconds. Selected element in position {} is {}".format(minLen, elapsed, k, res)) if trivial: l = list(basel) start = time() res = Selection.trivialSelect(l, k) elapsed = time() - start print("trivialSelect takes {} seconds. Selected element in position {} is {}".format(elapsed, k, res)) print("\nEnd.")
def generatePlayer(cls): """ Desc: Class method, creates a character and fills in parameters with user input when called Input: None Output: Character() instance """ mySelection = Selection() raceObj = mySelection.race_select() classObj = mySelection.class_select() print("What is your name?\n") return cls( input(">> "), # name raceObj, # race choice classObj, # class choice classObj.statsList, # stats raceObj.movesList # moves )
def test2(): print("Input ordinato inversamente. Lista di {} elementi.\n".format(amount)) l = list(range(amount, -1, -1)) start = time() res = Selection.sortSelect(l, k) elapsed = time() - start print("sortSelect takes {} seconds. Selected element in position {} is {}".format(elapsed, k, res)) l = list(range(amount, -1, -1)) start = time() res = Selection.heapSelect(l, k) elapsed = time() - start print("heapSelect takes {} seconds. Selected element in position {} is {}".format(elapsed, k, res)) l = list(range(amount, -1, -1)) start = time() res = Selection.quickSelectRand(l, k) elapsed = time() - start print("quickSelectRand takes {} seconds. Selected element in position {} is {}".format(elapsed, k, res)) l = list(range(amount, -1, -1)) minLen = 0 start = time() res = Selection.quickSelectDet(l, k, minLen) elapsed = time() - start print("quickSelectDet (with minLen={}) takes {} seconds. Selected element in position {} is {}".format(minLen, elapsed, k, res)) l = list(range(amount, -1, -1)) minLen = 15 start = time() res = Selection.quickSelectDet(l, k, minLen) elapsed = time() - start print("quickSelectDet (with minLen={}) takes {} seconds. Selected element in position {} is {}".format(minLen, elapsed, k, res)) l = list(range(amount, -1, -1)) minLen = 30 start = time() res = Selection.quickSelectDet(l, k, minLen) elapsed = time() - start print("quickSelectDet (with minLen={}) takes {} seconds. Selected element in position {} is {}".format(minLen, elapsed, k, res)) if trivial: l = list(range(amount, -1, -1)) start = time() res = Selection.trivialSelect(l, k) elapsed = time() - start print("trivialSelect takes {} seconds. Selected element in position {} is {}".format(elapsed, k, res)) print("\nEnd.")
def GenerateOffspring(parents): offspring = [] while (len(offspring) != len(parents)): parentA, parentB = Selection.Selection(parents) childA, childB = Crossover.Crossover(parentA, parentB) childA = Mutation.Mutation(childA) childB = Mutation.Mutation(childB) offspring.append(childA) offspring.append(childB) return offspring
def test1(): print "Input gia' ordinato. Lista di {} elementi.\n".format(amount) l = range(amount) start = time() res = Selection.sortSelect(l, position) elapsed = time() - start print "sortSelect takes {} seconds. Selected element in position {} is {}".format( elapsed, position, res) l = range(amount) start = time() res = Selection.heapSelect(l, position) elapsed = time() - start print "heapSelect takes {} seconds. Selected element in position {} is {}".format( elapsed, position, res) l = range(amount) start = time() res = Selection.quickSelectRand(l, position) elapsed = time() - start print "quickSelectRand takes {} seconds. Selected element in position {} is {}".format( elapsed, position, res) l = range(amount) minLen = 0 start = time() res = Selection.quickSelectDet(l, position, minLen) elapsed = time() - start print "quickSelectDet (with minLen={}) takes {} seconds. Selected element in position {} is {}".format( minLen, elapsed, position, res) l = range(amount) minLen = 15 start = time() res = Selection.quickSelectDet(l, position, minLen) elapsed = time() - start print "quickSelectDet (with minLen={}) takes {} seconds. Selected element in position {} is {}".format( minLen, elapsed, position, res) l = range(amount) minLen = 30 start = time() res = Selection.quickSelectDet(l, position, minLen) elapsed = time() - start print "quickSelectDet (with minLen={}) takes {} seconds. Selected element in position {} is {}".format( minLen, elapsed, position, res) if trivial: l = range(amount) start = time() res = Selection.trivialSelect(l, position) elapsed = time() - start print "trivialSelect takes {} seconds. Selected element in position {} is {}".format( elapsed, position, res) print "\nEnd."
def test4(): print("Test con input size crescente. Input random(0,{}). Lista di {} elementi.\n".format(amount, amount)) k = int(amount / 2) for i in range(50, 250, 5): random.seed(i) basel = [randint(0, (1 << 32) - 1) for j in range(1000*i)] # @UnusedVariable l = list(basel) start = time() res = Selection.sortSelect(l, k) elapsed = time() - start print('{},{}'.format(1000*i, elapsed))
def main(): """ reports the maximal distance between two sets of atoms """ parser = OptionParser() parser.add_option("-t", dest="target", help="target") parser.add_option("-p", dest="probe", help="probe") parser.add_option("-P", dest="probelist", help="probelist") parser.add_option("-s", dest="selection", help="selection") parser.set_description(main.__doc__) (options, args) = parser.parse_args() if not options.target: parser.print_help() sys.exit() probes = [] if options.probelist: probes = files_from_list(options.probelist) elif options.probe: probes.append(options.probe) else: parser.print_help() sys.exit() target = Molecule() probe = Molecule() target.readPDB(options.target) mysel = None tlist = [] if options.selection: mysel = Selection() mysel.makeSelection(options.selection) target = mysel.apply_selection(target) tlist = target.atomList() nlist = len(tlist) plist = [] for probefile in probes: maxdist = 0.0 probe.readPDB(probefile) if options.selection: probe = mysel.apply_selection(probe) plist = probe.atomList() if len(plist) != nlist: print "differing number of atoms" sys.exit() for i in range(nlist): dist = tlist[i].distance(plist[i]) if dist > maxdist: maxdist = dist print probefile, maxdist probe.clear()
def GetEventRates(Db, CompTable, Area=1.): """ Method to compute observed annual rates (incremental and cumulative) from a given completeness table. In this implementation, completeness is one window per magnitude bin in M. Example: CompTable = [[4.50, 0.25, 2000., 2013.], [4.75, 0.25, 1980., 2013.], [5.00, 0.25, 1970., 2013.], [5.25, 0.25, 1960., 2013.], [5.50, 0.50, 1950., 2013.], [6.00, 1.50, 1901., 2013.]] """ Enum = [] Data = [[],[]] for CT in CompTable: MinM = CT[0] MaxM = CT[0]+CT[1] MinY = CT[2] MaxY = CT[3] # Catalogue selection (Magnitude-Year) DbM = Sel.MagRangeSelect(Db, MinM, MaxM) DbY = Sel.TimeSelect(DbM, MinY, MaxY) # Computing incremental rates RY = float(DbY.Size())/float(MaxY-MinY) Enum.append(RY/float(Area)) # Data per magnitude bin Data[0].append(DbY.Extract(Key='Year')) Data[1].append(DbY.Extract(Key='MagSize')) # Cumulative distribution Ecum = np.cumsum(Enum[::-1])[::-1] return Enum, Ecum, Data
def create_spectra(demog_params, theta, args): ns = np.array([args.samples]) pts_l = [args.samples + 10, args.samples + 20, args.samples + 30] spectra = Selection.spectra(demog_params, ns, develop_then_select, pts_l=pts_l, int_bounds=(1e-5, 50), Npts=500, echo=True, mp=True) theta_ns = theta * args.ratio return spectra, theta_ns
def main(): logging.basicConfig(level=logging.INFO, format='%(message)s') my_log() hits = 0 for i in range(40): CryptoArithmetic.getExpression("send", 9567, "more", 1085, "money", 10652) population = CryptoArithmetic.makeSpecimen(40) population = GA.init(population) best = Selection.getBestSpecimen(population) if best.fitness == CryptoArithmetic.MAX_VALUE: hits += 1 print("\n the GA found the answer {} times in 100!".format(hits))
def test5(): print("Test con k differenti. Input random(0,{}). Lista di {} elementi.\n".format(amount, amount)) basel = [randint(0, 1 << 32) for i in range(amount)] # @UnusedVariable k = int(amount / 2) kNumber = 101 for i in range(1, kNumber): k = int(amount / kNumber) * i - 1 l = list(basel) start = time() res = Selection.quickSelectDet(l, k, 10) elapsed = time() - start print('{},{}'.format(k, elapsed))
def main(): """ program that prints out selections from a pdbfile """ parser = OptionParser() parser.add_option("-p", dest="pdbfile", help="pdbfile") parser.add_option("-s", dest="selection", help="selection") (options, args) = parser.parse_args() if not options.pdbfile or not options.selection: parser.print_help() sys.exit() protein = Molecule() protein.readPDB(options.pdbfile) sele = Selection() sele.makeSelection(options.selection) smol = sele.apply_selection(protein) reslist = smol.residueList() for res in reslist: print res
print("Preparing for the information...") c = CityMap.CityMap(western29) city_map = c.city_map print("preparation end.") gen = 0 print("Initialize population...") init = Initialization.Population(popsize, city_map) init.evalPopulation() print("Initialization end.") while gen < gen_limit: #parent selection #print("parent selection...") parents = Selection.tournament_selection(init.population[1:], mating_pool_size, tournament_size) #print("parent selection end.") CPU_num = multiprocessing.cpu_count() sub_mating_pool_size = int(mating_pool_size/CPU_num) q = multiprocessing.Queue() pro1 = EAProcess(q, parents, city_map, sub_mating_pool_size, mut_rate, xover_rate) pro2 = EAProcess(q, parents, city_map, sub_mating_pool_size, mut_rate, xover_rate) pro3 = EAProcess(q, parents, city_map, sub_mating_pool_size, mut_rate, xover_rate) pro4 = EAProcess(q, parents, city_map, sub_mating_pool_size, mut_rate, xover_rate) pro1.daemon = True pro2.daemon = True pro3.daemon = True
def SmartSearch_Seachbrands(self): Selection.smartsearch("Air Filter")
def SmartSearch_SeachYMMbrands(self): Selection.smartsearch("air filter 2010")
def SmartSearch_SeachYMMCategories(self): Selection.smartsearch("Universal Air Filter Accessories 2009")
def main(): western29 = "Cities/TSP_WesternSahara_29.txt" uruguay734 = "Cities/TSP_Uruguay_734.txt" canada4663 = "Cities/TSP_Canada_4663.txt" popsize = 500 mating_pool_size = 100 tournament_size = 3 mut_rate = 0.2 xover_rate = 0.9 gen_limit = 15 print("Preparing information...") c = CityMap.CityMap(western29 ) city_map = c.city_map print("preparation end.") gen = 0 init = Initialization.Population(popsize, city_map) population = init.population #EA algorithm while gen < gen_limit: #parent selection #print("parent selection...") parents = Selection.tournament_selection(population, mating_pool_size, tournament_size) #print("parent selection end.") offsprings = [] i = 0 while len(offsprings) < mating_pool_size: p1 = parents[i][0] p2 = parents[i + 1][0] #crossover #print("crossover...") if random.random() < xover_rate: off1, off2 = Crossover.COWGC(p1, p2, city_map) else: off1 = copy.copy(p1) off2 = copy.copy(p2) #print("crossover end") #mutation #print("Mutation...") if random.random() < mut_rate: off1 = Mutation.WGWWGM(p1, city_map) if random.random() < mut_rate: off2 = Mutation.WGWWGM(p2, city_map) #print("Mutation end") offsprings.append([off1, off1.fitness]) offsprings.append([off2, off2.fitness]) i += 2 #survial selection #print("survival selection") population = Selection.mu_plus_lambda(population, offsprings) #print("survival selection end") best_fitness = population[0][1] best_tour = population[0][0].tour tour_length = population[0][0].length for i in population: if i[0].length < tour_length: best_fitness = i[1] best_tour = i[0].tour tour_length = i[0].length print("generation: ", gen, " best fitness: ", best_fitness, " length: ", tour_length) gen += 1
def main(): western29 = "Cities/TSP_WesternSahara_29.txt" uruguay734 = "Cities/TSP_Uruguay_734.txt" canada4663 = "Cities/TSP_Canada_4663.txt" popsize = 500 mating_pool_size = 100 tournament_size = 3 mut_rate = 0.2 xover_rate = 0.9 gen_limit = 500 print("Preparing for the information...") c = CityMap.CityMap(uruguay734) city_map = c.city_map print("preparation end.") gen = 0 print("Initialize population...") init = Initialization.Population(popsize, city_map) init.evalPopulation() print("Initialization end.") #EA algorithm while gen < gen_limit: #parent selection #print("parent selection...") parents = Selection.tournament_selection(init.population[1:], mating_pool_size, tournament_size) #print("parent selection end.") offsprings = [] i = 0 while len(offsprings) < mating_pool_size: # 2 parents -> 2 individuals p1 = parents[i] p2 = parents[i + 1] # crossover ################################################################################################ #print("crossover...") if random.random() < xover_rate: #off1, off2 = Crossover.COWGC(p1, p2, city_map) off1, off2 = Crossover.order_crossover(p1, p2, city_map) else: off1 = copy.copy(p1) off2 = copy.copy(p2) #print("crossover end") # mutation ################################################################################################# #print("Mutation...") if random.random() < mut_rate: off1 = Mutation.WGWWGM(p1, city_map) #off1 = Mutation.WGWRGM(p1, city_map) #off1 = Mutation.IRGIBNNM_mutation(p1, city_map) #off1 = Mutation.inversion_mutation(p1, city_map) if random.random() < mut_rate: off2 = Mutation.WGWWGM(p2, city_map) #off2 = Mutation.WGWRGM(p2, city_map) #off2 = Mutation.IRGIBNNM_mutation(p2, city_map) #off2 = Mutation.inversion_mutation(p2, city_map) #print("Mutation end") offsprings.append(off1) offsprings.append(off2) #print(len(offsprings)) i += 2 # survial selection ############################################################################################ #print("survival selection") init.population[1:] = Selection.mu_plus_lambda(init.population[1:], offsprings) #print("survival selection end") init.evalPopulation() print("generation:", gen, " Average length:", init.AverageLength, " Longest length: ", init.worstTour.length, " shortest length:", init.bestTour.length) gen += 1