diff --git a/esrimap/esrimap.py b/esrimap/esrimap.py index 160bcb80bbad9b1e47ac10405b6899c9af9cd01c..abfdd099fbdb4aca6594fd362cd85effbe04a890 100644 --- a/esrimap/esrimap.py +++ b/esrimap/esrimap.py @@ -100,6 +100,45 @@ nodata_value {self.nodata_value} header = header.replace("xllcenter", "xllcorner").replace("yllcenter", "yllcorner") return header + @classmethod + def from_ascii(cls, ascii_text: str) -> EsriAscii: + """Create an EsriAscii object from an ascii text. Data length must match rows and columns + (length of data = rows * columns) + + :param ascii_text: The text (Should be an Esri Ascii raster formatted text) + :return: an EsriAscii map + """ + lines = ascii_text.splitlines() + assert len(lines) > 6 + _, s_ncols = lines[0].split(" ") + ncols = int(s_ncols) + _, s_nrows = lines[1].split(" ") + nrows = int(s_nrows) + alignment, s_xll = lines[2].split(" ") + xll = int(s_xll) + if alignment[3:] == "center": + coord = EsriCoordinateType.center + else: + coord = EsriCoordinateType.corner + _, s_yll = lines[3].split(" ") + yll = int(s_yll) + _, s_cellsize = lines[4].split(" ") + cellsize = int(s_cellsize) + _, s_nodata = lines[5].split(" ") + nodata = int(s_nodata) + s_data = " ".join(lines[6:]) + data = np.array(s_data.split(" "), dtype=np.int32).reshape((nrows, ncols)) + ascii_map = cls(rows=nrows, + cols=ncols, + cellsize=cellsize, + data_array=data, + nodata_value=nodata, + coord_type=coord, + ) + ascii_map.xll = int(xll) + ascii_map.yll = int(yll) + return ascii_map + def to_ascii(self) -> str: """Return the map as text @@ -107,6 +146,12 @@ nodata_value {self.nodata_value} """ return self.header + self.sdata + @classmethod + def from_file(cls, path: str) -> EsriAscii: + with open(path) as fp: + content = fp.read() + return cls.from_ascii(content) + def to_file(self, path: str) -> None: """Write the ascii raster to a file.