def map(request, fName, kOsa): mapUrl = 'https://nominatim.openstreetmap.org/?addressdetails=1&q=' + fName + '+' + kOsa + '&format=json&limit=1' response = requests.get(mapUrl) data = response.json() lat = [] lon = [] if data == []: print("Kenttaa ei loytynyt kartalta") return redirect('api') else: for field in data: lat = field['lat'] lon = field['lon'] # https://openrouteservice-py.readthedocs.io/en/latest/ myLocation = geocoder.ip('me').latlng coords = ((myLocation[1], myLocation[0]), (lon, lat)) client = openrouteservice.Client(key='') # Specify your personal API key routes = client.directions(coords) geometry = routes['routes'][0]['geometry'] #Geometriatiedot decoded = convert.decode_polyline( geometry) #Hakee 'coordinates': [[lon, lan][lon,lan] yms...] route = decoded['coordinates'] #Lista koordinaateista for point in route: point.reverse() # [lon, lat] -> [lat, lon] return render( request, 'sportFields/map.html', { 'lat': lat, 'lon': lon, 'fName': fName, 'route': route, 'myLocation': myLocation })
def __init__(self, id, name, lat, long, cometido, cuerpo, nueva): self.id = id # instance variable unique to each instance self.name = name # instance variable unique to each instance self.latitud = lat self.longitud = long self.cometido = cometido longrand = round(random.uniform(-3.661257, -3.607165), 6) latrand = round(random.uniform(40.507342, 40.561603), 6) coords = ((self.longitud, self.latitud), (longrand, latrand)) decoded = [] try: geometry = client.directions(coords)['routes'][0]['geometry'] decoded = convert.decode_polyline(geometry) except: print(str(name) + " FALLO EL GEOMETRY") if nueva == True: addtarea( "INSERT INTO lugares (geom, name, cuerpo, tipo, direccion, cometido) VALUES (ST_GeomFromText('POINT(" + str(long) + " " + str(lat) + ")',4326),'" + str(name) + "', '" + str(cuerpo) + "', '" + str(self.rol) + "', 0, '" + str(cometido) + "');") self.contador = self.contador + 1 mensajes.append([ len(mensajes), current_date_format(), "Patrulla " + self.name + " ha iniciado el servicio." ]) self.hilo = threading.Thread(target=patrullar, args=(self, decoded, self.contador, cometido, 0)) self.hilo.setDaemon(True) self.hilo.start()
def ORS_query_directions(query, profile='driving-car', _id=0, geometry=True): ''' start (class point) end (class point) profile= ["driving-car", "driving-hgv", "foot-walking","foot-hiking", "cycling-regular", "cycling-road","cycling-mountain", "cycling-electric",] ''' ORS_client = start_ORS_client() coord = [query.start_point, query.end_point] ORS_step = ORS_client.directions( coord, profile=profile, instructions=False, geometry=geometry, ) geojson = convert.decode_polyline(ORS_step['routes'][0]['geometry']) step = journey_step(_id, _type=ORS_profile(profile), label=profile, distance_m=ORS_step['routes'][0]['summary']['distance'], duration_s=ORS_step['routes'][0]['summary']['duration'], price_EUR=[0], gCO2=0, geojson=geojson, ) return step
def test_polyline_decode_3d(self): syd_mel_route = (r"mlqlHat`t@OiACMvAs@HCPGJ?JAJBRFTRLJPNHDNDJ" "@D?fACRAZCPAb@AF?HAfBQJEDAn@QFC@QD_@@QFe@Bg" "@@KBy@?M@a@@q@?iE?C?OGgAkEwUQ{@c@gBQeAYeCIe" "AWmDAIImACUOyBIeAC}@Ey@?QLC@_@@KBiAVmDF]Ni@" "Zu@RYBA^_@~A{A`Ai@JCPGf@Qf@]X_@BMAMIKuBTI?G" "E?A?ADOnCsB\c@DGDIl@sAJUFMBGJUP[DCD@DP@l@?R" "?h@Bx@PnAAl@?BAFc@rAAB?@BRHBFEN[FQFQRg@Rw@J" "g@Ny@DUDOJe@N_ADm@BkBGcC@s@Du@l@eEZgBP_AHe@" "He@Fc@RuATaA?SCWAGIOQS[Qu@Ym@C}@R{@`@m@p@Wj" "@]nAGBE?KGAE?E?KVcB`@eB^mAn@uALUJSj@y@fA}@f" "@k@BGHM^k@r@qAHSLU^i@bA_Af@q@PYFKHIHCJ?RLFN" "XjAj@tDj@rERzBLzCHp@xAdKLf@RXTDNEBCFGDEDE@G" "@GDKBGRc@Xi@N[JUf@u@l@o@f@c@h@]XMfQ}D|EcAlA" "ORIJQ?C?CAUKOSGwAMa@M_EsBcBqA_A{@k@q@sCcEi@" "gAWo@[gAYyAMy@y@aNMyAc@uDS_As@uBMc@Ig@SeBKc" "@Uy@AI@A]GGCMIiCmAGCWMqAk@") points = convert.decode_polyline(syd_mel_route, True)['coordinates'] self.assertEqual(len(points[0]), 3) self.assertAlmostEqual(8.69201, points[0][0], places=5) self.assertAlmostEqual(49.410151, points[0][1], places=5) self.assertAlmostEqual(0.1, points[0][2], places=2) self.assertAlmostEqual(8.69917, points[-1][0], places=5) self.assertAlmostEqual(49.41868, points[-1][1], places=5) self.assertAlmostEqual(12.5, points[-1][2], places=2)
def list_trajet(coords): """Cette fonction permet de générer une liste avec l'itinéraire du trajet entre les deux points donnés en entrée""" coords = ((coords[0][1], coords[0][0]), (coords[1][1], coords[1][0])) geometry = client.directions(coords)['routes'][0]['geometry'] decoded = convert.decode_polyline(geometry) list_position = decoded['coordinates'] return (list_position)
def confirmSim(): print("Inside Confirm!") req = eval(request.data) coords = ((req["source_long"], req["source_lat"]), (req["dest_long"], req["dest_lat"])) client = openrouteservice.Client( key=api_key) # Specify your personal API key # decode_polyline needs the geometry only while (True): try: geometry = client.directions(coords)['routes'][0]['geometry'] break except Exception as e: print(e) pass global decoded decoded = convert.decode_polyline(geometry) decoded = decoded['coordinates'] for i in decoded: i[0], i[1] = i[1], i[0] closest_car = get_closest_distance(req['source_lat'], req['source_long'], 5) for i in closest_car[0]: i[0], i[1] = i[1], i[0] print(closest_car) global obj obj = car_state(closest_car[2], closest_car[0]) return "", 200
def test_polyline_decode_2d(self): syd_mel_route = (r"u`rgFswjpAKD") points = convert.decode_polyline(syd_mel_route, False)['coordinates'] self.assertEqual(len(points[0]), 2) self.assertAlmostEqual([13.3313, 38.10843], points[0], places=5) self.assertAlmostEqual([13.33127, 38.10849], points[1], places=5)
def ORS_query_directions(query, profile='driving-car', toll_price=True, _id=0, geometry=True): ''' start (class point) end (class point) profile= ["driving-car", "driving-hgv", "foot-walking","foot-hiking", "cycling-regular", "cycling-road","cycling-mountain", "cycling-electric",] ''' ORS_client = start_ORS_client() coord = [query.start_point[::-1], query.end_point[::-1]] # WARNING it seems that [lon,lat] are not in the same order than for other API. try: ORS_step = ORS_client.directions( coord, profile=profile, instructions=False, geometry=geometry, options={'avoid_features': ['ferries']}, ) except: return None geojson = convert.decode_polyline(ORS_step['routes'][0]['geometry']) local_distance = ORS_step['routes'][0]['summary']['distance'] local_emissions = co2_emissions.calculate_co2_emissions(constants.TYPE_COACH, constants.DEFAULT_CITY, constants.DEFAULT_FUEL, constants.DEFAULT_NB_SEATS, constants.DEFAULT_NB_KM) * \ constants.DEFAULT_NB_PASSENGERS * local_distance step = tmw.Journey_step(_id, _type=ORS_profile(profile), label=profile, distance_m=local_distance, duration_s=ORS_step['routes'][0]['summary']['duration'], price_EUR=[ORS_gas_price(ORS_step['routes'][0]['summary']['distance'])], gCO2=local_emissions, geojson=geojson, departure_date=query.departure_date ) # Correct arrival_date based on departure_date step.arrival_date = (step.departure_date + timedelta(seconds=step.duration_s)) # Add toll price (optional) step = ORS_add_toll_price(step) if toll_price else step ors_journey = tmw.Journey(0, departure_date=query.departure_date, arrival_date=step.arrival_date, steps=[step]) # Add category category_journey = list() for step in ors_journey.steps: if step.type not in [constants.TYPE_TRANSFER, constants.TYPE_WAIT]: category_journey.append(step.type) ors_journey.category = list(set(category_journey)) ors_journey.update() ors_journey.arrival_date = ors_journey.departure_date + timedelta(seconds=ors_journey.total_duration) return ors_journey
def getcoordinates(coord): geometry = client.directions(coords)['routes'][0]['geometry'] decoded = convert.decode_polyline(geometry) global coordinates coordinates = decoded['coordinates'] old_time = datetime.datetime.now() global totalDistance totalDistance = 0 start(coord)
def ruta(self, lat, long, contador, cometido, idpatrus): self.contador = contador self.cometido = cometido coords = ((self.longitud, self.latitud), (long, lat)) print(coords) geometry = client.directions(coords)['routes'][0]['geometry'] decoded = convert.decode_polyline(geometry) self.contador = self.contador + 1 addtarea("update lugares SET cometido = '" + str(cometido) + "' WHERE id = '" + str(self.id) + "';") self.hilo = threading.Thread( target=patrullar, args=(self, decoded, self.contador, cometido, idpatrus), ) self.hilo.start()
def search(): req = eval(request.data) geolocator = Nominatim() while (True): try: source = geolocator.geocode(req['source']) dest = geolocator.geocode(req['destination']) break except: pass print(source.latitude, source.longitude) print(dest.latitude, dest.longitude) i = 0 num_cars = 0 print("HELLO") while (num_cars <= 5): i += 0.5 num_cars, cars = get_num_cars(source.latitude, source.longitude, i) print("The Number of cars is: ", num_cars) coords = ((source.longitude, source.latitude), (dest.longitude, dest.latitude)) client = openrouteservice.Client( key=api_key) # Specify your personal API key # decode_polyline needs the geometry only while (True): try: geometry = client.directions(coords)['routes'][0]['geometry'] break except: pass decoded = convert.decode_polyline(geometry) decoded = decoded['coordinates'] for i in decoded: i[0], i[1] = i[1], i[0] return { "source_lat": source.latitude, "source_long": source.longitude, "dest_lat": dest.latitude, "dest_long": dest.longitude, "graph": plot_cars(source, cars, decoded) }
def get_paths(df): path_list = [] for index, row in df.iterrows(): coords = [(row['plo'], row['pla']), (row['maplong'], row['maplat'])] print(coords) client = openrouteservice.Client( key='5b3ce3597851110001cf6248c196e442e9f148a9a1863fa5c168e7bc') geometry = client.directions(coords)['routes'][0]['geometry'] decoded = convert.decode_polyline(geometry) reverse = [(y, x) for x, y in decoded['coordinates']] path_list.append(reverse) print(index) return path_list
def test_polyline_decode(self): syd_mel_route = ( r"mtkeHuv|q@~@VLHz@\PR|@hBt@j@^n@L\NjALv@Jh@NXi@zBm@jC" "KTy@z@qAhBa@\[Ne@DgCc@i@?[Ty@hAi@zASRi@R}@H_@N[b@kAd" "Cy@`Au@d@eA|@q@h@WRe@PYHYBqADgAAcAL_A^w@~@q@`@w@Zw@C" "m@K[PeA|Aa@p@g@fAiAhBuAv@]VU^k@xAUXe@TqATy@V}@f@_@VO" "\Mb@[fBe@|@Mp@WbCgClKSdAq@Rm@?g@WYg@G[[}Bk@qBy@wDUm@" "w@}@q@}A]o@k@y@kAjC_AjC_ApCe@z@i@j@q@f@[NsAp@u@T}A\w" "ATU?WCeBm@q@MwAGUCg@SMaAi@mDQm@K}@Mq@u@mAc@i@c@Ys@[W" "W_@q@e@a@cA_@w@E{BHmBXqBkBsA}@{Ao@iAB{@QYSi@qCUy@Ee@" "@SDWbA_BLKLAVNb@r@J@HEHK?]k@iDe@w@COAWBUh@qBDc@?c@Q{" "BGa@MQKCOBgA\{@AKEs@Wq@i@q@{@s@gAk@kA]g@g@_@I]??k@i@" "yBkEa@}@W}@WkCUqC?_@Hg@ZqABg@Gm@YoAEgAMq@@jAB|CC`@{@rACH") points = convert.decode_polyline(syd_mel_route)['coordinates'] self.assertAlmostEqual(8.344268, points[0][0], places=5) self.assertAlmostEqual(48.233826, points[0][1], places=5) self.assertAlmostEqual(8.343433, points[-1][0], places=5) self.assertAlmostEqual(48.263552, points[-1][1], places=5)
def calcroute(p1lat, p1lng, p2lat, p2lng, problems): url = "https://api.openrouteservice.org/v2/directions/cycling-regular" problemsArray = problems.split(";") centerarray = [] for p in problemsArray: if (',' in p): lat = p.split(",")[0] lng = p.split(",")[1] centerarray.append([lat, lng]) body = { "coordinates": [[p1lat, p1lng], [p2lat, p2lng]], "elevation": "true", "extra_info": ["steepness"], "geometry_simplify": "false", "instructions": "true", "instructions_format": "html", "language": "pt", "options": { 'avoid_polygons': getexpandedareas(centerarray), "avoid_features": ["ferries", "steps", "fords"], "profile_params": { "weightings": { "steepness_difficulty": 1 } } }, "units": "m", "continue_straight": "true", "geometry": "true" } headers = { 'Accept': 'application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8', 'Authorization': '5b3ce3597851110001cf6248b092059e58f0474c88618af7252a3db9' } # sending get request and saving the response as response object r = requests.post(url=url, json=body, headers=headers) print(r.json()) geometry = r.json()['routes'][0]['geometry'] routes = convert.decode_polyline(geometry, True) return routes
def plot_route(myLat,myLon,closestLat,closestLon): """ Background: This function will return all of the paths / routes in latitudes and longitudes in between our starting and ending trip points. Inputs: myLat: the user's latitude coordinates myLon: the user's longitude coordinates closestLat: the closest station's latitude coordinates closestLon: the closest station's longitude coordinates Outputs: reverse: A list of lat long tuples for each trip. """ coords = ((myLon,myLat),(closestLon,closestLat)) try: #Specify your personal API key client = openrouteservice.Client(key={{INSERT YOUR API KEY}}) geometry = client.directions(coords)['routes'][0]['geometry'] decoded = convert.decode_polyline(geometry) # We need to reverse the long / lat output from results so that we can graph lat / long reverse = [(y, x) for x, y in decoded['coordinates']] # print(reverse) except: # print('Api limit reached') reverse = None return reverse
def get_closest_distance(lat, long, num): a = get_cars() l1 = [] for i in a: l1.append([haversine(lat, long, i[0], i[1]), i[2], [i[0], i[1]]]) l2 = sorted(l1, key=lambda val: val[0]) num = len(l2) if len(l2) < num else num min_distance = None answer = None client = openrouteservice.Client(key=api_key) for i in range(num): coords = ((l2[i][2][1], l2[i][2][0]), (long, lat)) while (True): try: result = client.directions(coords) geometry = result['routes'][0]['geometry'] break except Exception as e: print(e) pass decoded = convert.decode_polyline(geometry) print(decoded) print(result['routes'][0]['summary']['duration']) distance = result['routes'][0]['summary']['duration'] if min_distance is None: min_distance = distance answer = [ decoded['coordinates'], l2[i][1], [l2[i][2][0], l2[i][2][1]] ] elif distance < min_distance: min_distance = distance answer = [ decoded['coordinates'], l2[i][1], [l2[i][2][0], l2[i][2][1]] ] print("\n") return answer
def processAlgorithm(self, parameters, context, feedback): ''' Here is where the processing itself takes place. ''' from openrouteservice.convert import decode_polyline import pickle # Define data-storage classes for Sites and Counties # TODO: Add `assert`ions for @*.setter definitions (infested->bool, etc) class Site(): ''' Site object; contains information for monitoring locations. Site(self, lat, lon[, pH, pHDate, calcium, calciumDate, percentClean, habitability, attractiveness, initInfested]) -> Site object ''' def __init__(self, lat, lon, pH=None, calcium=None, attractiveness=1, initInfested=False, habitability=0.): self._lat = lat self._lon = lon self._pH = pH self._calcium = calcium self._attractiveness = attractiveness self._initInfested = initInfested self._habitability = habitability @property def lat(self): return self._lat @property def lon(self): return self._lon @property def pH(self): return self._pH @property def calcium(self): return self._calcium @property def attractiveness(self): return self._attractiveness @property def initInfested(self): return self._initInfested @property def infested(self): return self._infested def infest(self): if self._habitability > 0: self._infested = True def resetInfested(self): self._infested = self._initInfested @property def habitability(self): return self._habitability @habitability.setter def habitability(self, new_hab): self._habitability = new_hab class County(): ''' County object; contains information for counties. County(self, lat, lon[, boats]) -> County object ''' def __init__(self, lat, lon, boats): self._lat = lat self._lon = lon self._boats = boats @property def lat(self): return self._lat @property def lon(self): return self._lon @property def boats(self): return self._boats class State(): ''' Border object; contains information for border entry points. Border(self, lat, lon, states) -> Border object where "states" is a list of state names, locations, and boats. ''' def __init__(self, lat, lon, boats, infested, border): self._lat = lat self._lon = lon self._boats = boats self._infested = infested self._border = border @property def lat(self): return self._lat @property def lon(self): return self._lon @property def boats(self): return self._boats @property def infested(self): return self._infested @property def border(self): return self._border # Define habitability function def habitability(pH, calcium, lowpH, lowCalc): """ Returns the habitability of the site, based on pH and calcium levels. Result is a probability expressed as a decimal, or None if no data exists. """ if (pH == None) and (calcium == None): # Cannot compute risk return None elif pH == None: # Compute risk based only on calcium if 0 <= calcium < lowCalc: CaFactor = 0 elif lowCalc <= calcium: CaFactor = (-1 / (calcium - lowCalc + 1)) + 1 else: return None return CaFactor elif calcium == None: # Compute risk based only on pH if 0 <= pH < lowpH: pHFactor = 0 elif lowpH <= pH: pHFactor = (-1 / (10 * (pH - lowpH) + 1)) + 1 else: return None return pHFactor else: # Compute risk based on calcium and pH # Calcium factor if 0 <= calcium < lowCalc: CaFactor = 0 elif lowCalc <= calcium: CaFactor = (-1 / (calcium - lowCalc + 1)) + 1 else: CaFactor = 1 # pH factor if 0 <= pH < lowpH: pHFactor = 0 elif lowpH <= pH: pHFactor = (-1 / (10 * (pH - lowpH) + 1)) + 1 else: pHFactor = 1 return pHFactor * CaFactor # Retrieve parameters: feedback.setProgressText('Retrieving input parameters...') # Pickled routes file pickledFileName = self.parameterAsFile( parameters, self.ROUTES, context) # Pickled border routes file stateFileName = self.parameterAsFile( parameters, self.STATE_ROUTES, context) # Number of Monte Carlo loops to run MCLoops = self.parameterAsInt( parameters, self.MC_LOOPS, context) # Number of years to simulate years = self.parameterAsInt( parameters, self.YEARS, context) # Proportion of all boats assumed to be decontaminated propCleaned = self.parameterAsDouble( parameters, self.PROP_DECONT, context) # Proportion of infested out-of-state boats assumed to be contaminated infProp = self.parameterAsDouble( parameters, self.INF_PROP, context) # Proportion of uninfested out-of-state boats assumed to be contaminated uninfProp = self.parameterAsDouble( parameters, self.UNINF_PROP, context) # Model-specific variables: lowCalc = self.parameterAsDouble(parameters, self.LOW_CALC, context) lowpH = self.parameterAsDouble(parameters, self.LOW_PH, context) settleRisk = self.parameterAsDouble(parameters, self.SETTLE_RISK, context) tripsPerYear = self.parameterAsInt(parameters, self.TRIPS_PER_YEAR, context) # Internalize pickled counties, borders, sites, and routes # Format: # Counties: name str, lat float, lon float, boats int # States: name str, lat float, lon float, boats int, # border list [name str, lat float, lon float] # Sites: name str, lat float, lon float, pH float|None, # calcium float|None, attractiveness int, initInfested bool feedback.setProgressText('Retrieving pickled routes from file...') # For counties: with open(pickledFileName, 'rb') as pickledFile: (countiesList, sitesList, routeMatrix) = pickle.load(pickledFile) del pickledFile # For outside states: with open(stateFileName, 'rb') as stateFile: (statesList, stSitesList, stRouteMatrix) = pickle.load(stateFile) del stateFile # Check to be sure routes are present for the same sites in each file if not stSitesList == sitesList: feedback.reportError( 'In-state and out-of-state lakes do not match. Aborting.', fatalError=True) return {None: None} del stSitesList # Convert (name, lat, lon, **info) tuples into native objects counties = dict() for item in countiesList: counties[item[0]] = County(item[1], item[2], item[3]) sites = dict() for item in sitesList: sites[item[0]] = Site(item[1], item[2], item[3], item[4], item[5], item[6]) states = dict() for item in statesList: states[item[0]] = State(item[1], item[2], item[3], item[4], item[5]) del item, countiesList, sitesList, statesList # Begin Processing feedback.pushInfo('Beginning processing') from random import choices from numpy import array, zeros c = zeros([len(counties),len(sites)],dtype=float) cs = zeros([len(states),len(sites)],dtype=float) # Create route polylines feedback.setProgressText('Calculating internal route lengths... '\ '(This could take a while)') for i in range(len(counties)): # Cancellation check if feedback.isCanceled(): return {None: None} # Progress update feedback.setProgress(round(100 * i / (len(counties) - 1))) for j in range(len(sites)): encoded = routeMatrix[i][j] decoded = decode_polyline(encoded) feat = QgsFeature() feat.setGeometry(QgsGeometry.fromPolyline( [QgsPoint(pt[0], pt[1]) for pt in decoded['coordinates']])) # Store feature for later retrieval (to avoid taking a really # long time regenerating feature geometry when creating output) routeMatrix[i][j] = feat # Add distance to array c[i][j] c[i][j] = feat.geometry().length() * 10 # Gives length in km # Route distances are now stored in c[i][j] feedback.setProgressText('Calculating out-of-state route lengths... '\ '(This could take a while)') for i, s in enumerate(states.values()): # Cancellation check if feedback.isCanceled(): return {None: None} # Progress update feedback.setProgress(round(100 * i / (len(states) - 1))) for j in range(len(sites)): encoded = stRouteMatrix[i][j] decoded = decode_polyline(encoded) feat = QgsFeature() # Set geometry, including a straight path to state center feat.setGeometry(QgsGeometry.fromPolyline( [QgsPoint(pt[0], pt[1]) for pt in ( [[s.lon, s.lat]] + decoded['coordinates'])])) # Store feature for later retrieval to save time stRouteMatrix[i][j] = feat # Add distance to array cs[i][j] cs[i][j] = feat.geometry().length() * 10 # Converts to km # Border route distances are now stored in cb[i][j] del encoded, decoded, s # TODO: Pickle routeMatrix in QGIS temp folder to reduce processing # time for future alg runs # Begin Model feedback.setProgressText('Starting Monte Carlo model') feedback.setProgress(0) # Define a model-specific parameter: α = 2 # Calculate habitability values for site in sites.values(): site.habitability \ = habitability(site.pH, site.calcium, lowpH, lowCalc) # Set up arrays # Computed in Model: A = zeros(len(counties),dtype=float) As = zeros(len(states),dtype=float) T = zeros([len(counties),len(sites)],dtype=int) Ts = zeros([len(states),len(sites)],dtype=int) P = zeros(len(counties),dtype=int) t = zeros([MCLoops,years,len(counties),len(sites)],dtype=int) ts = zeros([MCLoops,years,len(states),len(sites)],dtype=int) Q = zeros(len(sites),dtype=int) # Extracted from input: O = zeros(len(counties),dtype=int) Os = zeros(len(states),dtype=int) W = zeros(len(sites),dtype=int) # c has already been set up and populated with distances, as has cs # Results: avgInfest = zeros([years,len(sites)],dtype=float) feedback.pushInfo('Arrays set up') # Set up O[i], Os[i], and W[j] for i, county in enumerate(counties.values()): O[i] = county.boats for i, state in enumerate(states.values()): Os[i] = state.boats for j, site in enumerate(sites.values()): W[j] = site.attractiveness # c has already been set up and populated with distances, as has cs feedback.pushInfo('Computed c[i][j], cs[i][j], O[i], Os[i], and W[j]') # Compute A[i]: balancing factor for i in range(len(counties)): for j in range(len(sites)): A[i] += W[j] * (c[i][j] ** -α) A[i] = 1 / A[i] # Compute As[i]: balancing factor for states for i in range(len(states)): for j in range(len(sites)): As[i] += W[j] * (cs[i][j] ** -α) As[i] = 1 / As[i] # Compute T[i][j]: total boats from county i to lake j for i in range(len(counties)): for j in range(len(sites)): T[i][j] = A[i] * O[i] * W[j] * (c[i][j] ** -α) # Compute Ts[i][j]: total boats from state i to lake j for i in range(len(states)): for j in range(len(sites)): Ts[i][j] = As[i] * Os[i] * W[j] * (cs[i][j] ** -α) feedback.pushInfo('Computed A[i], As[i], T[i][j], and Ts[i][j]') # Begin Model Core and Monte Carlo loop feedback.setProgressText('\nRunning model...') for MCLoop in range(MCLoops): feedback.pushInfo(f'Monte Carlo loop {MCLoop}') # Reset infestation statuses for site in sites.values(): site.resetInfested() # Begin Main Loop for year in range(years): feedback.pushInfo(f'\tYear {year}') # Cancellation check if feedback.isCanceled(): return {None: None} # Progress update feedback.setProgress(int(100 * \ ((MCLoop * years) + year + 1) / (MCLoops * years))) # Compute P[i]: potentially infested boats in county i # Note: This assumes that boats take on the status of the # lakes they visit. I.e. a contaminated boat visiting a # clean lake could contaminate the lake, but the boat # becomes clean. Thus, in a given year, each county always has # the same number of contaminated boats from the same lakes. P.fill(0) for i in range(len(counties)): for j, site in enumerate(sites.values()): if site.infested: P[i] += T[i][j] # Compute t[i][j]: infested boats from county i to lake j for i in range(len(counties)): for j in range(len(sites)): t[MCLoop][year][i][j] \ = A[i] * P[i] * W[j] * (c[i][j] ** -α) # Compute Q[j]: yearly infested boats to j Q.fill(0) for j in range(len(sites)): for i in range(len(counties)): Q[j] += (tripsPerYear - 1) * t[MCLoop][year][i][j] # Add contaminated out-of-state boats to ts for i, state in enumerate(states.values()): # Randomly choose whether each out-of-state boat is # contaminated; store in ts for boat in range(Ts[i][j]): if choices( [1, 0], [(infProp if state.infested else uninfProp), 1 - (infProp if state.infested \ else uninfProp)] )[0] == 1: ts[MCLoop][year][i][j] += 1 # Add ts (contaminated boats from state i to lake j) # to Q[j] Q[j] += ts[MCLoop][year][i][j] # Adjust for decontamination using propCleaned, # stochastically if propCleaned < 1: for j in range(len(sites)): b = Q[j] Q[j] = 0 for i in range(b): if choices( [1, 0], [1 - propCleaned, propCleaned] )[0] == 1: Q[j] += 1 del b # Update infestation states (with stochastic factor) for j, site in enumerate(sites.values()): for boat in range(Q[j]): if choices( [1, 0], [settleRisk * (2 * site.habitability), 1 - (settleRisk * (2 * site.habitability))] )[0] == 1: site.infest() # Update average infestation rate avgInfest[year][j] = (MCLoop * avgInfest[year][j] \ + int(site.infested)) / (MCLoop + 1) # End Main Loop del site, boat # End Monte Carlo loop and Model Core # End Model feedback.pushInfo('Completed Monte Carlo model') # Add field definitions: fields = QgsFields() fList = [QgsField('Origin', QVariant.String), QgsField('Lake', QVariant.String), QgsField('pH', QVariant.Double), QgsField('Calcium', QVariant.Double), QgsField('Habitability', QVariant.Double), QgsField('Attractiveness', QVariant.Int), # Boats on Route fields will go here # Infestation Proportion fields will go here QgsField('Initially Infested', QVariant.Bool), QgsField('Origin Infested', QVariant.Bool), QgsField('Origin Type', QVariant.String)] for n in range(years): fList.insert(n + 7, QgsField(f'Year {n} Infestation Proportion', QVariant.Double)) for n in range(years): fList.insert(n + 6, QgsField(f'Year {n} Boats on Route', QVariant.Double)) for field in fList: fields.append(field) del fList, n # Sink and ID for the route output layer (routeSink, routeSinkID) = self.parameterAsSink( parameters, self.ROUTE_OUTPUT, context, fields, geometryType=QgsWkbTypes.LineString, crs=QgsCoordinateReferenceSystem('EPSG:4326') ) # Add route polylines to route layer feedback.setProgressText('Adding routes to output layer... '\ '(This could take a while)') # Create matrices for average number of boats on routes inStBoats = sum(t) / MCLoops outStBoats = sum(ts) / MCLoops for i, (cName, county) in enumerate(counties.items()): # Progress update feedback.setProgress(round(100 * i / (len(counties) + len(states) - 1))) for j, (sName, site) in enumerate(sites.items()): # Cancellation check if feedback.isCanceled(): return {None: None} feat = routeMatrix[i][j] feat.setFields(fields, initAttributes=True) # Transfer attributes from each site to its feature feat.setAttributes([cName, sName, site.pH, site.calcium, site.habitability, site.attractiveness] + [float(inStBoats[y][i][j]) for y in range(years)] + [float(avgInfest[y][j]) for y in range(years)] + [site.initInfested, None, 'internal county']) routeSink.addFeature(feat) for i, (tName, state) in enumerate(states.items()): # Cancellation check if feedback.isCanceled(): return {None: None} # Progress update feedback.setProgress(round(100 * (len(counties) + i) / (len(counties) + len(states) - 1))) for j, (sName, site) in enumerate(sites.items()): feat = stRouteMatrix[i][j] feat.setFields(fields, initAttributes=True) # Transfer attributes from each site to its feature feat.setAttributes([tName, sName, site.pH, site.calcium, site.habitability, site.attractiveness] + [float(outStBoats[y][i][j]) for y in range(years)] + [float(avgInfest[y][j]) for y in range(years)] + [site.initInfested, state.infested, 'external district']) routeSink.addFeature(feat) del cName, tName, sName, avgInfest, feat routeSink.flushBuffer() # All routes are now in routeSink as polyline features # Cleanup del i, j, site, county, state # TODO: This could be replaced by using a transparent line symbology # Left examples below for creating and setting a renderer # # Set up heatmap renderer # # ^ Set weight for each point from field(s) (research) # rndrr = QgsHeatmapRenderer() # rndrr.setColorRamp(QgsGradientColorRamp( # QColor('transparent'),QColor(227,26,28))) # rndrr.setRadiusUnit(1) # rndrr.setRadius(500) # # # Assign heatmap renderer to extracted vertices layer # QgsProcessingUtils.mapLayerFromString(vertices['OUTPUT'], context # ).setRenderer(rndrr) # End Processing feedback.setProgressText('Processing complete; finishing up...') # Return output layers return {self.ROUTE_OUTPUT: routeSinkID}
coordenadas = [ [-0.2279885, -78.4862021], [-0.2343332, -78.4841716], [-0.2373534, -78.4842575], [-0.2420552, -78.485494], [-0.2447133, -78.4849226], [-0.251262, -78.483007], ] # Las coordenadas deben estar en este orden -> [lon, lat] coordenadasReversadas = list(map(reversar, coordenadas)) datos = { 'coordinates': coordenadasReversadas, } cabeceras = { 'Accept': 'application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8', 'Authorization': API_KEY, 'Content-Type': 'application/json; charset=utf-8' } r = requests.post(url=URL, headers=cabeceras, json=datos) data = r.json() # Las cooredadas del polyline estan codificadas geometria_codificada = data['routes'][0]['geometry'] geometria_descodificada = convert.decode_polyline(geometria_codificada) # Coordenadas para dibujar las lineas # {'type': 'LineString', 'coordinates': [[-78.48619, -0.22798], [-78.48619, -0.22797] ..]} print(geometria_descodificada)
hovertext="próba3", hoverinfo="text", customdata=[[event['description']['intro'], event['info_url']]], hovertemplate='<b>%{customdata[0]}</b><br><br>%{customdata[1]}') # Routes to the listed events are added to the map (red paths) for j in out_event_list: event = eventsapi.get_specific_event(j) print(event) coords = ((24.91438, 60.14947), (event['location']['lon'], event['location']['lat'])) client = openrouteservice.Client( key='5b3ce3597851110001cf62486ec15dbb6fa040b1b964169eebc6824d' ) # Specify your personal API key geometry = client.directions(coords)['routes'][0]['geometry'] coordis = convert.decode_polyline(geometry) xlist = [] ylist = [] for i in coordis['coordinates']: xlist.append(i[0]) ylist.append(i[1]) fig.add_scattermapbox(lat=ylist, lon=xlist, mode="lines", marker=dict(size=20, color="red")) # Plot the map fig.show() # We can make offline version of the output map # plotly.offline.plot(fig, image_filename='Map2', image='svg')
import openrouteservice from openrouteservice import convert import json coords = ((-3.635017,40.540277),(-3.620484,40.534947)) client = openrouteservice.Client(key='5b3ce3597851110001cf6248f2ed7abeb83047e6a74f5b73c4d2758d') # Specify your personal API key # decode_polyline needs the geometry only geometry = client.directions(coords)['routes'][0]['geometry'] decoded = convert.decode_polyline(geometry) print(json.dumps(decoded["coordinates"], indent=4, sort_keys=True))