def _setup(self,host,port): """ connect to Nidus for data transfer and pass sensor up event """ try: # get mgrs converter self._mgrs = mgrs.MGRS() # connect to data store self._nidus = socket.socket(socket.AF_INET,socket.SOCK_STREAM) self._nidus.connect((host,port)) except socket.error as e: raise RuntimeError("RTO:Nidus:%s" % e) except Exception as e: raise RuntimeError("RTO:Unknown:%s" % e)
def getMGRSVal(self,lat,lon): m = mgrs.MGRS() c = m.toMGRS(lat,lon) ind = 1 for i in range(1,len(c)): if c[i].isalpha(): ind = i break v1 = int(c[:ind])*(ord(c[ind:ind+1])+ord(c[ind+1:ind+2])) v2 = int(c[ind+3:]) return (v1*v2,c)
def get_coords(lat,lon): # find out pixels in the MODIS tile within the MGRS tile, as MODIS tile is larger than the MGRS tile # here only the indexes are returned, which realise the pixel to pixel transformation. m = mgrs.MGRS() mg_coor = m.toMGRS(lat, lon, MGRSPrecision=4) s_area = mg_coor[:5] h, v = mtile_cal(lat, lon) mgrss = get_mgrs(h, v).ravel() mgrss = np.array([(i[:5],i[-8:-4],i[-4:]) for i in mgrss]).reshape(2400,2400,3) index = np.where(mgrss[:,:,0] == s_area) d = mgrss[index[0],index[1],:] Scoords = [9999-d[:,2].astype('int'), d[:,1].astype('int')] return index, Scoords
def get_mgrs_info(wkt_polygon: Polygon) -> Tuple[str, str, str]: center = wkt_polygon.centroid longitude, latitude = center.x, center.y mgrs_converter = mgrs.MGRS() mgrs_code = mgrs_converter.toMGRS(latitude, longitude).decode('utf-8') utm_code = mgrs_code[0:2] latitude_band = mgrs_code[2:3] square = mgrs_code[3:5] return utm_code, latitude_band, square
def get_mgrs(h,v): wgs = get_wgs(h,v) m = mgrs.MGRS() mgr = [m.toMGRS(i[1], i[0],MGRSPrecision=4) for i in wgs] #par = partial(par_trans, wgs=wgs) #pool = multiprocessing.Pool(processes = 50) #mgr = pool.map(par, range(len(wgs))) #pool.close() #pool.join() #print 'finshed' return np.array(mgr).reshape(2400,2400)
def main(): m = mgrs.MGRS() # dcs = '38TLN046623' dcs = input("Enter MGRS cord.") dd = m.toLatLon(dcs) lat = m.ddtodms(dd[0]) Lat = round(lat[1] + lat[2] / 60, 1) long = m.ddtodms(dd[1]) Long = round(long[1] + long[2] / 60, 1) print(f"N{int(lat[0])} {Lat}") print(f"E0{int(long[0])} {Long}")
def _convert_to_grid(self): for la,lo in zip(self.lat,self.lon): m = mgrs.MGRS() mgrsCoord = m.toMGRS(la,lo).decode('utf-8') self.mgrsValue.append(mgrsCoord) self.mgrsLon.append(mgrsCoord[:2]) self.mgrsLat.append(mgrsCoord[2:3]) self.mgrsSquare.append(mgrsCoord[3:5]) UTMcoord = m.MGRSToUTM(mgrsCoord.encode('utf-8')) self.coordinates_utm.append((UTMcoord[2],UTMcoord[3])) if self.is_one_square() == True: self.mgrsGridSquare = str(self.mgrsLon[0])+self.mgrsLat[0]+self.mgrsSquare[0] else: self.mgrsGridSquare = -1
def main(): m = mgrs.MGRS() ncells = [] precision = 3 for i in range(100): randlat = np.random.uniform(-50, 50, 1)[0] randlon = np.random.uniform(-179, 179, 1)[0] c = m.toMGRS(randlat, randlon, MGRSPrecision=precision) ncells.append(c) convert = MGRStopoly(ncells) polygons = convert.generate_polytable() print(polygons)
def _setup(self, host, port): """ connect to Nidus for data transfer and pass sensor up event """ try: # get mgrs converter self._mgrs = mgrs.MGRS() # connect to data store self._nidus = ssl.wrap_socket(socket.socket( socket.AF_INET, socket.SOCK_STREAM), ca_certs=wraith.NIDUSCERT, cert_reqs=ssl.CERT_REQUIRED, ssl_version=ssl.PROTOCOL_TLSv1) self._nidus.connect((host, port)) except socket.error as e: raise RuntimeError("RTO:Nidus:%s" % e) except Exception as e: raise RuntimeError("RTO:Unknown:%s" % e)
def __init__(self): self.m = mgrs.MGRS() self.mgrs = "" self.latd, self.lond = "", "" self.latdm, self.londm = "", "" self.latdms, self.londms = "", "" self.coord_formats = [ "Decimal", "Decimal Min", "Decimal Min Sec", "MGRS" ] super(Ui, self).__init__() # Call the inherited classes __init__ method uic.loadUi('point_convert.ui', self) # Load the .ui file self.set_format_dec() self.save = self.findChild(QtWidgets.QAction, "actionSave") self.save.triggered.connect(self.save_text) self.loadlog = self.findChild(QtWidgets.QAction, "actionImport") self.loadlog.triggered.connect(self.import_text) self.exit = self.findChild(QtWidgets.QAction, "actionExit") self.exit.triggered.connect(QtWidgets.QApplication.quit) self.info = self.findChild(QtWidgets.QAction, "actionFormats") self.info.triggered.connect(self.format_info) self.dec_bool = self.findChild(QtWidgets.QCheckBox, "decCheck") self.dec_bool.stateChanged.connect(self.decmode) self.decmin_bool = self.findChild(QtWidgets.QCheckBox, "decminCheck") self.decmin_bool.stateChanged.connect(self.decminmode) self.dms_bool = self.findChild(QtWidgets.QCheckBox, "dmsCheck") self.dms_bool.stateChanged.connect(self.dmsmode) self.mgrs_bool = self.findChild(QtWidgets.QCheckBox, "mgrsCheck") self.mgrs_bool.stateChanged.connect(self.mgrsmode) self.format_btn = self.findChild(QtWidgets.QPushButton, "format") self.format_btn.clicked.connect(self.set_format) self.l1 = self.findChild(QtWidgets.QLabel, "l1") self.l2 = self.findChild(QtWidgets.QLabel, "l2") self.i1 = self.findChild(QtWidgets.QLineEdit, "i1") self.i2 = self.findChild(QtWidgets.QLineEdit, "i2") self.tag = self.findChild(QtWidgets.QLineEdit, "tag") self.convert = self.findChild(QtWidgets.QPushButton, "convert") self.convert.clicked.connect(self.convert_coords) self.results = self.findChild(QtWidgets.QTextEdit, "results") self.show()
def store_need(email, lat, lng, title, description, type): need_mgrs = mgrs.MGRS().toMGRS(lat, lng).decode('UTF-8') entity = datastore.Entity(key=datastore_client.key('User', email, 'need')) entity.update({ 'timestamp': datetime.datetime.now(), 'lat': lat, 'lng': lng, 'mgrs': need_mgrs, 'mgrs_6': need_mgrs[:6], 'mgrs_8': need_mgrs[:8], 'title': title, 'description': description, 'type': type, 'status': 'toconfirm', 'hash': uuid.uuid4().hex, 'p_hash': uuid.uuid4().hex }) datastore_client.put(entity)
class MGRSMapTool(QgsMapTool): import mgrs ct = mgrs.MGRS() epsg4326 = QgsCoordinateReferenceSystem("EPSG:4326") def __init__(self, canvas): QgsMapTool.__init__(self, canvas) self.setCursor(Qt.CrossCursor) def toMgrs(self, pt): canvas = iface.mapCanvas() canvasCrs = canvas.mapSettings().destinationCrs() transform = QgsCoordinateTransform(canvasCrs, self.epsg4326) pt4326 = transform.transform(pt.x(), pt.y()) try: mgrsCoords = self.ct.toMGRS(pt4326.y(), pt4326.x()) except: mgrsCoords = None return mgrsCoords def canvasMoveEvent(self, e): pt = self.toMapCoordinates(e.pos()) mgrsCoord = self.toMgrs(pt) if mgrsCoord: iface.mainWindow().statusBar().showMessage("MGRS Coordinate: " + mgrsCoord) else: iface.mainWindow().statusBar().showMessage("") def canvasReleaseEvent(self, e): pt = self.toMapCoordinates(e.pos()) mgrsCoord = self.toMgrs(pt) if mgrsCoord: clipboard = QApplication.clipboard() clipboard.setText(mgrsCoord) iface.messageBar().pushMessage( "", "Coordinate %s copied to clipboard" % mgrsCoord, level=QgsMessageBar.INFO, duration=3)
def __init__(self): super().__init__() self.show_map = True self.date = "0000-00-00" self.time = "00:00:00" self.m = mgrs.MGRS() self.GZD = "XXX" self.SID = "XX" self.EWP = "00000" self.NSP = "00000" self.latitude = 0.0 self.longitude = 0.0 self.altitude = 0.0 self.speed = 0.0 self.direction = 0.0 self.error = 0.0 self.satellites = 0.0 self.latlon_fstring = "\n\n DecDeg\n {date}\n {time}\n\n Lat: {latitude:.5f}\n Lon: {longitude:.5f}\n Alt: {altitude:.1f} ft\n Vel: {speed:.1f} mph\n Dir: {direction:.1f} deg\n Err: {error:.1f} m\n Sat: {satellites:.0f}" self.mgrs_fstring = "\n\n MGRS\n {date}\n {time}\n\n GZD: {GZD}\n SID: {SID}\n EWP: {EWP}\n NSP: {NSP}\n Alt: {altitude:.1f} ft\n Vel: {speed:.1f} mph\n Dir: {direction:.1f} deg\n Err: {error:.1f} m\n Sat: {satellites:.0f}" self.gps_text = self.latlon_fstring.format(date=self.date, time=self.time, latitude=self.latitude, longitude=self.longitude, altitude=self.altitude, speed=self.speed, direction=self.direction, error=self.error, satellites=self.satellites) self.text = Label(text=self.gps_text, size_hint=(.4, 1), font_name=quantico, font_size=font_size, valign='top') self.text.bind(size=self.text.setter('text_size')) self.browser_widget = CefBrowser(start_url="file:///leaflet.html") self.layout = BoxLayout(orientation='horizontal') self.layout.add_widget(self.browser_widget) self.layout.add_widget(self.text)
def latlon_to_usng(latitude, longitude, precision=4): """US National Grid value for a point location. The precision argument can range from 0 to 5, with 5 representing a 1-m grid, 4 a 10-m grid, 3 a 100-m grid, and so on. Arguments: latitude Latitude in decimal degrees. longitude Longitude in decimal degrees. precision Grid value precision. """ m = _mgrs.MGRS() usng = m.toMGRS(latitude, longitude, MGRSPrecision=precision).decode('ascii') usng_fmt = [] usng_fmt.append(usng[0:3]) usng_fmt.append(usng[3:5]) if precision > 0: gc = usng[5:] idx_split = int(len(gc) / 2) usng_fmt.append(gc[0:idx_split]) usng_fmt.append(gc[idx_split:]) return ' '.join(usng_fmt)
def zoomToPressed(self): try: import mgrs mgrsCoord = str(self.coordBox.text()).replace(" ", "") lat, lon = mgrs.MGRS().toLatLon(mgrsCoord) canvasCrs = self.canvas.mapSettings().destinationCrs() epsg4326 = QgsCoordinateReferenceSystem("EPSG:4326") transform4326 = QgsCoordinateTransform(epsg4326, canvasCrs) center = transform4326.transform(lon, lat) self.canvas.zoomByFactor(1, center) self.canvas.refresh() if self.marker is None: self.marker = QgsVertexMarker(self.canvas) self.marker.setCenter(center) self.marker.setIconSize(8) self.marker.setPenWidth(4) self.removeMarkerButton.setDisabled(False) self.coordBox.setStyleSheet("QLineEdit{background: white}") except Exception, e: print e self.coordBox.setStyleSheet("QLineEdit{background: yellow}")
def get_lon_lat(fhead): #fhead = 'data/50SMG20164100' # generate a list of the forth and fifth letter a = map(chr, range(65, 91)) a.remove('I') a.remove('O') #get the corner coordinates for each tile # the mgrs gives the lower left coordinate t = fhead.split('201')[0][-5:] bl = t ul = t.replace(t[-1], a[a.index(t[-1])+1]) br = t.replace(t[-2], a[a.index(t[-2])+1]) ur = t.replace(t[-2], a[a.index(t[-2])+1]).replace(t[-1], a[a.index(t[-1])+1]) m = mgrs.MGRS() b_l = list(m.toLatLon(bl)) u_l = list(m.toLatLon(ul)) b_r = list(m.toLatLon(br)) u_r = list(m.toLatLon(ur)) return np.array([u_l, u_r, b_l, b_r])
def _get_image_georef(self, im): """ Gets georeference of top left pixel of sentinel .jp2 """ # get the image georeferencing from the jp2 image header xmlString = im.box[3].box[1].box[1].__str__() # find the gml tag corresponding to position posStart = xmlString.find('<gml:pos>') + 9 posStop = xmlString.find('</gml:pos>') refPix = xmlString[posStart:posStop].split() self.refPixUtm = (int(refPix[0]), int(refPix[1])) # get the lon band and hemisphere from the mgrs grid square m = mgrs.MGRS() utm = m.MGRSToUTM(self.mgrsGridSquare.encode('utf-8')) self.refPixUtmZone = utm[0] self.refPixUtmHemisphere = utm[1].decode('utf-8') # generate UTM coordinates for 4 corners of bounding box # make tuple of coordinates describing the bounding polygon. XYs_utm = (self.refPixUtm, (self.refPixUtm[0] + 100000, self.refPixUtm[1]), (self.refPixUtm[0] + 100000, self.refPixUtm[1] - 100000), (self.refPixUtm[0], self.refPixUtm[1] - 100000), self.refPixUtm) self.bboxUtm = XYs_utm
def point_in_tile(lon: Union[int, float], lat: Union[int, float]) -> str: """Function printing where is the (lon, lat) location within the tile. The idea of this function is to show you if the location is very close to a border/corner so you wonder if you would need other COGs in the surroundings.""" m = mgrs.MGRS() _, _, x0, y0 = m.MGRSToUTM(m.toMGRS(lat, lon, MGRSPrecision=0)) _, _, x10, y10 = m.MGRSToUTM(m.toMGRS(lat, lon, MGRSPrecision=1)) x = (x10 - x0) / 10000 y = 10 - (y10 - y0) / 10000 res = "\n" for j in range(11): for i in range(11): if i == x and j == y: sign = "O " elif (i == 0 or i == 10) or (j == 0 or j == 10): sign = "+ " else: sign = " " res += sign res += "\n" return res
def TransformMGRSToDD(self, coordinate): """Performs a coordinate transformation from MGRS format to DD. Valid coordinates in MGRS format are as below: 19LCC3119933278 49MEU7917581850 Invalid values are: 237CC3119933278 72KCC3119933278 MGRS stands for Military Grid Reference System. Each MGRS coordinate transforms into a latitude and longitude values. Args: coordinate: A list containing coordinates in MGRS format. Returns: tuple containing conversion_status: Whether format conversion to decimal degrees succeeded. decimal_degrees_coordinates: List of coordinates in DD(Decimal Degrees) format. """ conversion_status = False decimal_degrees_coordinates = [] self._logger.debug( "Performing MGRS to DD transformation on coordinates %s.", coordinate) try: mgrs_obj = mgrs.MGRS() (latitude, longitude) = mgrs_obj.toLatLon(str(coordinate[0])) conversion_status = True except Exception, e: self._logger.error("MGRS coordinates %s not in proper format, %s.", coordinate[0], e)
import mgrs coords_converter = mgrs.MGRS() def latlon2mgrs(coords: tuple) -> str: return coords_converter.toMGRS(*coords).decode() def mgrs2latlon(coords: str) -> tuple: return coords_converter.toLatLon(str.encode(coords))
import logging # mirc_server = "orwell.freenode.net" # mirc_channel = "#dotest" # mirc_botNick = "bot_test_parker" # mirc_port = 6667 pubserv_IP = "" pubserv_PORT = "" pubserv_PROTOCOL = "" mirc_server = "" mirc_port = 0000 mirc_channel = "" mirc_botNick = "" m = mgrs.MGRS() # Called by pushtoPubServ() def pushUDP(ip_address, port, xml): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sent = sock.sendto(xml, (ip_address, port)) # Called by pushtoPubServ() def pushTCP(ip_address, port, xml): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) conn = sock.connect((ip_address, port))
__name__ = 'landnav' __license__ = 'GPL v3.0' __version__ = '0.3.2' __date__ = 'November 2013' __author__ = 'Dale Patterson' __maintainer__ = 'Dale Patterson' __email__ = '*****@*****.**' __status__ = 'Development' import mpl_toolkits.basemap.pyproj as pyproj import mgrs import math # GLOBALS _GEOD = pyproj.Geod(ellps='WGS84') _MGRS = mgrs.MGRS() def validMGRS(location): """ deterimes if location is valid :param location: location in mgrs coordinate system :returns: True if location is valid """ try: _MGRS.toLatLon(location) except: return False else: return True
def get_all_cb_tiles(lat_min, lat_max, long_min, long_max): m = mgrs.MGRS() corn_tiles = [] tile_info = [] # Using mgrs api, find the corresponding mgrs tile for coords # Append the formatted tile to our list lat_range = np.arange(lat_min, lat_max + 1, .25, dtype='float') long_range = np.arange(long_min, long_max + 1, .25, dtype='float') for latitude in lat_range: for longitude in long_range: tile = m.toMGRS(latitude, longitude, MGRSPrecision=0) tile = str(tile) tile = tile.replace("b", "") tile = tile.replace("'", "") tile = tile[:2] + '/' + tile[2:3] + '/' + tile[3:5] if tile not in corn_tiles: corn_tiles.append(tile) # Iterate through list of tiles and search for corresponding AWS tiles for idx, tile in enumerate(corn_tiles): count = 0 print(idx) print(tile) x = datetime.datetime.now() day = x.day month = x.month year = x.year tile_date = str(year) + '/' + str(month) + '/' + str(day) one_tile = (tile, tile_date) not_found = True # Search through 25 days to find most recent tile for mgrs while not_found: if count == 25: break # Try to grab tile for passed date try: count += 1 one_tile = (tile, tile_date) print(tile_date) resp = get_cb_tile(one_tile) break # Catch any exceptions, to which it just decreases day except Exception as e: print(e) day = day - 1 if day == 0: month = month - 1 if month == 0: year = year - 1 month = 1 day = 31 else: if month == 2: day = 28 elif month in [9, 4, 6, 11]: day = 30 else: day = 31 tile_date = str(year) + '/' + str(month) + '/' + str(day) # Appends tuple of tile name and the downloaded date tile_info.append((tile, tile_date)) # Deletes any directories for which any tiles had no images for x in tile_info: name, date = x name = name.replace("/", "") for root, dirs, files in os.walk('../../../data/corn_belt/' + name): if files: break else: os.rmdir('../../../data/corn_belt/' + name) return tile_info
from botocore.client import Config #custom exception to throw if upload fails class UploadException(Exception): pass # Initialize a session using DigitalOcean Spaces. session = boto3.session.Session() client = session.client('s3', region_name='nyc3', endpoint_url='https://nyc3.digitaloceanspaces.com', aws_access_key_id='<SPACES_ACCESS_KEY>', aws_secret_access_key='<SPACES_SECRET_KEY>') #initialize MGRS to LatLon converter mgrs = mgrs.MGRS() class TrainingHandler: # @param Int index : hardcode an index to start from if you want def __init__(self,index=None): #initialize sentinelsat self.api = SentinelAPI('username', 'password', 'https://scihub.copernicus.eu/dhus') #prepare queue for pending satellite products self.queue = deque([]) # if no index is set, load from indexLog.txt file if index is None: self.index = int(open('indexLog.txt').readline())
def __init__(self, ncells): '''Takes in ncells, which is list of MGRS cells to be converted into shapely polygons''' self.ncells = ncells self.m = mgrs.MGRS()
def left_lon(code): m = mgrs.MGRS() result_tup=m.toLatLon(code.encode()) return result_tup[1]
def left_edge_mgrs(lat,lon): m=mgrs.MGRS() points=str(m.toMGRS(lat,lon)) var = points[2:-1] point_left = var[0:9] + "0" + var[10:-1] + "0" return point_left
def get_scene_list(lon: float, lat: float, start_date: Union[dt.date, dt.datetime], end_date: Union[dt.date, dt.datetime], what: Union[str, Iterable[str]], cloud_cover_le: float = 50, use_ssl: bool = True, also: Optional[List[str]] = None) -> List[str]: """ Returns the scene list of a given location Parameters ---------- lon: float Float value defining the longitude of interest. lat: float Float value defining the latitude of interest. start_date: datetime.date or datetime.datetime Date to start looking for images to download. end_date: datetime.date or datetime.datetime Date to end looking for images to download. what: str or array_like Here you have to define what you want to download as a string or as an array_like of strings. Valid values are: 'TCI', 'B01', 'B02', 'B03', 'B04', 'B05', 'B06', 'B07', 'B08', 'B8A', 'B09', 'B11', 'B12', 'AOT', 'WVP', 'SCL' cloud_cover_le: float FLoat indicating the maximum cloud cover allowed. If the value is 10 it indicates the allowed cloud cover on the image must be lower or equal to 10%. Default value is 50 (%). also: list or None A list detailing if you want to download other COG files in the borders. Valid values are 'N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'. See below where 'X' is the original target. +-----+-----+-----+ |NW | N | NE| | | | | | | | | +-----+-----+-----+ | | | | |W | X | E| | | | | +-----+-----+-----+ | | | | | | | | |SW | S | SE| +-----+-----+-----+ """ _also = { "N": { "x": 0, "y": 150_000 }, "NE": { "x": 150_000, "y": 150_000 }, "E": { "x": 150_000, "y": 0 }, "SE": { "x": 150_000, "y": -150_000 }, "S": { "x": 0, "y": -150_000 }, "SW": { "x": -150_000, "y": -150_000 }, "W": { "x": -150_000, "y": 0 }, "NW": { "x": -150_000, "y": 150_000 }, } if start_date > end_date: raise ValueError( "`start_date` has to be lower or equal than `end_date`") if isinstance(what, str): what = [what] for w in what: if w.upper() not in [item.value for item in Properties]: raise ValueError(f"{w} is not a valid product") fs = s3fs.S3FileSystem(anon=True, use_ssl=use_ssl) start_date = dt.date(start_date.year, start_date.month, start_date.day) end_date = dt.date(end_date.year, end_date.month, end_date.day) rpaths = [] path: Union[str, Path] m = mgrs.MGRS() # Get the remote and local paths for the original target coord = m.toMGRS(lat, lon, MGRSPrecision=0) number, a, b = coord[:-3], coord[-3:-2], coord[-2:] def check_tile(_c): name = _c.split("/")[-1] info = _c + "/" + name + ".json" with fs.open(info, "r") as f: info = json.load(f) date_str = name.split("_")[2] cc = info["properties"]["eo:cloud_cover"] date = dt.datetime.strptime(date_str, "%Y%m%d").date() if cloud_cover_le >= cc and start_date <= date <= end_date: package = [] for w in what: package.append(str(_c + f"/{w}.tif")) rpaths.append(tuple(package)) def check_package(path): _contents = fs.ls(path) with ThreadPoolExecutor() as exe: for _c in _contents: exe.submit(check_tile, _c) with ThreadPoolExecutor() as ex: for yy, mm in _iter_dates(start_date, end_date): path = f"sentinel-cogs/sentinel-s2-l2a-cogs/{number}/{a}/{b}/{yy}/{mm}" ex.submit(check_package, path) # Get the remote and local paths for the adjacent COGS to the target, # if required # TODO (josep) make it threaded as before if also is None: also = [] for al in also: al = al.upper() if al not in list(_also.keys()): raise ValueError(f'"{al}" is not a valid value for `also` keyword') z, hem, x, y = m.MGRSToUTM(coord) x += _also[al]["x"] y += _also[al]["y"] _coord = m.UTMToMGRS(z, hem, x, y, MGRSPrecision=0) number, a, b = _coord[:-3], _coord[-3:-2], _coord[-2:] for yy, mm in _iter_dates(start_date, end_date): path = "sentinel-cogs/sentinel-s2-l2a-cogs/" f"{number}/{a}/{b}/{yy}/{mm}" _contents = fs.ls(path) for _c in _contents: name = _c.split("/")[-1] info = _c + "/" + name + ".json" with fs.open(info, "r") as f: info = json.load(f) date_str = name.split("_")[2] cc = info["properties"]["eo:cloud_cover"] date = dt.datetime.strptime(date_str, "%Y%m%d").date() if cloud_cover_le >= cc and start_date <= date <= end_date: package = [] for w in what: package.append(str(_c + f"/{w}.tif")) rpaths.append(tuple(package)) if not rpaths: raise Exception('No data found') return rpaths
def __init__(self): super().__init__() # self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.FramelessWindowHint) self.setWindowFlags(QtCore.Qt.FramelessWindowHint) self.coordinateType = int(sys.argv[1]) self.disconnectionPolicy = int(sys.argv[2]) self.chooseIka = int(sys.argv[3]) print("choose ika : ", self.chooseIka) self.disconnectTime = int(sys.argv[4]) self.coordinateConverter = mgrs.MGRS() # vars self.isRestart = False self.isClosing = False self.isConfigDone = False self.socketReceive, self.socketSend = None, None self.cabledSocketReceive, self.cabledSocketSend = None, None self.lastMessage = None self.udpLastReceiveTime = None self.payloadID = None self.kgmControl = None self.kgmTest = None # self.ggmTest = None if self.chooseIka == 0: self.kgmTest = Com.PingTest(UKBParams.kgmIp) elif self.chooseIka == 1: self.kgmTest = Com.PingTest(UKBParams.ggmIp) # self.loginTab = None # self.loggedIn = False self.userPermission = 0 self.panelTab = None self.serialPrefix = [0xAA, 0XBB] self.serialSuffix = [0xCC, 0XDD] self.brightnessLevels = [10, 60, 99] self.serialJoystick = None self.joystickPatternDetector = Joystick() self.joystickPatternDetector.setOnClicks(self.execute_joystick_action) self.resources = Resources() self.peripheral = PeripheralData() self.ukbCoords = None self.joystickLeftX = 0 self.joystickLeftY = 0 self.communicationProcess = BackgroundProcess(self.communication_loop, parent=self) self.communicationTimer = QtCore.QTimer() self.communicationTimer.setInterval(40) self.communicationTimer.timeout.connect( self.execute_received_board_udp_data) self.init_ui() self.dialog = OverlayDialog(parent=self) self.emptyMessage = Message(None, "", None, None) self.pimMessage = Message(2, self.resources.get("pim_not_inserted"), None, None, _type="info") self.batteryIka10Message = Message( 5, "IKA: " + self.resources.get("battery_10").replace("\\n", "\n"), self.resources.get("ok"), None) self.batteryIka30Message = Message( 6, "IKA: " + self.resources.get("battery_30").replace("\\n", "\n"), self.resources.get("ok"), None) self.batteryUkb10Message = Message( 4, "UKB: " + self.resources.get("battery_10").replace("\\n", "\n"), self.resources.get("ok"), None) self.batteryUkb30Message = Message( 3, "UKB: " + self.resources.get("battery_30").replace("\\n", "\n"), self.resources.get("ok"), None) self.batteryIka10Message.success = self.set_empty_message self.batteryIka30Message.success = self.set_empty_message self.batteryUkb10Message.success = self.set_empty_message self.batteryUkb30Message.success = self.set_empty_message # self.motionDetectionMessage = Message(5, self.resources.get("motion_detected"), # self.resources.get("ok"), None) self.screenShotMessage = Message( 0, self.resources.get("screenshot_taken"), None, None) self.disconnectedMessage = Message(1, self.resources.get("disconnected"), None, None, _type="error") self.config() self.communicationProcess.start() self.communicationTimer.start()
def getMGRSZone(lat, lon, feature, parent): m = mgrs.MGRS() return m.toMGRS(lat, lon).decode('UTF-8')