def init(self, phys, forces, prop): """ Initialize propagator. @type phys: Physical @param phys: The physical system. @type forces: Forces @param forces: MDL Forces object. @type prop: Propagator @param prop: MDL Propagator object. """ prop.calculateForces(forces) self.Potnl = forces.energies.potentialEnergy(phys) #: Potential energy self.gkT = 3.0 * (phys.numAtoms() - 1.0) * Constants.boltzmann( ) * self.temp #: Number of Dof*kT, momentum conserved so number of atoms * 3D - 3 self.KEtoT = 2.0 / (3.0 * (phys.numAtoms() - 1.0) * Constants.boltzmann() ) #: Convertion of kinetic energy to temperature self.Nf = 3.0 * (phys.numAtoms() - 1.0) #: number of Dof self.kT = Constants.boltzmann( ) * self.temp #: Boltzmann constant times Kelvin temperature self.h0 = self.totalEnergy(0, phys, forces) #: Initial total energy self.stepsdone = 0 #: Number of steps completed self.avTemp = 0 #: Average Kelvin temperature self.tempers = [ ] #: Holds pairs of step numbers and average temperatures self.Hamiltonian = [ ] #: Holds pairs of step numbers and total energies
def collisions(self): sprites = copy.copy(Globe.MENU.GAME.boxes) sprites.append(Globe.MENU.GAME.player) explode_list = [] explode = False for sprite in sprites: dist = Constants.distance(self.pos, sprite.pos) if not sprite.state == "drown": if dist < Constants.cscale(60): explode = True if dist < Constants.cscale(108): explode_list.append(sprite) if explode: for sprite in explode_list: if "player" in sprite.tags: sprite.set_drown() Globe.MENU.GAME.reset = True else: sprite.kill = True self.kill = True Globe.MENU.GAME.add_sprite( Animation(-1, 15, {}, (9, 9), 1, Constants.EXPLOSION_IMAGE, Constants.cscale(*sprite.pos), 74)) if self.kill: Globe.MENU.GAME.add_sprite( Animation(-1, 15, {}, (9, 9), 1, Constants.EXPLOSION_IMAGE, Constants.cscale(*self.pos), 74))
def Getkperphitmiss(self,string): # to be used within the string decay class ''' function used to generate a sensible kperp value based on a hit or miss rejection basis ''' ''' Find the suitable range (min - max) of kperp values based on the given string ''' sigma = Constants.kperpsigma() g_sigma = Constants.gsigma() # this value is for g(x) such that g(x) > f(x). If edited, needs to be recalculated (c.f. finding a suitable.... generation) #g_sigma = Constants.kperpsigma() B = 1/(g_sigma*g_sigma) A = Constants.g_kperpA() M = string.Getstringmass() kperpmin = 0 kperpmax = M/2 # where M is the invariant mass of the string decaying # g_kperp = Aexp(-kperp/(gsigma*gsigma) = Aexp(-Bkperp) #numpy.exp(-M*M/(sigma1*sigma1)) - this factor can be omited as it cancels when creating testvalue (its essentially a constant) G_kperp_max = -(A/B)*numpy.exp(-B*kperpmax) G_kperp_min = -(A/B)*numpy.exp(-B*kperpmin) while True: rand_1 = numpy.random.uniform(0,1) #(kperpmin,kperpmax) rand_2 = numpy.random.uniform(0,1) #(kperpmin,kperpmax) kperp_test = -(1/B)*numpy.log(rand_1*(numpy.exp(-kperpmax*B)-1) + 1) # working inverse function #kperp_test = -(1/B)*numpy.log(rand_1*(1-numpy.exp(kperpmax*B)) - 1) # bfroken inverse function #kperp_test = -(1/B)*numpy.log(rand_1 - 1 +numpy.exp(-kperpmax*B)) # dans inverse function f_kperptest = numpy.exp(-kperp_test*kperp_test/(sigma*sigma)) # system designed such that gx is always greater than fx g_kperptest = A*numpy.exp(-B*kperp_test) testvalue = f_kperptest/g_kperptest if rand_2 <= testvalue: return kperp_test break else: continue
def interactive(): result = {} result['battlename'] = read_nonempty("Name for this battle: ") result['player_1_nation'] = Constants.Nation(*read_multiple( "Which nation for player 1? Enter age (EA, MA, LA) " "and name, separated by commas.\nNation: ", 2)) print("Construct your armies.\n" "Enter commander name or ID, then enter all items this " "commander should have, separated by commas.\n" "Finally, enter unit name and quantity separated by comma.\n" "Finish by entering a bare dot.") result['player_1_armies'] = read_repeated("", lambda: read_army("")) print("Do you want a center army?") if read_oneof("(Y/N): ", set("YNyn"), mapper=lambda c: c.upper() == "Y"): print("Construct center armies the same way.\n") result['centerarmies'] = read_repeated("", lambda: read_army("")) print("Do you want a second human player?") if read_oneof("(Y/N): ", set("YNyn"), mapper=lambda c: c.upper() == "Y"): result['player_2_nation'] = Constants.Nation(*read_multiple( "Which nation for player 2? Enter age (EA, MA, LA) " "and name, separated by commas.\nNation: ", 2)) if result['player_2_nation'].age != result['player_1_nation'].age: print("You must select two nations in the same age.") exit(1) result['player2_armies'] = read_repeated("", lambda: read_army("")) return result
def exec_getfield(inst): name_addr = Registers.get_reg(inst['rt']) obj_addr = Registers.get_reg(inst['rs']) while True: try: field = Memory.get_field(obj_addr, name_addr) except Exception as e: Memory.print_obj(obj_addr) Memory.print_obj(name_addr) raise e if not field: # The field cannot be found. ctor_addr = Memory.get_field(obj_addr, Constants.get_str('constructor')) if not ctor_addr: # There is no constructor field new_field = Memory.new_field(Registers.get_reg(inst['rs']), name_addr) Memory.set_prop(new_field, value=Memory.new_obj()) res = Memory.get_prop(new_field) break ctor_obj = Memory.get_prop(ctor_addr)['value'] proto_addr = Memory.get_field(ctor_obj, Constants.get_str('prototype')) if not proto_addr: # There is no prototype field new_field = Memory.new_field(Registers.get_reg(inst['rs']), name_addr) Memory.set_prop(new_field, value=Memory.new_obj()) res = Memory.get_prop(new_field) break obj_addr = Memory.get_prop(proto_addr)['value'] # Find field in the prototype else: res = Memory.get_prop(field) break Registers.set_reg(inst['rd'], res['value']) inc_pc(4) """
def gen_function_expression(ast): assert ast[0] == 'FunctionExpression' label = Labels.function() func, temp = Registers.allocate(2) builder.inst_newfunc(func, label) context['function'].append(func) if ast[2] != '(': # The function has an identifier identifier = gen_identifier(ast[2], True) builder.inst_getvar(temp, identifier) builder.inst_move(temp, func) Registers.free([identifier]) args, t1, t2 = Registers.allocate(3) builder.inst_la(t1, Constants.string('arguments')) builder.inst_getfield(args, func, t1) if ast[-3] != '(': # The function has arguments offset = -16 for node in ast[-3]: if type(node) == list: arg = gen_identifier(node, True) builder.inst_getfield(t1, args, arg) builder.inst_la(t2, Constants.integer(offset)) builder.inst_move(t1, t2) Registers.free([arg]) offset -= 4 Registers.free([t1, t2]) # The function body starts. builder.enter(label) gen_function_body(ast[-1]) builder.exit(label) context['function'].pop() return func
def save_cats_vs_dogs_pictures(train): collection_name = "cats_vs_dogs" import tensorflow_datasets as tfds import cv2 Constants.mkdir("data/" + collection_name) if train: dir = "train" else: dir = "test" data_dir = "data/" + collection_name + "/" + dir Constants.mkdir(data_dir) builder = tfds.builder(collection_name) print(builder.info.splits['train'].num_examples) builder.download_and_prepare() datasets = builder.as_dataset() # If you need NumPy arrays np_datasets = tfds.as_numpy(datasets) my_labels = [] for i in range(Constants.max_count_of_pictures): example = np_datasets[dir].__next__() cv2.imwrite( data_dir + "/" + str(len(my_labels)) + "." + Constants.graph_format, example["image"]) my_labels.append(example["label"]) f = open(data_dir + "/labels", 'wb') f.write(bytes(my_labels)) f.close()
def calculate_metrics(dataset: list, model, print_model_name: str, do_plot=True, save=False, thresholds=None): """ Final metrics to compare different models :param dataset: list of graphs :param model: model :param print_model_name: to print model name :param do_plot: if true it plots roc and other visualizations :return: accuracy, precision, recall, f1 scores """ if save: Constants.set_model_directory(print_model_name) y_true = _get_y_true(dataset) all_predictions = predict_percent(model, dataset, predict_type=None) return print_metrics(y_true, all_predictions, print_model_name, do_plot, save, threshold_dict=thresholds)
def get_comments(request): if request.method == "POST": username = request.POST.get(Constants.getCode("uUsername"), '') postId = request.POST.get(Constants.getCode("uPostId"), '') try: post = Images.objects.get(id=postId) try: comments = Comments.objects.all().filter( imageId=postId).order_by("-ctime") data = [] for comment in comments: item = { Constants.getCode("dCommentId"): comment.id, Constants.getCode("dUsername"): comment.username, Constants.getCode("dText"): comment.comment, Constants.getCode("dTimestamp"): comment.ctime.__str__(), } data.append(item) if (len(data) == 0): return HttpResponse(Constants.getCode("ecode_noComments")) return HttpResponse(json.dumps(data)) except Comments.DoesNotExist as e: return HttpResponse(Constants.getCode("ecode_noComments")) except Images.DoesNotExist as e: return HttpResponse(Constants.getCode("ecode_noSuchPost")) else: return HttpResponse(Constants.getCode("ecode_notPost"))
def save_MNIST_pictures(train, filter): import cv2 if filter: model_name = "MNIST9" else: model_name = "MNIST" Constants.mkdir("data/" + model_name) if train: data_dir = "data/" + model_name + "/Train" pictures = mnist_pictures_train labels = mnist_labels_train else: data_dir = "data/" + model_name + "/Test" pictures = mnist_pictures_test labels = mnist_labels_test Constants.mkdir(data_dir) my_labels = [] for picture in range(pictures.shape[0]): if filter and labels[picture] == 9: continue cv2.imwrite( data_dir + "/" + str(len(my_labels)) + "." + Constants.graph_format, pictures[picture]) my_labels.append(labels[picture]) f = open(data_dir + "/labels", 'wb') f.write(bytes(my_labels)) f.close()
def exec_getvar(inst): func_addr = Memory.read_plain(Registers.read_fp() - 4) rs_val = Registers.get_reg(inst['rs']) while True: arg_field = Memory.get_field(func_addr, Constants.get_str('arguments')) arg_obj = Memory.get_prop(arg_field)['value'] var_field = Memory.get_field(arg_obj, rs_val) if var_field: # The field is found in arguments. offset_addr = Memory.get_prop(var_field)['value'] offset = Memory.get_int(offset_addr) Registers.set_reg(inst['rd'], Memory.read_plain(Registers.read_fp() + offset)) break scope_field = Memory.get_field(func_addr, Constants.get_str('scope')) scope_obj = Memory.get_prop(scope_field)['value'] var_field = Memory.get_field(scope_obj, rs_val) if var_field: # The field is found in scope. var_obj = Memory.get_prop(var_field)['value'] Registers.set_reg(inst['rd'], var_obj) break outer_field = Memory.get_field(func_addr, Constants.get_str('outer')) outer_obj = Memory.get_prop(outer_field)['value'] if not outer_obj: # The field 'outer' is empty. func_addr = Memory.read_plain(Registers.read_fp() - 4) scope_field = Memory.get_field(func_addr, Constants.get_str('scope')) scope_obj = Memory.get_prop(scope_field)['value'] prop_addr = Memory.new_field(scope_obj, rs_val) obj_addr = Memory.new_obj() Memory.set_prop(prop_addr, value=obj_addr) Registers.set_reg(inst['rd'], obj_addr) break else: func_addr = outer_obj inc_pc(4)
def run(self, phys, forces, prop): """ Execute the propagator. @type phys: Physical @param phys: The physical system. @type forces: Forces @param forces: MDL Forces object @type prop: Propagator @param prop: MDL Propagator object """ forceconstant = 2 * Constants.boltzmann( ) * self.temp * self.gamma / self.dt # assign random force forces.force += forces.randomForce(phys, self.seed) * numpy.sqrt( forceconstant * phys.masses) phys.velocities *= (1.0 - 0.5 * self.dt * self.gamma ) # first half kick phys.velocities += forces.force * 0.5 * self.dt * phys.invmasses phys.positions += phys.velocities * self.dt # drift prop.calculateForces(forces) forceconstant = 2 * Constants.boltzmann( ) * self.temp * self.gamma / self.dt # assign random force forces.force += forces.randomForce(phys, self.seed) * numpy.sqrt( forceconstant * phys.masses) phys.velocities += forces.force * 0.5 * self.dt * phys.invmasses # second first kick phys.velocities *= (1.0 / (1.0 + 0.5 * self.dt * self.gamma))
def exec_cmp(inst): rs_obj = Memory.get_obj(Registers.get_reg(inst['rs'])) rt_obj = Memory.get_obj(Registers.get_reg(inst['rt'])) if rs_obj['type'] == rt_obj['type'] and rs_obj['data'] == rt_obj['data']: Registers.set_reg(inst['rd'], Constants.get_int(1)) else: Registers.set_reg(inst['rd'], Constants.get_int(0)) inc_pc(4)
def convert_units(config): result = [] for army in config: units = [] for (name_or_id, count) in army['units'].items(): units.append(Constants.Unit(name_or_id, count)) result.append(Constants.Army(army['commander'], army['items'], units)) return result
def exec_newfunc(inst): func_addr = Memory.new_func() address_prop = Memory.get_field(func_addr, Constants.get_str('address')) Memory.set_prop(address_prop, value=Memory.new_int(Labels.query(inst['label']))) outer_func = Memory.read_plain(Registers.read_fp() - 4) outer_prop = Memory.get_field(func_addr, Constants.get_str('outer')) Memory.set_prop(outer_prop, value=outer_func) Registers.set_reg(inst['rd'], func_addr) inc_pc(4)
def award_to_display(award) -> str: itemname = Constants.item_name(award.name.strip()) or '' if award.data_type == 4: icon = itemname+'Icon' else: icon = Constants.item_filename(itemname) or award.icon or award.data_id rarity = Constants.RARITY_NAME_ITEM[award.rarity] name = str(award.amount)+'x '+itemname return simple_template('Display', [str(icon), rarity, name])
def get_settings(): settings_q = [{ 'type': 'list', 'name': 'follow_status', 'message': 'Which functions would you like to run?', 'choices': ['Follow & Unfollow', 'Follow only', 'Unfollow only'] }, { 'type': 'input', 'name': 'days_to_unfollow', 'message': 'Days to unfollow:', 'default': '3', 'validate': NumberValidator }, { 'type': 'input', 'name': 'likes_max', 'message': 'Max number of likes per post to follow and like:', 'default': '150', 'validate': NumberValidator }, { 'type': 'input', 'name': 'check_followers_every', 'message': 'Follow & like every (minutes):', 'default': '10', 'validate': NumberValidator }, { 'type': 'input', 'name': 'run_for', 'message': 'Run for (minutes):', 'default': '60', 'validate': NumberValidator }, { 'type': 'input', 'name': 'hashtag_num', 'message': 'How many hashtags would you like to follow & like?', 'default': '4', 'validate': NumberValidator }] answers = prompt(settings_q) hashtag_list = [] for i in range(int(answers['hashtag_num'])): new_hashtag = generate_hashtag_list() hashtag_list.append(new_hashtag) # assign values Constants.RUN_MODE = 2 if answers[ 'follow_status'] == 'Follow & Unfollow' else 1 if answers[ 'follow_status'] == 'Follow only' else 0 Constants.DAYS_TO_UNFOLLOW = int(answers['days_to_unfollow']) Constants.LIKES_LIMIT = int(answers['likes_max']) Constants.CHECK_FOLLOWERS_EVERY = int(answers['check_followers_every']) Constants.RUN_DURATION = int(answers['run_for']) Constants.HASHTAGS = hashtag_list Constants.update_settings_file()
def read_army(prompt, mapper=None, quit="."): commander_type = read_nonempty("Commander name/ID: ", quit=quit) items = read_list("Items: ", quit=quit) units = read_repeated("Units\n", make_multiple_reader("Unit name/ID, quantity: ", 2, [None, int], quit=quit), quit=quit, mapper=lambda x: Constants.Unit(*x)) return Constants.Army(commander_type, items, units)
def Fixlowenergy(lop): # If gluon has too small an energy that it cannot be fed into PyLund after decaying, its absorbed into its neighbours. maxqmass = 0.6 # mass of the ud diquark pair WAS no_parts = len(lop) finished = False while True: if finished == True: #print "final number of particles", len(lop) return lop break no_parts = len(lop) #rint no_parts, "number particles" # go over the list. combine the low energy gluons absorbed into their neighbours. for i in range(no_parts): #print i, "i nubmer" if lop[i].Checkgluon() == True: vec_g = copy.deepcopy(lop[i].Getvector4D()) vecleft = copy.deepcopy(lop[i-1].Getvector4D()) vecright = copy.deepcopy(lop[i+1].Getvector4D()) testleft = numpy.sqrt((vec_g + vecleft) * (vec_g + vecleft)) # invariant mass of the gluon and the partner on the left testright = numpy.sqrt((vec_g + vecright) * (vec_g + vecright)) # invariant mass of the gluon and the partner on the right Eg = vec_g.Getvector()[0] x = Constants.gmm() * maxqmass / Eg #print testleft, "testleft" #print testright, "testright" #print vec_g, "vec g into the code" if 1 < x: newgluons = Absorbgluons(lop[i-1],lop[i],lop[i+1]) lop[i-1] = newgluons[0] lop[i+1] = newgluons[1] lop.pop(i) # remove the quark from the list. then need to go back to start of while to get the newest len (as it has changed) #print "list popped, check if we go back to start" break if testleft < (Constants.gcc()*maxqmass): # inv mass with left too small. GEt absorbed into neighbours newgluons = Absorbgluons(lop[i-1],lop[i],lop[i+1]) lop[i-1] = newgluons[0] lop[i+1] = newgluons[1] lop.pop(i) # remove the quark from the list. then need to go back to start of while to get the newest len (as it has changed) #print "list popped, check if we go back to start" break if testright < (Constants.gcc()*maxqmass): # inv mass with the right too small. Get absorbed into neighbours newgluons = Absorbgluons(lop[i-1],lop[i],lop[i+1]) lop[i-1] = newgluons[0] lop[i+1] = newgluons[1] lop.pop(i) # remove the quark from the list. then need to go back to start of while to get the newest len (as it has changed) #print "list popped, check if we go back to start" break else: # inv mass with neightbours is high enough. move to next gluon. pass # get to this point once finished the lot? if i == (no_parts-1): finished = True
def impulse(phys, forces, io, steps, cyclelength, fg, nextinteg, *args): """ Verlet/r-RESPA propagation method. Implements the multiple-timestepping Verlet/r-RESPA method, also known as Impulse. This propagator invokes an 'inner' propagator for a specific number of cycles per iteration, then computes its own forces. cf. H. Grubmuller, H. Heller, A. Windemuth and K. Schulten. Generalized Verlet Algorithm for Efficient Molecular Dyanmics Simulatiosn with Long-Range Interactions. Molecular Simulation, vol. 6, pages 121-142, 1991. @type phys: Physical @param phys: The physical system. @type forces: Forces @param forces: MDL Forces object. @type io: IO @param io: MDL IO object. @type steps: int @param steps: Number of steps to run. @type cyclelength: float @param cyclelength: Number of iterations of inner method. @type fg: ForceField @param fg: MDL force field for evaluation. @type nextinteg: function handle @param nextinteg: Method handle for next propagator in the chain @type args: tuple @param args: Parameters for the next propagator in the chain """ # Calculate initial forces step = 0 # For all steps timestep = cyclelength * args[0] args2 = (args[0] * Constants.invTimeFactor(), ) + args[1:len(args)] while (step < steps): # Update velocities by half a step phys.velocities += forces.force * 0.5 * timestep * phys.invmasses # half kick # Run the next integrator in the chain, and store its results # in an array nextinteg(phys, forces, io, cyclelength / Constants.invTimeFactor(), *args2) # Calculate new forces fg.calculateForces(phys, forces) # Update velocities by another half step phys.velocities += forces.force * 0.5 * timestep * phys.invmasses # half kick step = step + 1
def impulse(phys, forces, io, steps, cyclelength, fg, nextinteg, *args): """ Verlet/r-RESPA propagation method. Implements the multiple-timestepping Verlet/r-RESPA method, also known as Impulse. This propagator invokes an 'inner' propagator for a specific number of cycles per iteration, then computes its own forces. cf. H. Grubmuller, H. Heller, A. Windemuth and K. Schulten. Generalized Verlet Algorithm for Efficient Molecular Dyanmics Simulatiosn with Long-Range Interactions. Molecular Simulation, vol. 6, pages 121-142, 1991. @type phys: Physical @param phys: The physical system. @type forces: Forces @param forces: MDL Forces object. @type io: IO @param io: MDL IO object. @type steps: int @param steps: Number of steps to run. @type cyclelength: float @param cyclelength: Number of iterations of inner method. @type fg: ForceField @param fg: MDL force field for evaluation. @type nextinteg: function handle @param nextinteg: Method handle for next propagator in the chain @type args: tuple @param args: Parameters for the next propagator in the chain """ # Calculate initial forces step = 0 # For all steps timestep = cyclelength*args[0] args2 = (args[0]*Constants.invTimeFactor(),)+args[1:len(args)] while (step < steps): # Update velocities by half a step phys.velocities += forces.force*0.5*timestep*phys.invmasses # half kick # Run the next integrator in the chain, and store its results # in an array nextinteg(phys, forces, io, cyclelength/Constants.invTimeFactor(), *args2) # Calculate new forces fg.calculateForces(phys, forces) # Update velocities by another half step phys.velocities += forces.force*0.5*timestep*phys.invmasses # half kick step = step + 1
def bbk(phys, forces, io, steps, timestep, fg, temp, gamma, seed): """ Brunger-Brooks-Karplus propagation method. cf. A. Brunger, C. B. Brooks and M. Karplus. Stochastic Boundary Conditions for Molecular Dynamics Simulations of ST2 Water. Chem. Phys. Lett, v. 105, pages 495-500, 1982. Single timestepping. @type phys: Physical @param phys: The physical system. @type forces: Forces @param forces: MDL Forces object. @type io: IO @param io: MDL IO object. @type steps: int @param steps: Number of steps to run. @type timestep: float @param timestep: Timestep for propagation. @type fg: ForceField @param fg: MDL force field for evaluation. @type temp: float @param temp: Kelvin temperature. @type gamma: float @param gamma: Friction constant in Langevin dynamics. @type seed: int @param seed: Random number seed """ gamma = gamma * 0.001 / Constants.invTimeFactor() #fg.calculateForces(phys, forces) step = 0 while (step < steps): forceconstant = 2 * Constants.boltzmann( ) * temp * gamma / timestep # assign random force forces.force += forces.randomForce(phys, seed) * numpy.sqrt( forceconstant * phys.masses) phys.velocities *= (1.0 - 0.5 * timestep * gamma) # first half kick phys.velocities += forces.force * 0.5 * timestep * phys.invmasses phys.positions += phys.velocities * timestep # drift fg.calculateForces(phys, forces) forceconstant = 2 * Constants.boltzmann( ) * temp * gamma / timestep # assign random force forces.force += forces.randomForce(phys, seed) * numpy.sqrt( forceconstant * phys.masses) phys.velocities += forces.force * 0.5 * timestep * phys.invmasses # second first kick phys.velocities *= (1.0 / (1.0 + 0.5 * timestep * gamma)) step = step + 1
def animate(self, screen, update_lock): # Draw Shadow screen.blit( Constants.BALL_SHADOW_IMAGE, Constants.BALL_SHADOW_IMAGE.get_rect( center=Constants.cscale(self.pos[0] + 10, self.pos[1] + 22))) current_index = int((self.time % 24) // 6) screen.blit(self.current_image[current_index], self.image.get_rect(center=Constants.cscale(*self.pos))) if not update_lock: self.time += 0.95
def exec_slt(inst): rs_obj = Memory.get_obj(Registers.get_reg(inst['rs'])) rt_obj = Memory.get_obj(Registers.get_reg(inst['rt'])) if (rs_obj['type'] == 0 and rt_obj['type'] == 0) or \ (rs_obj['type'] == 2 and rt_obj['type'] == 2): if rs_obj['data'] < rt_obj['data']: Registers.set_reg(inst['rd'], Constants.get_int(1)) else: Registers.set_reg(inst['rd'], Constants.get_int(0)) else: raise Exception('The following object are not comparable yet.\n' + '%s\n%s' % (str(rs_obj), str(rt_obj))) inc_pc(4)
def __init__(self): if Constants.DATABASE_PATH == '': # if no path is specified, save in the same file Constants.DATABASE_PATH = os.getcwd( ) + '/' + Constants.INST_USER + '.csv' try: if not os.path.isfile(Constants.DATABASE_PATH): headers = ['username', 'date'] with open(Constants.DATABASE_PATH, 'a+') as f: writer = csv.writer(f) writer.writerow(headers) Constants.update_settings_file() # save into the settings file except OSError: # to handle error when file exists and cannot be accessed pass
def follow_request(request): if request.method == "POST": username = request.POST.get(Constants.getCode("uUsername"), '') followee = request.POST.get(Constants.getCode("uFollowee"), '') if username == followee: return HttpResponse(Constants.getCode("ecode_noSelfFollow")) try: user = User.objects.get(username=followee) try: row = Follows.objects.get(follower=username, followee=followee) return HttpResponse(Constants.getCode("ecode_alreadyFollow")) except Follows.DoesNotExist: if user.privacy == "private": reqstatus = "requested" else: reqstatus = "accepted" followRow = Follows(follower=username, followee=followee, fstatus=reqstatus) followRow.save() if not followRow: return HttpResponse( Constants.getCode("ecode_unableFollow")) else: return HttpResponse(Constants.getCode("OK")) except User.DoesNotExist as e: return HttpResponse(Constants.getCode("ecode_noSuchUser")) else: return HttpResponse(Constants.getCode("ecode_notPost"))
def get_followers_list(request): if request.method == "POST": username = request.POST.get(Constants.getCode("uUsername"), '') profileId = request.POST.get(Constants.getCode("uProfileId"), '') try: user = User.objects.get(username=profileId) rows = Follows.objects.all().filter(followee=profileId) followerlist = [] if username == profileId: for row in rows: item = { Constants.getCode("dFollower"): row.follower, Constants.getCode("dFollowStatus"): row.fstatus, } followerlist.append(item) else: for row in rows: item = { Constants.getCode("dFollower"): row.follower, } followerlist.append(item) if (len(followerlist) == 0): return HttpResponse(Constants.getCode("ecode_noFollowers")) else: return HttpResponse(json.dumps(followerlist)) except User.DoesNotExist as e: return HttpResponse(Constants.getCode("ecode_noSuchUser")) else: return HttpResponse(Constants.getCode("ecode_notPost"))
def majority_model_metrics(dataset: list, do_plot=True, save=False): model_name = 'majority_classifier' if save: Constants.set_model_directory(model_name) y_true = dataset[0].ndata[LABEL_NODE_NAME].cpu() for graph in dataset[1:]: y_true = torch.cat((y_true, graph.ndata[LABEL_NODE_NAME].cpu()), dim=0) y_true = y_true.cpu() y_pred = torch.zeros_like(y_true) all_predictions = { 'y_pred': y_pred, } print_metrics(y_true, all_predictions, model_name, do_plot, save)
def gen_literal(ast): assert ast[0] == 'Literal' if type(ast[1]) == int: label = Constants.integer(ast[1]) rd = Registers.allocate(1)[0] builder.inst_la(rd, label) return rd elif type(ast[1]) == str: return gen_string_literal(ast[1]) elif type(ast[1]) == bool: label = Constants.integer(1 if ast[1] else 0) rd = Registers.allocate(1)[0] builder.inst_la(rd, label) return rd
def main(): print('Welcome to InstaBot') # first time user if not Constants.INST_USER: get_username_pass() get_chrome_driver_path() # some username is already saved else: if settup_account() == 'Yes': get_username_pass() get_chrome_driver_path() change_settings() change_developer_mode() Constants.update_settings_file()
def remove_comment(request): if request.method == "POST": username = request.POST.get(Constants.getCode("uUsername"), '') postId = request.POST.get(Constants.getCode("uPostId"), '') commentId = request.POST.get(Constants.getCode("uCommentId"), '') try: post = Images.objects.get(id=postId) try: comment = Comments.objects.get(id=commentId) # check if comment is 10 minutes (or maxDeletePeriod) of age. commentTime = comment.ctime currentTime = datetime.now() difference = currentTime - commentTime if (difference.seconds > maxDeletePeriodinSeconds): return HttpResponse(Constants.getCode("ecode_tooLate")) comment.delete() return HttpResponse(Constants.getCode("OK")) except Comments.DoesNotExist as e: return HttpResponse(Constants.getCode("ecode_noSuchComment")) except Images.DoesNotExist as e: return HttpResponse(Constants.getCode("ecode_noSuchPost")) else: return HttpResponse(Constants.getCode("ecode_notPost"))
def image_upload(request): if request.method == "POST": username = request.POST.get(Constants.getCode("uUsername"), '') count = Images.objects.filter(owner=username).count() cur_date = datetime.today().strftime(Constants.format_date) filepath = username + "_" + str(cur_date) + "_" + str(count) b64 = request.POST.get(Constants.getCode("uImage"), 'nil') #handle null image desc = request.POST.get(Constants.getCode("uDescription"), "") Functions.saveImage_b64(filename=filepath, b64=b64) #check if saving was successful. handle cases try: i = Images(path=filepath, desc=desc, owner=username) i.save() retval = { Constants.getCode("dStatus"): Constants.getCode("OK"), Constants.getCode("dId"): i.id } Functions.generateThumbnail(filepath) return HttpResponse(json.dumps(retval)) except IntegrityError as e: return HttpResponse(Constants.getCode("ecode_imageExists")) else: return HttpResponse(Constants.getCode("ecode_notPost"))
def new_func(): func_addr = alloc(8) prop_addr = alloc(60) write(func_addr, {'type': 1, 'object': {'type': 4, 'data': prop_addr}, 'content': 4}) write(func_addr + 4, {'type': 0, 'content': prop_addr}) for index, name in enumerate(['address', 'prototype', 'scope', 'outer', 'arguments']): next_addr = prop_addr + 12 if index < 4 else 0 value = new_obj() if name in ['scope', 'arguments', 'prototype'] else 0 write(prop_addr, {'type': 3, 'property': {'key': Constants.get_str(name), 'value': value, 'ptr': next_addr}, 'content': Constants.get_str(name)}) write(prop_addr + 4, {'type': 0, 'content': value}) write(prop_addr + 8, {'type': 0, 'content': next_addr}) prop_addr = next_addr return func_addr
def Decayparticlelist(self,particlelist): stableparticles = [] templist = particlelist # use a psudeo third list to get around pythons inability to edits lists that its iterating over. c = Constants.speedoflight() unstableparticles = particlelist # guilty until proven innocent! twobodyclass = Twobodydecay.twobodydecay4D() numberdecays = 1 # if a particle decays and forms products - then the products may decay further. this counter tells whether to keep looping or not. while numberdecays != 0: particlelist = templist templist = [] # reinitialise the templist to contain the next set of prodcut numberdecays = 0 # set to zero. if different that means that somethihng has decayed for i in range(len(particlelist)): self.Checkforkaons(particlelist[i]) particlecode = particlelist[i].Getcode() print particlecode, "PARTICLECODE" if abs(particlecode) <= 100: stableparticles.append(particlelist[i]) continue particlelifetime = particlelist[i].Getlifetime() Time = Radioactivedecay.radioactivedecay4D(particlelifetime) distance = Time * c #print distance, "Distacne" if distance >= Constants.detector_limit(): #check particle stability. if the particle gets past the detector 10CM, LIMIT, then it doesnt decay. add it to the final list. stableparticles.append(particlelist[i]) continue ''' If the particle decays quick enough, it will create some products. Kinematics held using standard 2/3 body decayers ''' particledecayproducts = self.Choosehadrondecay(particlecode) # choose one of the decay routes for the unstable particle decayedproductlist = self.Performhadrondecay(particlelist[i],particledecayproducts) templist += decayedproductlist numberdecays += 1 return stableparticles
def game_avail_info(self, auth): """ Return game state including objects of player with given auth code. @type auth: string @param auth: authCode of the player making the requests. """ alive_players = [] for player in self.players.itervalues(): if player.alive: alive_players.append(player.name) player = self.get_player_by_auth(auth) if player == None: return {'success':False, 'message':'bad auth'} return { 'game_active': self.active, 'turn':self.turn, 'constants':Constants.to_dict(), 'you': id(player), 'resources': player.resources, 'score':player.score, 'alive_players': alive_players, 'objects': [object.to_dict() for object in\ player.objects.itervalues()], }
def exec_jalr(inst): Memory.write_plain(Registers.read_fp(), read_pc()) # set return address func_obj = Memory.get_obj(Registers.get_reg(inst['rd'])) if func_obj['type'] == 7: # panel.readInt() num = int(raw_input('Please enter an integer.\n')) num_addr = Memory.new_int(num) Memory.write_plain(Registers.read_fp() - 12, num_addr) inc_pc(4) elif func_obj['type'] == 8: # panel.readStr() string = raw_input('Please enter an string.\n') str_addr = Memory.new_str(string) Memory.write_plain(Registers.read_fp() - 12, str_addr) inc_pc(4) elif func_obj['type'] == 9: # panel.show() arg = Memory.read_plain(Registers.read_fp() - 16) Memory.print_obj(arg) inc_pc(4) else: assert func_obj['type'] == 4 func_addr = Registers.get_reg(inst['rd']) address_field = Memory.get_field(func_addr, Constants.get_str('address')) address_addr = Memory.get_prop(address_field)['value'] address = Memory.get_int(address_addr) Memory.write_plain(Registers.read_fp(), read_pc() + 4) write_pc(address)
def run(self): self.train() speciesFolders = cleanHiddenFiles(getFolderContents(self.path)) for speciesName in speciesFolders: speciesFolder = getPath(self.path, speciesName) #folder for 1 species if os.path.isdir(speciesFolder): images = cleanHiddenFiles(getFolderContents(speciesFolder)) for imageName in images: try: name = getPath(speciesFolder, imageName) img = loadImage(name) start = time.time() #a mobile phone would request to process the image and get the species list speciesImage = LeafImage(inputImg=img, disks=self.disks, circumferences=self.circumferences) neighbours1, dist1 = self.runKnn(self.knn1, speciesImage.getHistogram(C.HIST_HCoS)) neighbours2, dist2 = self.runKnn(self.knn2, speciesImage.getHistogram(C.HIST_LBP_R1P8_R3P16_CONCAT)) histPath = C.matchHistToName(C.HIST_HCoS) expectedLabel = Label(speciesName, histPath, speciesFolder) kResults = self.getTopK(neighbours1, dist1, neighbours2, dist2, self.maxk, expectedLabel) end = time.time() elapsed = end - start self.log.write(name + "\t" + str(elapsed)) aux = self.parseResults(kResults) + "\n" print(name + "\t" + str(elapsed)) except Exception as e: print(e) self.log.toDisk("/Users/maeotaku/Documents/time_results_noisy.txt")
def getPRMLadder(seq, startMass, ambigAA='X', ambigEdges=None, epsilon=1, addEnds=True, considerTerminalMods=True): nodeGen = Constants.nodeInfoGen(seq, startMass=startMass, addTerminalNodes=addEnds, considerTerminalMods=considerTerminalMods) seqIndex = 1 PRMLadder = [] while True: try: node = nodeGen.next() PRMLadder.extend([node['prm']]) except KeyError: if seq[seqIndex - 1] == ambigAA: edge = ambigEdges[0] ambigEdges = ambigEdges[1:] if np.abs(edge[0] - (PRMLadder[-1] if len(PRMLadder) > 0 else startMass)) < epsilon: PRMLadder.extend([edge[1]]) PRMLadder.extend(getPRMLadder(seq=seq[seqIndex:], startMass=edge[1], ambigAA=ambigAA, ambigEdges=ambigEdges, epsilon=epsilon, addEnds=False)) break else: print 'ERROR: Ambiguous edges do not correspond to ambiguous regions of sequence for PRM =', PRMLadder[-1] if len(PRMLadder) > 0 else startMass, 'and ambiguous edges', edge return False else: raise ValueError('Unknown amino acid found %s' % node['lattAA']) except StopIteration: break return PRMLadder
def getPRMLadder(seq, ambigAA='X', addEnds=True, ambigEdges=None): prmLadder = [] nodeGen = Constants.nodeInfoGen(seq, considerTerminalMods=True, addTerminalNodes=addEnds, ambigEdges=ambigEdges, ambigAA=ambigAA) for node in nodeGen: prmLadder.extend([node['prm']]) return prmLadder
def metropolis( self, new, curr, phys ): """ Metropolis function which computes an acceptance probability for sets of positions depending on energy change dE. P = e^-dE/kt @type new: float @param new: Hypothetical new energy with flip. @type curr: float @param curr: Current energy. @type phys: Physical @param phys: The physical system. @rtype: int @return: 0 for reject, 1 for accept """ deltaE = new - curr if( deltaE < 0 ): return 1 acceptProb = exp( -deltaE / ( Constants.boltzmann() * phys.getTemperature() ) ) randNum = random() if( randNum < acceptProb ): print "\n**** Move accepted\n" return 1 else: print "\n**** Move rejected\n" return 0
def use(self, pokemonA, pokemonT): damage = Constants.calcDamage(self.hit_chance, self.amount, pokemonA, pokemonT, False, True); if damage < 0: damage = 1; print "%s used %s." % (pokemonA.name, self.name); pokemonT.health = pokemonT.health - damage;
def gen_identifier(ast, as_literal=False): assert ast[0] == 'Identifier' ret = Registers.allocate(1)[0] builder.inst_la(ret, Constants.string(ast[1])) if not as_literal: builder.inst_getvar(ret, ret) # TODO: getvar/findvar? return ret
def getAllAAs(seq, ambigAA='X', ambigEdges=None): AAs = [] nodeGen = Constants.nodeInfoGen(seq, considerTerminalMods=True, ambigEdges=ambigEdges) for node in nodeGen: AAs.extend([node['formAA']]) AAs.extend([node['lattAA']]) return AAs
def load_data(data): addr = 0x10000000 line = 0 while line < len(data): label = data[line].strip().split(':')[0] Labels.add(label, addr) if label.startswith('int_'): value = int(re.match(r'\s+\.word\s+(-?\w+)', data[line+2]).group(1), 16) Memory.set_int(addr, value) Constants.set_int(value, addr) addr += 8 line += 3 elif label.startswith('str_'): string = re.match(r'\s+\.asciiz\s+"([^"]+)"', data[line+3]).group(1) string = string.decode('string_escape') Memory.set_str(addr, string) Constants.set_str(string, addr) addr += 8 + math.floor(len(string) / 4 + 1) * 4 line += 4
def timestep(self, integ): """ Return the timestep of a propagator, scaled accordingly @type integ: object @param integ: MDL propagator object (STS or MTS) @rtype: float @return: The timestep (dt) of a propagator """ return integ.getTimestep() * Constants.invTimeFactor()
def executePropagator(prop, phys, forces, io, numsteps): """ Run and finish the propagator. @type prop: Propagator @param prop: MDL Propagator object @type phys: Physical @param phys: The physical system. @type forces: Forces @param forces: MDL Forces object @type io: IO @param io: MDL IO object @type numsteps: int @param numsteps: Number of steps to run """ # RUN if (prop.myStep == 0 and prop.myLevel == 0): io.run(phys, forces, prop.myStep, prop.myTimestep, prop.myPropagator) if (prop.isMDL(prop.myPropagator)): prop.runModifiers(prop.myPropagator.prerunmodifiers, phys, forces, prop, prop.myPropagator) ii = 0 #prop.myPropagator.run(numsteps) #return while (ii < numsteps): nextstop = int(numpy.minimum(numsteps, io.computeNext(ii, phys.remcom, phys.remang))) if (prop.isMDL(prop.myPropagator)): while (ii < nextstop): prop.myPropagator.run(phys, forces, prop) ii += 1 phys.myTop.time = prop.myStep*prop.myPropagator.getTimestep()*Constants.invTimeFactor() phys.updateCOM_Momenta() else: prop.myPropagator.run(nextstop-ii) ii = nextstop if (prop.myLevel == 0): prop.myStep = nextstop phys.myTop.time = prop.myStep*prop.myPropagator.getTimestep() io.run(phys, forces, prop.myStep, prop.myTimestep, prop.myPropagator) if (phys.remcom > 0 and ii % phys.remcom == 0): TopologyUtilities.remLin(phys.velvec, phys.myTop) if (phys.remang > 0 and ii % phys.remang >= 0): TopologyUtilities.remAng(phys.posvec, phys.velvec, phys.myTop) if (prop.isMDL(prop.myPropagator)): prop.runModifiers(prop.myPropagator.postrunmodifiers, phys, forces, prop, prop.myPropagator) prop.myPropagator.finish(phys, forces, prop)
def main(): #init the constants first. Without that, you have nothing Constants.init() print("Printing from main: " + Constants.KeepDirectory) # first create our directory startTime = datetime.now() print('----------------- time now is ----------------------') print(startTime) print('----------------------------------------------------') print() print() _directoryWrapper = DirectoryWrapper.DirectoryWrapper() print('Creating the "Keep_Abstract" folder') _directoryWrapper.makeFolder("Keep_Abstract") print('writing out each file') _xmlTreeWrapper = XMLTreeWrapper.XMLTreeWrapper() _xmlTreeWrapper.writeXMLTree('List_of_150.txt') print('finished writing files') endTime = datetime.now() totaltime = endTime - startTime print('total time = ' + str(totaltime))
def getFilteredPRMLadder(seq, specs, filterRule, ambigAA='X', addEnds=True, ambigEdges=None): prmLadder = [] nodeGen = Constants.nodeInfoGen(seq, considerTerminalMods=True, addTerminalNodes=addEnds, ambigEdges=ambigEdges, ambigAA=ambigAA) for node in nodeGen: addToLadder = False for spec in specs: if node['prm'] == 0 or node['prm'] == spec.pm or filterRule(node, spec): addToLadder = True if addToLadder: prmLadder += [node['prm']] return prmLadder
def executePropagator(prop, phys, forces, io, numsteps): """ Run and finish the propagator. @type prop: Propagator @param prop: MDL Propagator object @type phys: Physical @param phys: The physical system. @type forces: Forces @param forces: MDL Forces object @type numsteps: int @param numsteps: Number of steps to run """ # RUN if (prop.myStep == 0 and prop.myLevel == 0): io.run(phys, forces, prop.myStep, prop.myTimestep, prop.myPropagator) if (prop.isMDL(prop.myPropagator)): prop.runModifiers(prop.myPropagator.prerunmodifiers, phys, forces, prop, prop.myPropagator) ii = 0 while (ii < numsteps): if (io.pmvMODE == 0): # STOP CODE return elif (io.pmvMODE != 2): # RUN CODE if (prop.isMDL(prop.myPropagator)): prop.myPropagator.run(phys, forces, prop) phys.myTop.time = prop.myStep*prop.myPropagator.getTimestep()*Constants.invTimeFactor() phys.updateCOM_Momenta() else: prop.myPropagator.run(1) if (io.doPmv): io.pmvPlot() ii = ii + 1 if (prop.myLevel == 0): prop.myStep += 1 phys.myTop.time = prop.myStep*prop.myPropagator.getTimestep() io.run(phys, forces, prop.myStep, prop.myTimestep, prop.myPropagator) if (phys.remcom >= 0): TopologyUtilities.removeLinearMomentum(phys.velvec, phys.myTop).disown() if (phys.remang >= 0): TopologyUtilities.removeAngularMomentum(phys.posvec, phys.velvec, phys.myTop).disown() else: # PAUSE CODE io.pmvPlot() if (prop.isMDL(prop.myPropagator)): prop.runModifiers(prop.myPropagator.postrunmodifiers, phys, forces, prop, prop.myPropagator) prop.myPropagator.finish(phys, forces, prop)
def init(self, phys, forces, prop): """ Initialize propagator. @type phys: Physical @param phys: The physical system. @type forces: Forces @param forces: MDL Forces object. @type prop: Propagator @param prop: MDL Propagator object. """ self.bathPold = self.bathP #: Old thermostat value as system stores rescaled velocity number of Dof of system, momentum conserved so atoms*3D-3 self.gkT = 3.0*(phys.numAtoms()-1.0)*Constants.boltzmann()*self.temp #: Product of degrees of freedom, boltzmann constant and Kelvin temperature self.KEtoT = 2.0 / (3.0*(phys.numAtoms()-1.0)*Constants.boltzmann()) #: Kinetic to temp. conversion prop.calculateForces(forces) self.Potnl = forces.energies.potentialEnergy(phys) #: Potential energy self.h0 = self.Potnl + forces.energies.kineticEnergy(phys) #: Initial 'internal' Hamiltonian value so that total Hamiltonian allways 0 self.stepsdone = 0 #: Number of steps completed self.avTemp = 0 #: Average Kelvin temperature self.tempers = [] #: Holds pairs of step numbers and average temperatures self.Hamiltonian = [] #: Holds pairs of step numbers and total energies
def run(self, phys, forces, prop): """ Execute the propagator. @type phys: Physical @param phys: The physical system. @type forces: Forces @param forces: MDL Forces object @type prop: Propagator @param prop: MDL Propagator object """ forceconstant = 2*Constants.boltzmann()*self.temp*self.gamma/self.dt # assign random force forces.force += forces.randomForce(phys,self.seed)*numpy.sqrt(forceconstant*phys.masses) phys.velocities *= (1.0-0.5*self.dt*self.gamma) # first half kick phys.velocities += forces.force*0.5*self.dt*phys.invmasses phys.positions += phys.velocities*self.dt # drift prop.calculateForces(forces) forceconstant = 2*Constants.boltzmann()*self.temp*self.gamma/self.dt # assign random force forces.force += forces.randomForce(phys,self.seed)*numpy.sqrt(forceconstant*phys.masses) phys.velocities += forces.force*0.5*self.dt*phys.invmasses # second first kick phys.velocities *= (1.0/(1.0+0.5*self.dt*self.gamma))
def getScoreStats(specs, peptide, ambigEdges=None, ppmstd=5): prmStats = {'All Evidence': 0, 'Majority Evidence': 0, 'None Evidence': 0} nodeGen = Constants.nodeInfoGen(peptide, considerTerminalMods=True, ambigEdges=ambigEdges) prevNodeMass = 0 totalMinNodeScore = 100000 specScoreStats = {} for i in range(len(specs)): specScoreStats[i] = {'Score': 0, 'Negative': 0, 'Min Node Score': 100000} for node in nodeGen: numPos = 0 totalNodeScore = 0 for i, spec in enumerate(specs): if prevNodeMass == 0: specScoreStats[i]['Score'] += spec.getPriorScore(prm=0, formAA=None, lattAA=node['formAA']) score = spec.getNodeScore(prm=node['prm'], formAA=node['formAA'], lattAA=node['lattAA']) specScoreStats[i]['Score'] += score totalNodeScore += score if score > 0: numPos += 1 if score < 0: specScoreStats[i]['Negative'] += 1 if score < specScoreStats[i]['Min Node Score']: specScoreStats[i]['Min Node Score'] = score if numPos == len(specs): prmStats['All Evidence'] += 1 if 2*numPos >= len(specs): prmStats['Majority Evidence'] += 1 if numPos == 0: prmStats['None Evidence'] += 1 if totalNodeScore < totalMinNodeScore: totalMinNodeScore = totalNodeScore prevNodeMass = node['prm'] for i, spec in enumerate(specs): specScoreStats[i]['Score'] += spec.getPriorScore(prm=spec.pm, formAA=node['lattAA'], lattAA=None) scores = [specScoreStats[i]['Score'] for i in specScoreStats] totalPathScore = sum(scores) maxPathScore = max(scores) minPathScore = min(scores) return {'Total Path Score': totalPathScore, 'Total Minimum Node Score': totalMinNodeScore, 'Minimum Path Score': minPathScore, 'Maximum Path Score': maxPathScore, 'Aggregate PRM Score Statistics': prmStats, 'Spectrum Specific Score Statistics': specScoreStats}
def init(self, phys, forces, prop): """ Set and initialize the propagator. @type phys: Physical @param phys: The physical system. @type forces: Forces @param forces: MDL Forces object @type prop: Propagator @param prop: MDL Propagator object """ self.gamma = self.gamma*0.001/Constants.invTimeFactor() #: Dissipative factor prop.calculateForces(forces)