def test_get_pnt(self): """Test get_pnt method""" line = Line([(0, 0), (1, 1)]) with self.assertRaises(ValueError): line.point_on_line(5) vals = (0.7071067811865475, 0.7071067811865475) self.assertTupleEqual(line.point_on_line(1).coords(), vals)
def test_get_pnt(self): """Test get_pnt method""" line = Line([(0, 0), (1, 1)]) with self.assertRaises(ValueError): line.get_pnt(5) vals = (0.7071067811865475, 0.7071067811865475) self.assertTupleEqual(line.get_pnt(1).coords(), vals)
def setUp(self): """Create input data """ self.runModule("g.region", res=1, n=90, s=0, w=0, e=90) self.runModule("r.mapcalc", expression="map_a = 100 + row() + col()", overwrite=True) self.runModule("r.mapcalc", expression="zone_map = if(row() < 20, 1,2)", overwrite=True) self.runModule("r.mapcalc", expression="row_map = row()", overwrite=True) self.runModule("r.to.vect", input="zone_map", output="zone_map", type="area", overwrite=True) cols = [(u'cat', 'INTEGER PRIMARY KEY'), (u'name', 'VARCHAR(20)')] vt = VectorTopo('test_line') vt.open('w', tab_cols=cols) line1 = Line([(1, 1), (2, 1), (2, 2)]) line2 = Line([(10, 20), (15, 22), (20, 32), (30, 40)]) vt.write(line1, ('first',)) vt.write(line2, ('second',)) vt.table.conn.commit() vt.close() vt = VectorTopo('test_small_area') vt.open('w', tab_cols=cols) area1 = Boundary(points=[(0, 0), (0, 0.2), (0.2, 0.2), (0.2, 0), (0, 0)]) area2 = Boundary(points=[(2.7, 2.7), (2.7, 2.8), (2.8, 2.8), (2.8, 2.7), (2.7, 2.7)]) cent1 = Centroid(x=0.1, y=0.1) cent2 = Centroid(x=2.75, y=2.75) vt.write(area1) vt.write(area2) vt.write(cent1, ('first',)) vt.write(cent2, ('second',)) vt.table.conn.commit() vt.close()
def test_bbox(self): """Test bbox method""" line = Line([(0, 10), (0, 11), (1, 11), (1, 10)]) bbox = line.bbox() self.assertEqual(11, bbox.north) self.assertEqual(10, bbox.south) self.assertEqual(1, bbox.east) self.assertEqual(0, bbox.west)
def _axes_x_marks(self): """Return""" mark_x = [] labels = [] for i in range(self.cols): for j in range(self.opts2["rows"]): for k in range(int(self.cols_width_left[i + 1]), 0, -int(self.opts1["mark_x_dist"])): pnt1 = Point( self.centers[i][j].x + self.cols_width_left[i + 1] - k, self.centers[i][j].y - self.opts1["mark_lon"], ) pnt2 = Point( self.centers[i][j].x + self.cols_width_left[i + 1] - k, self.centers[i][j].y + self.opts1["mark_lon"], ) mark_x.append(Line([pnt1, pnt2])) labels.append([-k]) pnt1 = Point( self.centers[i][j].x + self.cols_width_left[i + 1], self.centers[i][j].y - self.opts1["mark_lon"] - 1, ) pnt2 = Point( self.centers[i][j].x + self.cols_width_left[i + 1], self.centers[i][j].y + self.opts1["mark_lon"] + 1, ) mark_x.append(Line([pnt1, pnt2])) labels.append([0]) for k in range( int(self.opts1["mark_x_dist"]), int(self.cols_width_right[i + 1]) + 1, int(self.opts1["mark_x_dist"]), ): pnt1 = Point( self.centers[i][j].x + self.cols_width_left[i + 1] + k, self.centers[i][j].y - self.opts1["mark_lon"], ) pnt2 = Point( self.centers[i][j].x + self.cols_width_left[i + 1] + k, self.centers[i][j].y + self.opts1["mark_lon"], ) mark_x.append(Line([pnt1, pnt2])) labels.append([k]) return mark_x, labels
def _axes_y_marks(self): """Return """ mark_y = [] labels = [] for i in range(self.cols): for j in range(self.opts2['rows']): lim_sup = self._get_trans_lim_sup(self.mat_trans[i][j]) for k in range(0, int(lim_sup) + 1, int(self.opts1['mark_y_dist'] * self.scale)): labels.append( [self.mat_trans[i][j].min_height() + k / self.scale]) mark_y.append( Line([ Point( self.centers[i][j].x - self.opts1['mark_lon'], k + self.centers[i][j].y), Point( self.centers[i][j].x + self.opts1['mark_lon'], k + self.centers[i][j].y) ])) return mark_y, labels
def _init_table_to_plant(self): """ Return """ pnt_center = Base.RoadPoint(self.polygon[0]) pnt_1 = Base.RoadPoint(self.polygon[1]) recta_1 = Base.Straight(pnt_center, pnt_1) rectas = [] new_rows = [] for i, dat in enumerate(self.road_table): new_rows.append(dat) if dat['lr_'] != 0: new_rows.append({ 'radio': 0.0, 'a_in': 0.0, 'a_out': 0.0, 'dc_': dat['dc_'], 'lr_': dat['lr_'] }) for i, dat in enumerate(new_rows[:-1]): dat1 = new_rows[i] dat2 = new_rows[i + 1] if dat1['radio'] == 0 and dat2['radio'] == 0: continue elif dat1['radio'] == 0: pnt_center, pnt_1, recta_1 = \ self._staight_curve(pnt_center, pnt_1, dat1, dat2) if i == 1: self.list_aligns.insert(0, recta_1) self.straight_curve_lengs.insert(1, recta_1.length()) elif dat2['radio'] == 0: pnt_center, pnt_1, recta_1 = \ self._curve_straight(pnt_center, pnt_1, dat1, dat2) elif abs(dat1['radio']) > abs(dat2['radio']) and dat1['a_out'] < 0: pnt_center, pnt_1, recta_1 = \ self._curve_high_low(pnt_center, pnt_1, dat1, dat2) elif abs(dat1['radio']) > abs(dat2['radio']) and dat2['a_in'] < 0: pnt_center, pnt_1, recta_1 = \ self._curve_low_high(pnt_center, pnt_1, dat1, dat2) else: raise ValueError('Error') rectas.append(recta_1) new_polygon = [rectas[0].pstart] for i, recta in enumerate(rectas[:-1]): if round(recta.azimuth(), 8) == round(rectas[i + 1].azimuth(), 8): continue new_polygon.append(recta.cutoff(rectas[i + 1])) new_polygon.append(rectas[-1].pend) self.polygon = Line(new_polygon) self.road_table.polyline = new_polygon
def get_area(self, pnts_line2): """Return a closed polyline with this roadline and the reverse of the given roadline """ list_lines = [] pnts_line1 = self.r_pnts line1, line2 = [[]], [[]] for i in range(len(pnts_line1)): if pnts_line1[i] is None or pnts_line2[i] is None: if line1[-1] != [] and line2[-1] != []: line1.append([]) line2.append([]) else: line1[-1].append(pnts_line1[i]) line2[-1].append(pnts_line2[i]) line1 = [lin for lin in line1 if lin != []] line2 = [lin for lin in line2 if lin != []] for i in range(len(line1)): line2[i] = line2[i][::-1] line2[i].append(line1[i][0]) line1[i].extend(line2[i]) line = Line(line1[i]) list_lines.append(line) return list_lines
def get_segments_pnts(self, puntos, vert=None, line=False): """ Return """ list_lines = [] list_attrs = [] for i, ali in enumerate(self.list_aligns): pnt_ini = ali.get_roadpoint(0)[0] pnt_ini.align = i + 1 pnts_align = [pnt_ini] pnts_align.extend([r_pnt for r_pnt in puntos if ali.is_in(r_pnt)]) pnt_end = ali.get_roadpoint(-1)[0] pnt_end.align = i + 1 pnts_align.append(pnt_end) if vert is not None: vert.set_pnts_elev(pnts_align) if line: list_lines.append(Line(pnts_align)) else: list_lines.append(pnts_align) list_attrs.append([ ali.get_leng_accum(), ali.__class__.__name__, round(ali.length(), 3), ali.param(), ali.grassrgb() ]) return list_lines, list_attrs
def not_overlaped(line): """The countur lines are always a ring even if we see tham as line they are just overlaped, we want to avoid this situation therefore we return only the part of the line that is not overlaped """ if len(line) >= 2 and line[1] == line[-2]: return Line(line[: len(line) // 2 + 1]) return line
def _axis_y(self): """Return""" return [ Line([ Point(self.zero_x, self.zero_y), Point(self.zero_x, self.alt_y) ]) ], [["Axis Y", "", ""]]
def _ras(self, r_line): """Return(self.max_elev - self.min_elev) """ line = [] for r_pnt in r_line: line.append( Point(r_pnt.npk + self.zero_x, (r_pnt.z - self.min_elev) * self.scale + self.zero_y)) return Line(line)
def _axis_y(self): """Return """ return [ Line([ Point(self.zero_x, self.zero_y), Point(self.zero_x, self.alt_y) ]) ], [['Axis Y', '', '']]
def _terr(self, r_line): """Return """ line = [] for r_pnt in r_line: line.append( Point(r_pnt.npk + self.zero_x, (r_pnt.terr - self.min_elev) * self.scale + self.zero_y)) return Line(line)
def write_vector_map(self, drainage_network, map_name, linking_elem): """Write a vector map to GRASS GIS using drainage_network is a networkx object """ with VectorTopo(map_name, mode='w', overwrite=self.overwrite) as vect_map: # create db links and tables dblinks = self.create_db_links(vect_map, linking_elem) # set category manually cat_num = 1 # dict to keep DB infos to write DB after geometries db_info = {k: [] for k in linking_elem} # Points for node in drainage_network.nodes(): if node.coordinates: point = Point(*node.coordinates) # add values map_layer, dbtable = dblinks['node'] self.write_vector_geometry(vect_map, point, cat_num, map_layer) # Get DB attributes attrs = tuple([cat_num] + node.get_attrs()) db_info['node'].append(attrs) # bump cat cat_num += 1 # Lines for in_node, out_node, edge_data in drainage_network.edges_iter( data=True): link = edge_data['object'] # assemble geometry in_node_coor = in_node.coordinates out_node_coor = out_node.coordinates if in_node_coor and out_node_coor: line_object = Line([in_node_coor] + link.vertices + [out_node_coor]) # set category and layer link map_layer, dbtable = dblinks['link'] self.write_vector_geometry(vect_map, line_object, cat_num, map_layer) # keep DB info attrs = tuple([cat_num] + link.get_attrs()) db_info['link'].append(attrs) # bump cat cat_num += 1 # write DB for geom_type, attrs in db_info.iteritems(): map_layer, dbtable = dblinks[geom_type] for attr in attrs: dbtable.insert(attr) dbtable.conn.commit() return self
def setUp(self): """Create input data """ self.runModule("g.region", res=1, n=90, s=0, w=0, e=90) self.runModule("r.mapcalc", expression="map_a = 100 + row() + col()", overwrite=True) self.runModule("r.mapcalc", expression="zone_map = if(row() < 20, 1,2)", overwrite=True) self.runModule("r.to.vect", input="zone_map", output="zone_map", type="area", overwrite=True) cols = [(u'cat', 'INTEGER PRIMARY KEY'), (u'name', 'VARCHAR(20)')] vt = VectorTopo('test_line') vt.open('w', tab_cols=cols) line1 = Line([(1, 1), (2, 1), (2, 2)]) line2 = Line([(10, 20), (15, 22), (20, 32), (30, 40)]) vt.write(line1, ('first',)) vt.write(line2, ('second',)) vt.table.conn.commit() vt.close()
def get_pnts_displ(self, list_r_pnts, line=False): """Return a displaced line of a given axis""" list_pnts_d = [] for r_pnt in list_r_pnts: list_pnts_d.append(self.find_cutoff(r_pnt)) if line: return Line(list_pnts_d) else: return list_pnts_d
def update_areas(trn_area, seg_area, ids, cur=None, sql=None): """Update the table with the areas that contained/are contained or intersect the training areas. """ to_up = [] bbox = trn_area.bbox() aline = Line() tline = Line() for s_id in ids: seg_area.id = s_id seg_area.read() seg_area.get_points(aline) trn_area.get_points(tline) if ((intersects(aline, tline)) or (trn_area.contain_pnt(aline[0], bbox)) or (seg_area.contain_pnt(tline[0]))): to_up.append((trn_area.cat, seg_area.cat)) if (cur is not None) and (sql is not None): cur.executemany(sql, to_up) return to_up
def get_roadpnts(self, start, end, interv): """Return""" if start == 0: start = int(self.pk1) if end == -1: end = int(self.pk2) list_pts = [] for pki in range(start, end, interv): list_pts.append(self.get_roadpoint(pki)[0]) self.line = Line(list_pts) return list_pts
def _axes_y(self): """Return""" list_lines = [] list_attrs = [] for i in range(self.cols): for j in range(self.opts2["rows"]): lim_sup = self._get_trans_lim_sup(self.mat_trans[i][j]) pnt2 = Point(self.centers[i][j].x, self.centers[i][j].y + lim_sup) list_lines.append(Line([self.centers[i][j], pnt2])) list_attrs.append(["Axis Y", "", ""]) return list_lines, list_attrs
def test_getitem(self): """Test __getitem__ magic method""" line = Line([(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]) self.assertTupleEqual(line[0].coords(), (0, 0)) self.assertTupleEqual(line[1].coords(), (1, 1)) self.assertTupleEqual(line[-2].coords(), (3, 3)) self.assertTupleEqual(line[-1].coords(), (4, 4)) self.assertListEqual([p.coords() for p in line[:2]], [(0, 0), (1, 1)]) self.assertListEqual([p.coords() for p in line[::2]], [(0, 0), (2, 2), (4, 4)]) with self.assertRaises(IndexError): line[5]
def get_charact_pnts(self, lines=False): """ Return """ list_attrs = [] list_obj = [] for i, ali in enumerate(self.list_aligns): if ali is not None: r_pnt = ali.get_roadpoint(0)[0] if lines: pnt2 = r_pnt.project(10, r_pnt.azi - math.pi / 2) list_obj.append(Line([r_pnt, pnt2])) else: r_pnt.align = ali.__class__.__name__ + '_' + str(i + 1) list_obj.append(r_pnt) list_attrs.append([ r_pnt.get_pk(), r_pnt.get_azi(), r_pnt.p_type, ali.param() ]) for i, ali in enumerate(self.list_aligns[::-1]): if ali is not None: r_pnt = ali.get_roadpoint(-1)[0] break if lines: pnt2 = r_pnt.project(10, r_pnt.azi - math.pi / 2) list_obj.append(Line([r_pnt, pnt2])) else: r_pnt.align = self.list_aligns[-1].__class__.__name__ + '_' + \ str(len(self.list_aligns) + 1) list_obj.append(r_pnt) for i, ali in enumerate(self.list_aligns[::-1]): if ali is not None: list_attrs.append([ ali.get_leng_accum2(), r_pnt.get_azi(), r_pnt.p_type, 'L=0' ]) break return list_obj, list_attrs
def _axes_x(self): """Return """ list_lines = [] list_attrs = [] for i in range(self.cols): for j in range(self.opts2['rows']): pnt2 = Point( self.centers[i][j].x + self.cols_width_left[i + 1] + self.cols_width_right[i + 1], self.centers[i][j].y) list_lines.append(Line([self.centers[i][j], pnt2])) list_attrs.append(['Axis X', '', '']) return list_lines, list_attrs
def _axis_x(self, r_line): """Return """ lines = [] for j in range(0, 4): lines.append( Line([ Point(self.zero_x, self.zero_y - j * self.dist_ejes_x), Point(self.zero_x + r_line[-1].npk, self.zero_y - j * self.dist_ejes_x) ])) return lines, [['Axis X', '', ''], ['Elevation', '', ''], ['Terrain', '', ''], ['Red elevation', '', '']]
def update_lines(line, alist, cur=None, sql=None): """Update lines using only the boundary""" to_up = [] bbox = Bbox() aline = Line() for area in alist: bbox = area.bbox(bbox) if (intersects(area.get_points(aline), line)) or (area.contain_pnt( line[0], bbox)): to_up.append((line.cat, area.cat)) if (cur is not None) and (sql is not None): cur.executemany(sql, to_up) return to_up
def _axis_y_marks(self): """Return""" mark_y = [] labels = [] lim_sup = self.alt_y if lim_sup % int(self.mark_y_dist * self.scale) != 0: lim_sup += int(self.mark_y_dist * self.scale) for i in range(self.zero_y, lim_sup, int(self.mark_y_dist * self.scale)): # labels.append(self.min_elev + i / self.scale) labels.append(self.min_elev + (i - self.zero_y) / self.scale) mark_y.append( Line([ Point(self.zero_x - self.mark_lon, i), Point(self.zero_x + self.mark_lon, i), ])) return mark_y, labels
def _axis_x(self, r_line): """Return""" lines = [] for j in range(0, 4): lines.append( Line([ Point(self.zero_x, self.zero_y - j * self.dist_ejes_x), Point( self.zero_x + r_line[-1].npk, self.zero_y - j * self.dist_ejes_x, ), ])) return lines, [ ["Axis X", "", ""], ["Elevation", "", ""], ["Terrain", "", ""], ["Red elevation", "", ""], ]
def _terr(self): """Return """ list_lines = [] list_attrs = [] for i, col in enumerate(self.mat_trans): for j, tran in enumerate(col): line = [] for r_pnt in tran.terr_pnts: diff = self.cols_width_left[i + 1] - tran.max_left_width() line.append( Point(r_pnt.npk + self.centers[i][j].x + diff, (r_pnt.terr - tran.min_height()) * self.scale + self.centers[i][j].y)) list_lines.append(Line(line)) list_attrs.append( [tran.r_pnt.npk, 'Terr', tran.length(), '', '166:75:45']) return list_lines, list_attrs
def get_line_attrs(self, set_leng=None): """Return Line or list of Lines, split if some roadpoint of the roadline is None, and attributes """ list_lines = [[]] list_attrs = [] lista_lineas = [] for r_pnt in self.r_pnts: if r_pnt is not None: list_lines[-1].append(r_pnt) elif list_lines[-1] != []: list_lines.append([]) for i, lin in enumerate(list_lines): if len(lin) != 0: lista_lineas.append(Line(lin)) if set_leng: self.attrs[set_leng] = round(lista_lineas[-1].length(), 6) list_attrs.append(self.attrs) return lista_lineas, list_attrs
def _ras(self): """Return""" list_lines = [] list_attrs = [] for i, col in enumerate(self.mat_trans): for j, tran in enumerate(col): line = [] for r_pnt in tran.get_ras_pnts(): diff = self.cols_width_left[i + 1] - tran.max_left_width() line.append( Point( r_pnt.npk + self.centers[i][j].x + diff, (r_pnt.z - tran.min_height()) * self.scale + self.centers[i][j].y, )) list_lines.append(Line(line)) list_attrs.append( [tran.r_pnt.npk, "Ras", tran.length(), "", "0:0:255"]) return list_lines, list_attrs
def get_tin_maxmin(self, map_info): """Return""" line1 = Line() num_areas = GrassVect.Vect_get_num_areas(map_info) max_z = 0 min_z = 100000 for area_id in range(1, num_areas + 1): GrassVect.Vect_get_area_points(map_info, area_id, line1.c_points) pto1_z = line1.c_points.contents.z[0] pto2_z = line1.c_points.contents.z[1] pto3_z = line1.c_points.contents.z[2] min_ptos = min(pto1_z, pto2_z, pto3_z) max_ptos = max(pto1_z, pto2_z, pto3_z) if min_ptos < min_z: min_z = min_ptos if max_ptos > max_z: max_z = max_ptos return [int(math.floor(min_z)), int(math.ceil(max_z))]