def net_topology(self, topology): self.mask = ma.Mask(self, topology).weights; # this boolean specifies if the net has a fully connected topology # (in this sense if it's not so the backprop and forward change a lot) self.fully_connected = False;
class Pyro(Character): #FIXME: width, height of pyro - rectangle collision collision_mask = mask.Mask(12, 33, True) max_speed = 198 maxhp = 120 def __init__(self, game, state, player_id): Character.__init__(self, game, state, player_id) self.hp = self.maxhp self.weapon_id = weapon.Flamethrower(game, state, self.id).id
class Engineer(Character): # FIXME: width, height of engineer - rectangle collision collision_mask = mask.Mask(12, 33, True) max_speed = 180 maxhp = 120 def __init__(self, game, state, player_id): Character.__init__(self, game, state, player_id) self.hp = self.maxhp self.weapon_id = weapon.Shotgun(game, state, self.id).id
class Soldier(Character): # FIXME: width, height of soldier - rectangle collision collision_mask = mask.Mask(12, 33, True) max_speed = 162 maxhp = 150 def __init__(self, game, state, player_id): Character.__init__(self, game, state, player_id) self.hp = self.maxhp self.weapon_id = weapon.Rocketlauncher(game, state, self.id).id
class Sniper(Character): # FIXME: width, height of heavy - rectangle collision # TODO: this class collision_mask = mask.Mask(12, 33, True) max_speed = 144 maxhp = 200 def __init__(self, game, state, player_id): Character.__init__(self, game, state, player_id) self.hp = self.maxhp self.weapon_id = weapon.Minigun(game, state, self.id).id
class Spy(Character): # FIXME: width, height of spy - rectangle collision collision_mask = mask.Mask(12, 33, True) max_speed = 194.4 maxhp = 100 def __init__(self, game, state, player_id): Character.__init__(self, game, state, player_id) self.hp = self.maxhp self.weapon_id = weapon.Revolver(game, state, self.id).id self.cloaking = False
class Medic(Character): # FIXME: width, height of Medic - rectangle collision # FIXME: offsets to be proper collision_mask = mask.Mask(12, 33, True) max_speed = 175 maxhp = 120 def __init__(self, game, state, player_id): Character.__init__(self, game, state, player_id) self.hp = self.maxhp self.weapon_id = weapon.Medigun(game, state, self.id).id
class Heavy(Character): # FIXME: width, height of heavy - rectangle collision collision_mask = mask.Mask(12, 33, True) max_speed = 144 maxhp = 200 def __init__(self, game, state, player_id): Character.__init__(self, game, state, player_id) self.hp = self.maxhp self.weapon_id = weapon.Minigun(game, state, self.id).id def step(self, game, state, frametime): Character.step(self, game, state, frametime) if self.get_player(state).leftmouse: self.hspeed = min(54, max(-54, self.hspeed))
class Quote(Character): # width, height of scout - rectangle collision collision_mask = mask.Mask(12, 33, True) max_speed = 252 maxhp = 100 run_power = 1.4; def __init__(self, game, state, player_id): Character.__init__(self, game, state, player_id) self.hp = self.maxhp self.weapon_id = weapon.Blade(game, state, self.id).id self.can_doublejump = True def jump(self, game, state): if self.onground(game, state): self.vspeed = -300 self.can_doublejump = True elif self.can_doublejump: self.vspeed = -300 self.can_doublejump = False
def find_n_dot_estimate(self, fix_mask): ''' Estimate the number of dots and a mask assuming the chemical potential is mu_l everywhere The mask is defined as a list of size len(x) where x is the x-grid. Each element is labelled as 'l0','l1' corresponding to the leads, 'di' corresponding to the ith dot and 'bi' corresponding to the ith barrier. Counting begins from 0. ''' mu = self.mu_l[0] mu_x = np.repeat(mu, len(self.V)) # Use mu - V ~ n to make a preliminary classfication if (not fix_mask): prelim_mask = mask.Mask(mu_x - self.V) self.mask = prelim_mask return prelim_mask.mask_info['num_dot'] else: # return value from the old calculation return self.mask.mask_info['num_dot']
import sys import cv2 import utils import detection import mask import sqlmanager import schedule import track sys.path.insert(0, "analysis/") import analyzer #----------------------------- #<------ Configuration ------> #----------------------------- mask = mask.Mask("config-files/maskConfig.json") db = sqlmanager.SQLManager("config-files/MySQLConfig.json") analyzerObjct = analyzer.loadAnalyzer("config-files/analyzerConfig.json") #----------------------------- #<---------- Main -----------> #----------------------------- if __name__ == "__main__": # Load video here cap = cv2.VideoCapture('videos/testRotonda.mp4') # Should we resize the video frame? # cap.set(3, 1280) # cap.set(4, 720)
#%% import datasets import mask import numpy as np from scipy.stats import ttest_ind_from_stats nii_prefix = 'mri/mwp1{}.nii' centers_list = datasets.load_centers_mcad(use_nii=True, use_csv=False, nii_prefix=nii_prefix) _mask = mask.Mask('./data/mask', 'grey_matter_smoothed_005.nii') d = _mask.get_mask_data().flatten() #%% def get_center_voxel_msn_by_label(center, label): persons = center.get_by_label(label) data = [] for person in persons: data.append(np.asarray(person.nii.dataobj).flatten()) data = np.array(data) mean = np.mean(data, axis=0) std = np.std(data, axis=0) count = data.shape[0] return mean, std, count def gen_voxel_msn(centers_list, label_eg, label_cg): for center in centers_list: mean_eg, std_eg, count_eg = get_center_voxel_msn_by_label(center, label_eg) mean_cg, std_cg, count_cg = get_center_voxel_msn_by_label(center, label_cg) if count_eg and count_cg: t, p = ttest_ind_from_stats(mean_eg, std_eg, count_eg,
class Building_Sentry(entity.MovingObject): max_hp = 100 # Maximum hitpoints the sentry can ever have starting_hp = 25 # At what hitpoints the sentry will start building collision_mask = mask.Mask(26, 19, True) # TODO: Implement changing masks build_time = 2 # Number of secs it takes to build hp_increment = (max_hp-starting_hp)/build_time animation_increment = 10/build_time # 10 == number of frames in sentry build animation def __init__(self, game, state, owner): super(Building_Sentry, self).__init__(game, state) self.hp = self.starting_hp self.isfalling = True self.animation_frame = 0 self.building_time = 0 self.owner_id = owner.id self.x = owner.x self.y = owner.y self.team = owner.team if owner.flip == True: self.flip = True else: self.flip = False def step(self, game, state, frametime): if self.isfalling: # If we've hit the floor, get us back out and build while game.map.collision_mask.overlap(self.collision_mask, (int(round(self.x)), int(round(self.y)))): self.y -= 1 self.isfalling = False # Gravity self.vspeed += 300 * frametime # TODO: air resistance, not hard limit self.vspeed = min(800, self.vspeed) if not self.isfalling: self.hspeed = 0 self.vspeed = 0 if self.hp <= 0: self.destroy(state) return if self.building_time >= self.build_time: # Cap hp at max hp if self.hp >= self.max_hp: self.hp = self.max_hp # Create a finished sentry, and destroy the building sentry object owner = state.entities[self.owner_id] owner.sentry = Sentry(game, state, self.owner_id, self.x, self.y, self.hp, self.flip, self.team) self.destroy(state) else: # Continue building self.hp += self.hp_increment * frametime self.building_time += frametime self.animation_frame += self.animation_increment * frametime def interpolate(self, prev_obj, next_obj, alpha): super(Building_Sentry, self).interpolate(prev_obj, next_obj, alpha) self.animation_frame = prev_obj.animation_frame + (next_obj.animation_frame - prev_obj.animation_frame) * alpha self.hp = prev_obj.hp + (next_obj.hp - prev_obj.hp) * alpha self.build_time = prev_obj.build_time + (next_obj.build_time - prev_obj.build_time) * alpha def destroy(self, state): # TODO: Sentry destruction syncing, bubble super(Building_Sentry, self).destroy(state)
def file_mask_buf(self, file_path): mask_ = mask.Mask() mask_.masked(file_path)
def fileMask(self): mask_ = mask.Mask() mask_.masked(self.path_entry.get())
def main(): # Init logger if not os.path.isdir(args.save_path): os.makedirs(args.save_path) if args.resume: if not os.path.isdir(args.resume): os.makedirs(args.resume) log = open(os.path.join(args.save_path, '{}.txt'.format(args.description)), 'w') print_log('save path : {}'.format(args.save_path), log) state = {k: v for k, v in args._get_kwargs()} print_log(state, log) print_log("Random Seed: {}".format(args.manualSeed), log) print_log("use cuda: {}".format(args.use_cuda), log) print_log("python version : {}".format(sys.version.replace('\n', ' ')), log) print_log("torch version : {}".format(torch.__version__), log) print_log("cudnn version : {}".format(torch.backends.cudnn.version()), log) print_log("Compress Rate: {}".format(args.rate), log) print_log("Epoch prune: {}".format(args.epoch_prune), log) print_log("description: {}".format(args.description), log) # Init data loader if args.dataset=='cifar10': train_loader=dataset.cifar10DataLoader(True,args.batch_size,True,args.workers) test_loader=dataset.cifar10DataLoader(False,args.batch_size,False,args.workers) num_classes=10 elif args.dataset=='cifar100': train_loader=dataset.cifar100DataLoader(True,args.batch_size,True,args.workers) test_loader=dataset.cifar100DataLoader(False,args.batch_size,False,args.workers) num_classes=100 elif args.dataset=='imagenet': assert False,'Do not finish imagenet code' else: assert False,'Do not support dataset : {}'.format(args.dataset) # Init model if args.arch=='cifarvgg16': net=models.vgg16_cifar(True,num_classes) elif args.arch=='resnet32': net=models.resnet32(num_classes) elif args.arch=='resnet56': net=models.resnet56(num_classes) elif args.arch=='resnet110': net=models.resnet110(num_classes) else: assert False,'Not finished' print_log("=> network:\n {}".format(net),log) net = torch.nn.DataParallel(net, device_ids=list(range(args.ngpu))) # define loss function (criterion) and optimizer criterion = torch.nn.CrossEntropyLoss() optimizer = torch.optim.SGD(net.parameters(), state['learning_rate'], momentum=state['momentum'], weight_decay=state['decay'], nesterov=True) if args.use_cuda: net.cuda() criterion.cuda() recorder = RecorderMeter(args.epochs) # optionally resume from a checkpoint if args.resume: if os.path.isfile(args.resume+'checkpoint.pth.tar'): print_log("=> loading checkpoint '{}'".format(args.resume+'checkpoint.pth.tar'), log) checkpoint = torch.load(args.resume+'checkpoint.pth.tar') recorder = checkpoint['recorder'] args.start_epoch = checkpoint['epoch'] if args.use_state_dict: net.load_state_dict(checkpoint['state_dict']) else: net = checkpoint['state_dict'] optimizer.load_state_dict(checkpoint['optimizer']) print_log("=> loaded checkpoint '{}' (epoch {})".format(args.resume, checkpoint['epoch']), log) if args.evaluate: time1=time.time() validate(test_loader,net,criterion,args.use_cuda,log) time2=time.time() print('validate function took %0.3f ms' % ((time2 - time1) * 1000.0)) return else: print_log("=> no checkpoint found at '{}'".format(args.resume), log) else: print_log("=> not use any checkpoint for {} model".format(args.description), log) if args.original_train: original_train.args.arch=args.arch original_train.args.dataset=args.dataset original_train.main() return comp_rate=args.rate m=mask.Mask(net,args.use_cuda) print("-" * 10 + "one epoch begin" + "-" * 10) print("the compression rate now is %f" % comp_rate) val_acc_1, val_los_1 = validate(test_loader, net, criterion, args.use_cuda,log) print(" accu before is: %.3f %%" % val_acc_1) m.model=net print('before pruning') m.init_mask(comp_rate,args.last_index) m.do_mask() print('after pruning') m.print_weights_zero() net=m.model#update net if args.use_cuda: net=net.cuda() val_acc_2, val_los_2 = validate(test_loader, net, criterion, args.use_cuda,log) print(" accu after is: %.3f %%" % val_acc_2) # start_time=time.time() epoch_time=AverageMeter() for epoch in range(args.start_epoch,args.epochs): current_learning_rate=adjust_learning_rate(args.learning_rate,optimizer,epoch,args.gammas,args.schedule) need_hour, need_mins, need_secs = convert_secs2time(epoch_time.avg * (args.epochs - epoch)) need_time = '[Need: {:02d}:{:02d}:{:02d}]'.format(need_hour, need_mins, need_secs) print_log( '\n==>>{:s} [Epoch={:03d}/{:03d}] {:s} [learning_rate={:6.4f}]'.format(time_string(), epoch, args.epochs, need_time, current_learning_rate) \ + ' [Best : Accuracy={:.2f}]'.format(recorder.max_accuracy(False)), log) train_acc,train_los=train(train_loader,net,criterion,optimizer,epoch,args.use_cuda,log) validate(test_loader, net, criterion,args.use_cuda, log) if (epoch % args.epoch_prune == 0 or epoch == args.epochs - 1): m.model=net print('before pruning') m.print_weights_zero() m.init_mask(comp_rate,args.last_index) m.do_mask() print('after pruning') m.print_weights_zero() net=m.model if args.use_cuda: net=net.cuda() val_acc_2, val_los_2 = validate(test_loader, net, criterion,args.use_cuda,log) is_best = recorder.update(epoch, train_los, train_acc, val_los_2, val_acc_2) if args.resume: save_checkpoint({ 'epoch': epoch + 1, 'state_dict': net, 'recorder': recorder, 'optimizer': optimizer.state_dict(), }, is_best, args.resume, 'checkpoint.pth.tar') print('save ckpt done') epoch_time.update(time.time()-start_time) start_time=time.time() torch.save(net,args.model_save) # torch.save(net,args.save_path) flops.print_model_param_nums(net) flops.count_model_param_flops(net,32,False) log.close()
class Sentry(entity.MovingObject): collision_mask = mask.Mask(26, 19, True) def __init__(self, game, state, owner_id, x, y, hp, flip, team): super(Sentry, self).__init__(game, state) self.owner_id = owner_id self.aiming_direction = 0 self.x = x self.y = y self.hp = hp self.flip = flip self.detection_radius = 375 self.team = team self.rotating = False self.turret_flip = flip self.rotatestart = 0 self.rotateend = 4 self.rotateindex = self.rotatestart; self.default_direction = 180 * self.flip self.direction = self.default_direction #targetting Queue self.nearest_target = -1 self.target_queue = [] def step(self, game, state, frametime): # TODO: Aim at nearest enemy # TODO: Clean up if self.hp <= 0: self.destroy(state) self.target_queue = [] #clear the list for obj in state.entities.values(): if isinstance(obj, character.Character) and math.hypot(self.x-obj.x,self.y - obj.y) <= self.detection_radius: target_tuple = (obj, math.hypot(self.x-obj.x,self.y - obj.y)) self.target_queue.append(target_tuple) if len(self.target_queue) > 0: #TODO: implement point_direction and adjust priorities accordingly self.target_queue.sort(key= lambda distance: distance[1]) #sort by the second item in the tuples; distance self.nearest_target = self.target_queue[0][0] #get the first part of tuple target_character = state.entities[self.nearest_target.id] target_angle = function.point_direction(self.x,self.y,target_character.x,target_character.y) self.direction = target_angle if target_character.x > self.x and self.turret_flip == True: self.rotating = True elif target_character.x < self.x and self.turret_flip == False: self.rotating = True else: self.nearest_target = -1 if self.nearest_target == -1 and self.flip != self.turret_flip: #reset to old position self.rotating = True self.direction = self.default_direction if self.rotating == True: self.rotateindex += 0.15 if (self.rotateindex >= self.rotateend): self.rotating = False self.turret_flip = not self.turret_flip self.rotateindex = self.rotatestart def interpolate(self, prev_obj, next_obj, alpha): super(Sentry, self).interpolate(prev_obj, next_obj, alpha) self.hp = prev_obj.hp + (next_obj.hp - prev_obj.hp) * alpha self.direction = prev_obj.direction + (next_obj.direction - prev_obj.direction) * alpha self.rotateindex = prev_obj.rotateindex + (next_obj.rotateindex - prev_obj.rotateindex) * alpha if alpha < 0.5: self.rotating = prev_obj.rotating else: self.rotating = next_obj.rotating if alpha < 0.5: self.turret_flip = prev_obj.turret_flip else: self.turret_flip = next_obj.turret_flip def destroy(self, state): # TODO: Sentry destruction syncing, bubble super(Sentry, self).destroy(state) owner = state.entities[self.owner_id] owner.sentry = None