def main(): fname = 'data/empire.jpg' img = Image.open(fname).convert('L') #img.thumbnail((500, 500)) im = array(img) pics = [img] for func in (sobel, gaussian, prewitt): pics.extend(map(toimg, trans(im, func))) grid(pics).show()
def load_map(self, path): doc = dom.parse(path) maptag = doc.firstChild self.name = os.path.splitext(os.path.basename(path))[0] self.description = maptag.getAttribute('description') self.size_str = maptag.getAttribute('size') self.width = int(self.size_str.split('x')[0]) self.height = int(self.size_str.split('x')[1]) for node in maptag.childNodes: if node.nodeName == 'Tiles': self.tiles = str_to_vec_lst(node.firstChild.data) elif node.nodeName == 'Spawnpoints': self.spawnpoints = str_to_vec_lst(node.firstChild.data) elif node.nodeName == 'Portals': for portal_node in node.childNodes: if portal_node.nodeName == 'Portal': # Needs refactoring/improvement point1 = point2 = p1_dir = p2_dir = None for p_node in portal_node.childNodes: if p_node.nodeName == 'p1': point1 = \ str_to_vec(p_node.firstChild.data) p1_dir = \ DIRECTIONS[ p_node.getAttribute('dir')] elif p_node.nodeName == 'p2': point2 = \ str_to_vec(p_node.firstChild.data) p2_dir = \ DIRECTIONS[ p_node.getAttribute('dir')] if point1 is not None and point2 is not None: self.portals.update( {point1: (point2, p2_dir), point2: (point1, p1_dir)}) set_of_tiles = set(grid(self.width, self.height)) set_of_tiles -= set(self.tiles) accessibility_map = [None] * self.width accessibility_map = [[None] * self.height for _ in accessibility_map] for xpos, ypos in grid(self.width, self.height): accessibility_map[xpos][ypos] = (xpos, ypos) not in self.tiles while set_of_tiles: pos = set_of_tiles.pop() tiles = flood_fill(accessibility_map, (self.width, self.height), pos) portals = [] for portal in self.portals: if (self.portals[portal][0] in tiles and portal not in tiles): portals.append(portal) self.islands.append(MapAccessibilityNode(tiles, portals)) set_of_tiles -= tiles
directions = np.rad2deg( np.arctan([(y2 - y1) / ((x2 - x1) + 0.001) for (x1, y1), (x2, y2) in lines])) directions = np.where(directions < 0, directions + 180, directions) hist = np.histogram(directions, range=[0, 180], bins=180) sort_indexes = np.argsort(hist[0]) hist = hist[0][sort_indexes], hist[1][sort_indexes] plt.figure() plt.bar(hist[1], hist[0]) a1, a2 = hist[1][-2:] print(" - Ângulos mais frequentes: " + str(a1) + ", " + str(a2)) print('Exemplo de grade com frequência e fase especificada') plt.imshow(utils.grid(pimg.shape, [a1, a2], [0.02, 0.01], [1, 3], 3)) plt.show() width = 5 img_fit = np.where(pimg == 1, width, -1 / width) def plot_img_grid(image_grid): grid_height, grid_width = len(image_grid), len(image_grid[0]) fig, axes = plt.subplots(grid_height, grid_width, squeeze=False, figsize=1.5 * np.array(plt.rcParams['figure.figsize'])) for i, row in enumerate(axes): for j, ax in enumerate(row):
def load_map(self, path): doc = dom.parse(path) maptag = doc.firstChild self.name = os.path.splitext(os.path.basename(path))[0] self.description = maptag.getAttribute('description') self.size_str = maptag.getAttribute('size') self.width = int(self.size_str.split('x')[0]) self.height = int(self.size_str.split('x')[1]) for node in maptag.childNodes: if node.nodeName == 'Tiles': self.tiles = str_to_vec_lst(node.firstChild.data) elif node.nodeName == 'Spawnpoints': self.spawnpoints = str_to_vec_lst(node.firstChild.data) elif node.nodeName == 'Portals': for portal_node in node.childNodes: if portal_node.nodeName == 'Portal': # Needs refactoring/improvement point1 = point2 = p1_dir = p2_dir = None for p_node in portal_node.childNodes: if p_node.nodeName == 'p1': point1 = \ str_to_vec(p_node.firstChild.data) p1_dir = \ DIRECTIONS[ p_node.getAttribute('dir')] elif p_node.nodeName == 'p2': point2 = \ str_to_vec(p_node.firstChild.data) p2_dir = \ DIRECTIONS[ p_node.getAttribute('dir')] if point1 is not None and point2 is not None: self.portals.update({ point1: (point2, p2_dir), point2: (point1, p1_dir) }) set_of_tiles = set(grid(self.width, self.height)) set_of_tiles -= set(self.tiles) accessibility_map = [None] * self.width accessibility_map = [[None] * self.height for _ in accessibility_map] for xpos, ypos in grid(self.width, self.height): accessibility_map[xpos][ypos] = (xpos, ypos) not in self.tiles while set_of_tiles: pos = set_of_tiles.pop() tiles = flood_fill(accessibility_map, (self.width, self.height), pos) portals = [] for portal in self.portals: if (self.portals[portal][0] in tiles and portal not in tiles): portals.append(portal) self.islands.append(MapAccessibilityNode(tiles, portals)) set_of_tiles -= tiles
#!/usr/bin/env python from __future__ import print_function from utils import grid from utils import partII if __name__ == '__main__': power_level = grid(grid_serial_number=1788, size=300) coordinates, power, size = partII(power_level) print('Answer: {},{},{}'.format(coordinates[0], coordinates[1], size)) #142,265,7
(0, 0): 0.0, (1, 0): 0.1, (2, 0): 0.2, (3, 0): 0.3, (4, 0): 0.4, (5, 0): 0.5, (6, 0): 0.6, (7, 0): 0.7, (8, 0): 0.8, (9, 0): 0.9, (10, 0): 1.0, } png.write(args.out, config, valResults, 11, 1) sys.exit(0) i = 0 for loc in utils.grid(bounds, lat_steps, lng_steps): yi = i // lng_steps xi = i % lng_steps #print('xi = ' + str(xi) + ' yi = ' + str(yi)) y = loc['loc']['lat'] x = loc['loc']['lng'] results[(y, x)] = {} if (1): if (funcRecord.get('module')): results[(y, x)]['val'] = evaluate_variable((y, x), data, config, args.func) else: results[(y, x)]['val'] = evaluate((y, x), data, config, funcRecord) valResults[(xi,yi)] = results[(y, x)]['val'] else: # for testing with something like "wrmap.py -resolution 5 -eval" results[(y, x)]['val'] = 'not eval'
def auxGrid(freq1, phase1, freq2, phase2): return utils.grid(img_fit.shape, [a1, a2], [freq1, freq2], [phase1, phase2], width)
directions = np.rad2deg( np.arctan([(y2 - y1) / ((x2 - x1) + 0.001) for (x1, y1), (x2, y2) in lines])) directions = np.where(directions < 0, directions + 180, directions) hist = np.histogram(directions, range=[0, 180], bins=180) sort_indexes = np.argsort(hist[0]) hist = hist[0][sort_indexes], hist[1][sort_indexes] plt.figure() plt.bar(hist[1], hist[0]) a1, a2 = hist[1][-2:] print(" - Ângulos mais frequentes: " + str(a1) + ", " + str(a2)) print('Exemplo de grade com frequência e fase especificada') plt.imshow(utils.grid(pimg.shape, [a1, a2], [0.02, 0.01], [1, 3], 3)) plt.show() width = 5 img_fit = np.where(pimg == 1, width, -1 / width) def auxGrid(freq1, phase1, freq2, phase2): return utils.grid(img_fit.shape, [a1, a2], [freq1, freq2], [phase1, phase2], width) def denormalize(x): min_freq = 0.0016521614890856475 high = np.array([0.5, 500, 0.5, 500]) low = np.array([min_freq, 0, min_freq, 0])
def train(train_loader, model, criterion, optimizer, epoch, scheduler): batch_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() top5 = AverageMeter() # switch to train mode model.train() end = time.time() prefetcher = data_prefetcher(train_loader) input, target = prefetcher.next() i = 0 while input is not None: i += 1 if args.prof >= 0 and i == args.prof: print("Profiling begun at iteration {}".format(i)) torch.cuda.cudart().cudaProfilerStart() if args.prof >= 0: torch.cuda.nvtx.range_push("Body of iteration {}".format(i)) adjust_learning_rate(scheduler, optimizer, epoch, i, len(train_loader)) if args.grid: input = grid(input) # compute output if args.prof >= 0: torch.cuda.nvtx.range_push("forward") output = model(input) if args.prof >= 0: torch.cuda.nvtx.range_pop() loss = criterion(output, target) # compute gradient and do SGD step optimizer.zero_grad() if args.prof >= 0: torch.cuda.nvtx.range_push("backward") with amp.scale_loss(loss, optimizer) as scaled_loss: scaled_loss.backward() if args.prof >= 0: torch.cuda.nvtx.range_pop() # for param in model.parameters(): # print(param.data.double().sum().item(), param.grad.data.double().sum().item()) if args.prof >= 0: torch.cuda.nvtx.range_push("optimizer.step()") optimizer.step() if args.prof >= 0: torch.cuda.nvtx.range_pop() if i % args.print_freq == 0: # Every print_freq iterations, check the loss, accuracy, and speed. # For best performance, it doesn't make sense to print these metrics every # iteration, since they incur an allreduce and some host<->device syncs. # Measure accuracy prec1, prec5 = accuracy(output.data, target, topk=(1, 5)) # Average loss and accuracy across processes for logging if args.distributed: reduced_loss = reduce_tensor(loss.data) prec1 = reduce_tensor(prec1) prec5 = reduce_tensor(prec5) else: reduced_loss = loss.data # to_python_float incurs a host<->device sync losses.update(to_python_float(reduced_loss), input.size(0)) top1.update(to_python_float(prec1), input.size(0)) top5.update(to_python_float(prec5), input.size(0)) torch.cuda.synchronize() batch_time.update((time.time() - end) / args.print_freq) end = time.time() if args.local_rank == 0: print('Epoch: [{0}][{1}/{2}]\t' 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 'Speed {3:.3f} ({4:.3f})\t' 'Loss {loss.val:.10f} ({loss.avg:.4f})\t' 'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t' 'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format( epoch, i, len(train_loader), args.world_size * args.batch_size / batch_time.val, args.world_size * args.batch_size / batch_time.avg, batch_time=batch_time, loss=losses, top1=top1, top5=top5)) if args.prof >= 0: torch.cuda.nvtx.range_push("prefetcher.next()") input, target = prefetcher.next() if args.prof >= 0: torch.cuda.nvtx.range_pop() # Pop range "Body of iteration {}".format(i) if args.prof >= 0: torch.cuda.nvtx.range_pop() if args.prof >= 0 and i == args.prof + 10: print("Profiling ended at iteration {}".format(i)) torch.cuda.cudart().cudaProfilerStop() quit()