def getcoordinate(self): """ Returns random neighbour coordinates :return (Coordinate): random coordinate that is not further than ngh from center in XY plane this coordinate is also in proper range that is specified by XRANGE and YRANGE (see __init__() documentation) z coordinate is a function valid in a corresponding x and y (function is provided in graph settings (see __init__() documentation)) """ while (True): d = self.ngh * random() angle = (pi * 2) * random() x = d * cos(angle) + self.center.x y = d * sin(angle) + self.center.y coordinate = Coordinate(x, y, 0) if (coordinate.x < self.xrange[0] or coordinate.x > self.xrange[1]): continue if (coordinate.y < self.yrange[0] or coordinate.y > self.yrange[1]): continue coordinate.z = self.func(coordinate.x, coordinate.y) return coordinate
def __init__(self, upper_left=None, lower_right=None): self.upper_left = upper_left self.lower_right = lower_right self.upper_right = Coordinate(self.lower_right.x, self.upper_left.y) self.lower_left = Coordinate(self.upper_left.x, self.lower_right.y) self.area = (self.upper_right.x - self.upper_left.x) * ( self.upper_left.y - self.lower_left.y)
def verwerk_coordinaat(coordinaat): coordinaat = coordinaat.split(",") x = coordinaat[0] y = coordinaat[1] nieuw_coordinaat = Coordinate(x) adjusted_x = nieuw_coordinaat.pas_x_aan() return str(adjusted_x) + ',' + str(y)
def getCustomPath(latitude, longitude, end_place): startCoord = Coordinate() startCoord.latitude = latitude startCoord.longitude = longitude #Get all coordinate in the database for our end place end_coordinates = Coordinate.getAllForBuilding(end_place) if len(end_coordinates) == 0: raise Exception(end_place + " is not a building in our database") #Figure out the two closest coordinates (startCoord, endCoord) = DB.getClosestCoords([startCoord], end_coordinates) #Find all floor plans for our end place #floorPlans = [] #floors = Floor.getAllForBuilding(end_place) #for floor in floors: # floorPlans.append(floor.floor_map) #Get building information for our end place building = Building() building.loadFromID(end_place) #Build path object to pass back path = Path() path.startCoord = startCoord.__dict__ path.endCoord = endCoord.__dict__ path.floorPlans = building.floorPlans path.buildingInfo = building.__dict__ return path.__dict__
def pickEmpty(self): while True: r = random.randrange(0, Constants.SECTOR_SIZE) c = random.randrange(0, Constants.SECTOR_SIZE) # check to see if anything in the sector is already there. if Coordinate(r, c) not in self: return Coordinate(r, c)
def getFollowingCoords(self, c): return [ Coordinate(c.row + 1, c.col + 1), Coordinate(c.row + 1, c.col - 1), Coordinate(c.row - 1, c.col + 1), Coordinate(c.row - 1, c.col - 1) ]
def fill_positions(self, coord): if self.vertical: for i in range(0, self.length): self.positions.append(Coordinate(coord.x + i, coord.y)) else: for i in range(0, self.length): self.positions.append(Coordinate(coord.x, coord.y + i))
def testSinglePiecesCanHaveTwoForwardSingleJumps(self): blackPiece = self.blackPieceAt(0,2) self.redPieceAt(1,1) self.redPieceAt(1,3) moves = blackPiece.getJumpMoves(self.board) self.assertEqual(2, len(moves)) for move in moves: self.assertTrue(move.moveTo == Coordinate(2,0) or move.moveTo == Coordinate(2,4))
class Bar: def __init__(self): self.utility = Util() self.rect = pygame.Rect(200, 300, 80, 5) self.coordinate = Coordinate(0.0, 0.0, 0.0, 0.0) self.lives = 3 self.score = 0 def draw(self, DISPLAYSURF): #(x, y, width, height) pygame.draw.rect(DISPLAYSURF, self.utility.getColor("black"), self.rect) # draw lives to the screen self.drawLives(DISPLAYSURF) # draw score to the screen self.drawScore(DISPLAYSURF) def drawLives(self, DISPLAYSURF): # lives self.utility.draw_text(DISPLAYSURF, "Lives: " + str(self.lives), 25, 465, 390, "black", "white") def drawScore(self, DISPLAYSURF): # lives self.utility.draw_text(DISPLAYSURF, "Score: " + str(self.score), 25, 35, 390, "black", "white") def move(self, DISPLAYSURF, x): pygame.draw.rect(DISPLAYSURF, self.utility.getColor("white"), self.rect) if x > 0 and self.rect.x + x <= self.utility.getScreenWidth() - 80: self.rect.x = self.rect.x + x elif x < 0 and self.rect.x + x >= 0.0: self.rect.x = self.rect.x + x self.draw(DISPLAYSURF) def get_coordinate(self): self.coordinate.setCoordinates(self.rect.x, self.rect.y) return self.coordinate def get_width(self): return self.rect.width def get_height(self): return self.rect.height def reduceLives(self): self.lives -= 1 def getLives(self): return self.lives def updateScore(self, points): self.score = self.score + points
def promoter_c(self): if self.c.strand == '+': return Coordinate(self.c.chr_id, self.tss - self.regions[1], self.tss + self.regions[2] - 1, strand='+') else: return Coordinate(self.c.chr_id, self.tss - self.regions[2] + 1, self.tss + self.regions[1], strand='-')
def testKingsCanMoveForwardAndBackwards(self): blackPiece = self.blackPieceAt(2, 2) moves = blackPiece.getSimpleMoves(self.board) self.assertEqual(4, len(moves)) for move in moves: self.assertTrue(move.moveTo == Coordinate(1,1)\ or move.moveTo == Coordinate(1,3)\ or move.moveTo == Coordinate(3,1)\ or move.moveTo == Coordinate(3,3))
def test_add_without_root_should_add_root(self): bounds = MBR(Coordinate(10, 10), Coordinate(20, 0)) o = Obj('Tank', bounds) r_tree = RTree(4, 2) r_tree.insert(o) self.assertIsNotNone(r_tree.root) self.assertIsInstance(r_tree.root, RTree.Node) self.assertEqual(r_tree.root.mbr, MBR.generate(bounds)) self.assertEqual(len(r_tree.root.members), 1) self.assertEqual(r_tree.root.members[0], o)
def distal_c(self): if self.c.strand == '+': return Coordinate(self.c.chr_id, self.tss - self.regions[0], self.tss - self.regions[1] - 1, strand='+') else: return Coordinate(self.c.chr_id, self.tss + self.regions[1] + 1, self.tss + self.regions[0], strand='-')
def full_c(self): if self.c.strand == '+': return Coordinate(self.c.chr_id, self.tss - self.regions[0], self.end + self.regions[3], strand='+') else: return Coordinate(self.c.chr_id, self.end - self.regions[3], self.tss + self.regions[0], strand='-')
def testRedMovesAfterBlack(self): player1 = Player() player2 = Player() rules = MoveRules() game = Game(player1, player2, rules) move = Move.simpleMove(game.board, self.blackPiece(), Coordinate(2,0), Coordinate(3,1)) rules.getMovesForColor = MagicMock(side_effect=[[move], []]) game.play() rules.getMovesForColor.assert_has_calls([call(Color.BLACK, game.board), call(Color.RED, game.board)])
class Joint(object): ''' classdocs ''' def __init__(self, jointInfo=None, X_3D=None, Y_3D=None, Z_3D=None, X_depth=None, Y_depth=None, X_rgb=None, Y_rgb=None, W_orientation=None, X_orientation=None, Y_orientation=None, Z_orientation=None, trackingState=None): ''' Constructor ''' if jointInfo is not None: self.coordinate_3D = Coordinate_3D(jointInfo[0], jointInfo[1], jointInfo[2]) self.coordinate_depth = Coordinate(jointInfo[3], jointInfo[4]) self.coordinate_rgb = Coordinate(jointInfo[5], jointInfo[6]) self.orientation = Orientation(jointInfo[7], jointInfo[8], jointInfo[9], jointInfo[10]) self.trackingState = jointInfo[11] else: self.coordinate_3D = Coordinate_3D(X_3D, Y_3D, Z_3D) self.coordinate_depth = Coordinate(X_depth, Y_depth) self.coordinate_rgb = Coordinate(X_rgb, Y_rgb) self.orientation = Orientation(W_orientation, X_orientation, Y_orientation, Z_orientation) self.trackingState = trackingState def getCoordinate_3D(self): return self.coordinate_3D.getCoordinate() def getCoordinate_depth(self): return self.coordinate_depth.getCoordinate() def getCoordinate_rgb(self): return self.coordinate_rgb.getCoordinate() def getOrientation(self): return self.orientation.getOrientation() def getTrackingState(self): return self.trackingState
def testWhenAPlayerCannotMoveThenOtherPlayerWins(self): player1 = Player() player2 = Player() rules = MoveRules() game = Game(player1, player2, rules) move = Move.simpleMove(game.board, self.blackPiece(), Coordinate(2,0), Coordinate(3,1)) rules.getMovesForColor = MagicMock(side_effect=[[move], []]) winner = game.play() self.assertEqual(player1, winner)
def neighbours(self, coordinate): """Returns a list of neighbour cells (coordinates)""" if isinstance(coordinate, Coordinate): if self.exists(coordinate): coordinates = [] for x in range(coordinate[0] - 1, coordinate[0] + 2): for y in range(coordinate[0] - 1, coordinate[0] + 2): if self.exists(Coordinate(x, y)): cor = Coordinate(x, y) return coordinates else: raise TypeError('Cannot apply room operation with non-coordinate')
def testSinglePiecesHaveTwoForwardMoves(self): blackPiece = self.blackPieceAt(0,2) moves = blackPiece.getSimpleMoves(self.board) self.assertEqual(2, len(moves)) for move in moves: self.assertTrue(move.moveTo == Coordinate(1,1) or move.moveTo == Coordinate(1,3)) redPiece = self.redPieceAt(4,2) moves = redPiece.getSimpleMoves(self.board) self.assertEqual(2, len(moves)) for move in moves: self.assertTrue(move.moveTo == Coordinate(3,1) or move.moveTo == Coordinate(3,3))
def __init__(self, jointInfo=None, X_3D=None, Y_3D=None, Z_3D=None, X_depth=None, Y_depth=None, X_rgb=None, Y_rgb=None, W_orientation=None, X_orientation=None, Y_orientation=None, Z_orientation=None, trackingState=None): ''' Constructor ''' if jointInfo is not None: self.coordinate_3D = Coordinate_3D(jointInfo[0], jointInfo[1], jointInfo[2]) self.coordinate_depth = Coordinate(jointInfo[3], jointInfo[4]) self.coordinate_rgb = Coordinate(jointInfo[5], jointInfo[6]) self.orientation = Orientation(jointInfo[7], jointInfo[8], jointInfo[9], jointInfo[10]) self.trackingState = jointInfo[11] else: self.coordinate_3D = Coordinate_3D(X_3D, Y_3D, Z_3D) self.coordinate_depth = Coordinate(X_depth, Y_depth) self.coordinate_rgb = Coordinate(X_rgb, Y_rgb) self.orientation = Orientation(W_orientation, X_orientation, Y_orientation, Z_orientation) self.trackingState = trackingState
def __str__(self): """Returns a string representation of a machine""" # TODO: This is a bit performance-consuming border = self._room.border str = '' while ( border % 2 ) > 0 or border > self._room.border: # Find the next matching number for 2 sane rasters border = border - 1 columns = range(int(border / 2)) first_colum = min(columns) def getSign(coordinate): if self._room.exists(coordinate): if self._room.getCellColor == Color.black: return 'B' else: return 'W' else: return 'N' for x in columns: if x is not first_colum: str = str + '\n' # Start a new line for y in columns: coordinate = Coordinate(x, y) if y is first_colum: str = str + getSign(coordinate) + ' ' else: str = str + getSign(coordinate) + ' ' return str.format()
def __init__(self, position=Coordinate(), text=u'', fontsize=12.0, id=None, classes=None): """ @param position: A Coordinate defining the position in the SVG document @type position: Coordinate @param text: The text of the element @type text: string @param fontsize: the fontsize of the text (for calculating width/height) @param id: The unique ID to be used in the SVG document @type id: string @param classes: Classnames to be used in the SVG document @type classes: string or sequence of strings """ if isinstance(position, Coordinate): Shape.__init__(self, tag=u'text', id=id, classes=classes) self.position = position self.text = text self.fontsize = fontsize else: raise TypeError("position must be of type 'Coordinate'")
def BFS_Algorithm(width, height, start, end, data): # init # shortest path result result = [] # list of visited points visited = [[False for y in range(width)] for x in range(height)] # list of parents parent = [[start for y in range(width)] for x in range(height)] y = [0, -1, 1, 0, 1, -1, 1, -1] x = [1, 0, 0, -1, -1, -1, 1, 1] q = queue.Queue(maxsize=0) q.put(start) visited[start.x][start.y] = True # implement while not q.empty(): loc = q.get() if loc == end: result = getPath(start, loc, parent) break else: for i in range(8): newX = loc.x + x[i] newY = loc.y + y[i] point = Coordinate(int(newX), int(newY)) if isValidPoint(width, height, data, point) and visited[newX][newY] == False: q.put(point) parent[newX][newY] = loc visited[newX][newY] = True return result
def update_board_with_time(self) -> None: original_board = deepcopy(self.board) normalizer = 0 for row in range(self.row): for col in range(self.column): temp_prob = 0 current_coord = Coordinate(row, col) neighbors = self.find_valid_neighbors(current_coord) for neighbor in neighbors: transition_prob = self.calc_transition_prob( current_coord, neighbor) # print(f'transition: {transition_prob}') neighbor_prob = original_board[neighbor.x][neighbor.y] # print(f'neighbor_prob: {neighbor_prob}') temp_prob += transition_prob * neighbor_prob # print(f'temp: {temp_prob}') self.board[row][col] = temp_prob normalizer += temp_prob self.board = np.round(np.array(self.board) / normalizer, decimals=ROUND_UPTO).tolist() self.move_ghost()
def update_with_sense(self, sense_coordinate) -> str: sensed_color = self.sensor_color(sense_coordinate, self.ghost_position) print(f'SENSOR READING: {sensed_color}') original_board = deepcopy(self.board) normalizer = 0 for row in range(self.row): for col in range(self.column): if self.sensor_color(sense_coordinate, Coordinate(row, col)) == sensed_color: emission_prob = 1 else: emission_prob = 0 current_cell_prob = original_board[row][col] self.board[row][col] = emission_prob * current_cell_prob normalizer += self.board[row][col] # print(f'normalizer: {normalizer}') self.board = np.round(np.array(self.board) / normalizer, decimals=ROUND_UPTO).tolist() # print(sum([self.board[row][col] for col in range(self.column) for row in range(self.row)])) self.print_board() return sensed_color
def introns_from_annotations(self, gene_annotation_file, header_lines=1): introns_list = [] with open(gene_annotation_file, 'r') as genes_file: for _ in range(header_lines): genes_file.readline() for gene_line in genes_file: fields = gene_line.split('\t') chr_id = fields[2] strand = fields[3] access = fields[1] exon_starts = map(int, fields[9].split(',')[:-1]) exon_ends = map(int, fields[10].split(',')[:-1]) introns = [ Coordinate(chr_id, bpstart - 1, bpend, strand=strand, name=access) for bpstart, bpend in zip(exon_ends[:-1], exon_starts[1:]) ] introns_list += introns return introns_list
def __init__(self): """ Инициализация класса SierpinskiTetrahedron для отображения 3D - модели пирамиды Серпинского """ # инициализируем базовый класс QApplication библиотеки PyQt5, передавая аргументом путь к файлу .py self.application = QtGui.QApplication(sys.argv) # загружаем конфигурационный файл и читаем его self.config = ConfigParser() self.config.read("config.ini") # получаем глубину рекурсии - при нуле строится обычная пирамида self.recursion_rate = self.config.getint("recurse", "recursion_rate") # список пирамид - объектов класса GLMeshItem self.meshes = list() # создаем базовый виджет библиотеки PyOpenGL для отображения 3D - модели self.widget = gl.GLViewWidget() # инициализируем виджет self.init_widget() # достаем из конфига координаты центра пирамиды - он же центр вписанной в основание окружности coordinate = Coordinate(self.config.getint("tetrahedron", "x"), self.config.getint("tetrahedron", "y"), self.config.getint("tetrahedron", "z")) # запускаем рекурсию для построения пирамиды Серпинского self.build_recursive(coordinate, self.config.getint("tetrahedron", "side"), self.recursion_rate) # отрисовываем каждую фигуру на графике for mesh in self.meshes: self.widget.addItem(mesh) # отображаем виджет self.widget.show()
def __init__(self, graph, settings): """ :param graph (matplotlib.pyplot.scatter): graph instance that needs to be filled while exporing the neighbourhood :param settings (Settings): settings of the graph to be plotted and bees algorithm itself Settings that are used here: determing elite and nonelite sites: - BEESNUM - ELITE - NONELITE - RECRUITEDELITE - RECRUITEDNONELITE plotting the points on the graph: - getbest() - getlocalbest() - SIZELOCALBEST - OPACITYLOCALBEST - getrgbcolor() """ self.graph = graph self.settings = settings self.globalbest = Point(Coordinate(float('inf'), float('inf'), float('inf')), Features(None, None, None)) self.wasglobalbest = False self.fabric = CoordinateFabric(settings) self.sites = [] self.pointscontroller = PointsController()
def get_tetrahedron_tops(coordinate: Coordinate, side: float) -> tuple: """ Вычисляет координаты вершины пирамиды :param coordinate: Координаты вписанной в основание пирамиды окружности :param side: Длина стороны :return: Кортеж массивов точек для отрисовки """ A = Coordinate(coordinate.x - side / 2, coordinate.y - math.sqrt(3) / 6 * side, coordinate.z) B = Coordinate(coordinate.x, coordinate.y + math.sqrt(3) / 3 * side, coordinate.z) C = Coordinate(coordinate.x + side / 2, coordinate.y - math.sqrt(3) / 6 * side, coordinate.z) D = Coordinate(coordinate.x, coordinate.y, coordinate.z + math.sqrt(2 / 3) * side) return A, B, C, D
def getRandomCoord(self): """Return an instance of Coordinate with random position inbound limits""" x = random.randint(self.limits[0][0], self.limits[1][0]) y = random.randint(self.limits[0][2], self.limits[1][2]) z = random.randint(self.limits[0][2], self.limits[1][2]) return Coordinate(x = x, y = y, z = z)
def genes_coordinates_from_annotations(self, gene_annotation_file, header_lines=1): genes_coordinates = [] with open(gene_annotation_file, 'r') as genes_file: for _ in range(header_lines): genes_file.readline() for gene_line in genes_file: fields = gene_line.split('\t') chr_id = fields[2] bpstart = int(fields[4]) bpend = int(fields[5]) strand = fields[3] access = fields[1] name = fields[-4] genes_coordinates.append( Coordinate(chr_id, bpstart, bpend, strand=strand, name=access)) return genes_coordinates
class g_Field(Vector): def __init__(self, p,x,y): Vector.__init__(self) self.x = x self.y = y self.Coordinate = Coordinate(x,y) self.units = "Newtons per Kilogram" def calculateGField(self, Points): self.i = 0 self.j = 0 self.theta = 0 for point in Points: if (self.x != point.x or self.y != point.y): E = -6.674 * 10**-11 * point.mass/self.Coordinate.getDistance(point)**2 if (self.x != point.x or self.y != point.y): self.i = self.i + ((E * (self.x - point.x) / (((self.x - point.x) ** 2 + (self.y - point.y) ** 2)) ** 0.5)) self.j = self.j + ((E * (self.y - point.y) / (((self.x - point.x) ** 2 + (self.y - point.y) ** 2)) ** 0.5)) self.r = (self.i ** 2 + self.j ** 2) ** 0.5 if (self.i == 0): self.theta = 90 else: self.theta = self.theta + math.atan2((self.j) , (self.i)) * 180 / math.pi def calculateVoltage (self, Points): self.Potential = 0 for point in Points: if (self.x != point.x or self.y != point.y): v = -6.674 * 10**-11 * point.mass/(((self.x - point.x)**2 + (self.y - point.y)**2 )**0.5) self.Potential = self.Potential + v def __str__(self): return "The Gravitational field at " + str(self.Coordinate) + " is " + Vector.__str__(self)
def splitEqual(coord_row): input_split = coord_row.split("=") for i in input_split: i = Coordinate(i) i.getAdjustedX() return i
def __init__(self, p,x,y): Vector.__init__(self) self.x = x self.y = y self.Coordinate = Coordinate(x,y) self.units = "Newtons per Kilogram"
def loadFile(self, group, index, *args): '''Load configuration from a predefined list of .mat files''' from Coordinate import Coordinate from Window import Window from Medium import Medium from Signal import Signal from System import System from Data import Data from Array import Array from Image import Image import os PHDCODE_ROOT = os.environ['COS_ROOT'] Ni = len(args) if type(index) == int: idx = copy(index) index = [idx] for i in index: if Ni > 0: origin = fileLUT(group, i, args) else: origin = fileLUT(group, i) # The dataset 'type' (defined by me) selects the "import method": if origin.type == 'hugin_delayed': # Using scipy.io.loadmat() to load .mat files. The result is a nparray, where structures # in the array are dictionaries (the data is treated later on..). print 'Loading ' + PHDCODE_ROOT + origin.path + origin.file mat_file = io.loadmat(PHDCODE_ROOT + origin.path + origin.file) BF = mat_file['p'][0, 0]['BF'][0, 0] s = System() s.data = Data() s.data.Xd = Ndarray(mat_file['dataCube'].transpose((1,0,2))) s.data.n = Ndarray(BF['mtaxe_re' ].T) s.data.Nt = Ndarray(BF['Nt'].T) s.data.fs = 40e3 s.data.fc = 100e3 s.data.M = 32 s.data.d = 0.0375 s.data.c = 1500 s.desc = 'HUGIN raw data' return s elif origin.type == 'focus_dump_type_A' or origin.type == 'focus_dump_type_B': # Using scipy.io.loadmat() to load .mat files. The result is a nparray, where structures # in the array are dictionaries (the data is treated later on..). print 'Loading ' + PHDCODE_ROOT + origin.path + origin.file mat_file = io.loadmat(PHDCODE_ROOT + origin.path + origin.file) # Load the 'Sonar' dictionary and get rid of empty dimensions: Sonar = mat_file['Sonar'][0,0] s = System() s.medium = Medium() s.medium.c = Ndarray(Sonar['c'][0,0]) # Propagation speed # self.B = 0 # Assume narrowband # The 'rx_x','rx_y' and 'rx_z' coordinates in the Sonar struct represents # the TX elements' location relative to the HUGIN body. We're going to # rotate this coordination system around the x-axis such that the # y-coordinate is 0 for all elements (22 degrees). rx_x = Sonar['rx_x'][:,1] # RX x-coordinates (HUGIN body) rx_y = Sonar['rx_y'][:,1] # RX y-coordinates (HUGIN body) rx_z = Sonar['rx_z'][:,1] # RX z-coordinates (HUGIN body) rx_yz = np.sqrt(rx_y ** 2 + rx_z ** 2) # RX y-z distance (new z-axis) p = Coordinate(x=rx_x, y=None, z=rx_yz)# New RX coordinates [x, axis] p.setAxesDesc(template='hugin') s.array = Array() s.array.p = p # desc='RX coordinates', # shape_desc=('x','axis')) s.signal = Signal() s.signal.desc = 'upchirp' s.signal.fc = Ndarray(Sonar['fc'][0,0]) if origin.type == 'focus_dump_type_A': s.data = Data() s.data.X = Ndarray(mat_file['mfdata'].T.copy()) s.data.t = Ndarray(mat_file['mtaxe' ][0]) s.image = Image() s.image.xarr = Ndarray(mat_file['xarr'].T.copy()) s.image.yarr = Ndarray(mat_file['yarr'].T.copy()) else: s.data = Data() s.data.X = Ndarray(mat_file['data1'].T.copy()) s.data.t = Ndarray(Sonar['T_pri'][0,0]) s.image = Image() # s.image.xarr = Ndarray(mat_file['xarr'].T.copy()) # s.image.yarr = Ndarray(mat_file['yarr'].T.copy()) return s elif origin.type == 'focus_sas_dump_type_A_parameters': # Using scipy.io.loadmat() to load .mat files. The result is a nparray, where structures # in the array are dictionaries (the data is treated later on..). print 'Loading ' + PHDCODE_ROOT + origin.path + origin.file mat_file = io.loadmat(PHDCODE_ROOT + origin.path + origin.file) # Load the 'Sonar' dictionary and get rid of empty dimensions: Sonar = mat_file['Sonar'][0,0] s = System() s.medium = Medium() s.medium.c = Ndarray(Sonar['c'][0,0]) # Propagation speed # self.B = 0 # Assume narrowband # The 'rx_x','rx_y' and 'rx_z' coordinates in the Sonar struct represents # the TX elements' location relative to the HUGIN body. We're going to # rotate this coordination system around the x-axis such that the # y-coordinate is 0 for all elements (22 degrees). rx_x = Sonar['rx_x'][:,1] # RX x-coordinates (HUGIN body) rx_y = Sonar['rx_y'][:,1] # RX y-coordinates (HUGIN body) rx_z = Sonar['rx_z'][:,1] # RX z-coordinates (HUGIN body) rx_yz = np.sqrt(rx_y ** 2 + rx_z ** 2) # RX y-z distance (new z-axis) p = Coordinate(x=rx_x, y=None, z=rx_yz)# New RX coordinates [x, axis] p.setAxesDesc(template='hugin') s.array = Array() s.array.p = p # desc='RX coordinates', # shape_desc=('x','axis')) s.signal = Signal() s.signal.desc = 'upchirp' s.signal.fc = Ndarray(Sonar['fc'][0,0]) return s elif origin.type == 'focus_sas_dump_type_A_data': # Using scipy.io.loadmat() to load .mat files. The result is a nparray, where structures # in the array are dictionaries (the data is treated later on..). print 'Loading ' + PHDCODE_ROOT + origin.path + origin.file mat_file = io.loadmat(PHDCODE_ROOT + origin.path + origin.file) s = System() s.data = Data() s.data.X = Ndarray(mat_file['mfdata'].copy()) s.data.t = Ndarray(mat_file['mtaxe' ][0]) return s elif origin.type == 'focus_sss_dump_type_A': # Using scipy.io.loadmat() to load .mat files. The result is a nparray, where structures # in the array are dictionaries (the data is treated later on..). print 'Loading ' + PHDCODE_ROOT + origin.path + origin.file mat_file = io.loadmat(PHDCODE_ROOT + origin.path + origin.file) s = System() # s.a = Data() s.img = Ndarray(mat_file['sss_image'].copy()) s.Nping = 140 s.Ny = 4000 s.Nx = 15 s.y_lim = [60,160] return s elif origin.type == 'hisas_sim': # Using scipy.io.loadmat() to load .mat files. The result is a nparray, where structures # in the array are dictionaries (the data is treated later on..). print 'Loading ' + PHDCODE_ROOT + origin.path + origin.file mat_file = io.loadmat(PHDCODE_ROOT + origin.path + origin.file) BF = mat_file['p'][0, 0]['BF'][0, 0] s = System() s.medium = Medium() s.medium.c = Ndarray(BF['c'][0, 0]) # Propagation speed s.array = Array() s.array.desc = 'ula' s.array.M = Ndarray(BF['n_hydros'][0, 0]) # Number of hydrophones s.array.d = Ndarray(BF['d' ][0, 0]) # Element distance s.data = Data() s.data.Xd = Ndarray(mat_file['dataCube']).transpose((1,0,2)) # Ndarray(, # axes = ['y','x','m'], # desc = 'Delayed and matched filtered data') # desc='Delayed and matched filtered data', # shape_desc = ('y','x','m'), # shape_desc_verbose = ('Range','Azimuth','Channel')) s.data.t = Ndarray(BF['mtaxe'].T) # Ndarray(, # axes = ['N'], # desc = 'Time axis') # desc = 'Corresponding time', # shape_desc = ('N','1')) s.phi_min = mat_file['p'][0,0]['phi_min'][0,0] s.phi_max = mat_file['p'][0,0]['phi_max'][0,0] s.R_min = mat_file['p'][0,0]['R_min'][0,0] s.R_max = mat_file['p'][0,0]['R_max'][0,0] s.signal = Signal() s.signal.desc = 'upchirp' s.signal.fc = Ndarray(BF['fc' ][0, 0]) # Carrier frequency return s # Some datasets simply do not fall into a general category. We'll handle these # individually... elif origin.type == 'barge': # Using scipy.io.loadmat() to load .mat files. The result is a nparray, where structures # in the array are dictionaries (the data is treated later on..). print 'Loading ' + PHDCODE_ROOT + origin.path + origin.file mat_file = io.loadmat(PHDCODE_ROOT + origin.path + origin.file) # Load the 'Sonar' dictionary and get rid of empty dimensions: Sonar = mat_file['Sonar'][0, 0] # See http://projects.scipy.org/numpy/wiki/ZeroRankArray s = System() # s.medium = Medium() # s.medium.c = Sonar['c'][0, 0] # Propagation speed # # # Format: Sonar[dictionary key][hydrophone coordinates, bank] # rx_x = Sonar['rx_x'][:, 1] # RX x-coordinates bank 2 (HUGIN body) # rx_y = Sonar['rx_y'][:, 1] # RX y-coordinates bank 2 (HUGIN body) # rx_z = Sonar['rx_z'][:, 1] # RX z-coordinates bank 2 (HUGIN body) # rx_yz = sqrt(rx_y ** 2 + rx_z ** 2) # RX y-z distance (new z-axis) # p = Coordinate(x=rx_x, y=None, z=rx_yz)# New RX coordinates [x, axis] ## p = vstack((rx_x, rx_yz)).T # New RX coordinates [x, axis] # # s.array = Array() # s.array.p = p ## , ## desc='RX coordinates', ## shape_desc=('x','axis')) s.data = Data() s.data.X = Ndarray(mat_file['data1']) s.signal = Signal() s.signal.fc = Ndarray(Sonar['fc'][0,0]) s.medium = Medium() s.medium.c = Ndarray(Sonar['c'][0,0]) # Propagation speed # s.signal = Signal() # s.signal.fc = Sonar['fc'][0, 0] # Carrier frequency # s.signal.bw = Sonar['bw'][0, 0] # s.signal.desc = 'upchirp'# Waveform return s elif origin.type == 'ultrasound multi file': print 'Loading ' + PHDCODE_ROOT + origin.path + origin.file #print 'Loading ' + PHDCODE_ROOT + origin.path + origin.info_file info_file = io.loadmat(PHDCODE_ROOT + origin.path + origin.info_file) mat_file = io.loadmat(PHDCODE_ROOT + origin.path + origin.file) NFrames = info_file['NFrames'][0,0] NElements = info_file['NElements'][0,0] angles = info_file['angles'] ranges = info_file['ranges'] tmp = mat_file['frame%d'%origin.index].shape Xd = np.zeros((tmp[0], tmp[1], tmp[2]), dtype=np.complex64) Xd[:,:,:] = mat_file['frame%d'%i] s = System() s.data = Data() s.data.Xd = Xd s.data.angles = angles s.data.ranges = ranges s.data.M = NElements s.data.NFrames = NFrames return s elif origin.type == 'csound': # Using scipy.io.loadmat() to load .mat files. The result is a nparray, where structures # in the array are dictionaries (the data is treated later < on..). print 'Loading ' + PHDCODE_ROOT + origin.path + origin.file mat_file = io.loadmat(PHDCODE_ROOT + origin.path + origin.file) if origin.index == 1: beamformedCycle = mat_file['beamformedcycle'][0,0] #beamformedFrames = beamformedCycle[0] beamformedCubes = beamformedCycle[1] NFrames = beamformedCycle[2] NFrames = NFrames[0, 0] NElements = beamformedCycle[3] NElements = NElements[0, 0] params = beamformedCycle[4] del beamformedCycle params = params[0, 0] #delays = params[0] angles = params[1]*np.pi/180 ranges = params[2] #phaseFactor = params[3] del params tmp = beamformedCubes[0,0].shape Xd = np.zeros((NFrames,tmp[0],tmp[1],tmp[2]),dtype=np.complex64) for i in range(NFrames): Xd[i,:,:,:] = beamformedCubes[i,0][:,:,:] elif origin.index == 2 or origin.index == 3: if origin.index == 2: NFrames = 10 else: NFrames = 60 NElements = mat_file['NElements'][0,0] angles = mat_file['angles'] ranges = mat_file['ranges'].T tmp = mat_file['frame%d'%1].shape Xd = np.zeros((NFrames, tmp[0], tmp[2], tmp[1]), dtype=np.complex64) for i in range(NFrames): Xd[i,:,:,:] = np.transpose(mat_file['frame%d'%(i+1)], (0, 2, 1)) else: pass # s = System() s.data = Data() s.data.Xd = Xd s.data.angles = angles s.data.ranges = ranges s.data.M = NElements return s elif origin.type == 'ultrasound_simulation': import tables as tb s = System() s.data = Data() # Using scipy.io.loadmat() to load .mat files. The result is a nparray, where structures # in the array are dictionaries (the data is treated later on..). print 'Loading ' + PHDCODE_ROOT + origin.path + origin.file file = tb.openFile( (PHDCODE_ROOT + origin.path + origin.file), 'r' ) root = file.getNode( file.root ) # s.data.fc = root.frame_1.fc.read() # s.data.c = root.frame_1.c.read() s.data.M = root.frame_1.N_rx.read() s.data.angles = root.frame_1.theta.read()[0] # Only first row makes sence to me :p s.data.ranges = root.frame_1.range.read() d = root.frame_1.datacube.read().shape s.data.Xd = np.zeros((100,d[1],d[2],d[0]),dtype=np.complex64) for i in range(100): tmp = np.transpose(getattr(root, 'frame_%d'%(i+1)).datacube.read(), (1, 2, 0)) s.data.Xd[i,:,:,:] = tmp file.close() return s else: print 'WW DataInput() - No method implemented for '+origin.type
def __init__(self,x, y): Coordinate.__init__(self, x, y) self.E = E_Field(self, x, y) self.g = g_Field(self, x, y) self.OverrideE = None self.OverrideG = None