def _getTimeDistManhattan(fromLocs, toLocs, speedMPS):
    """
	Generate two dictionaries, one for time, another for distance, using Manhattan

	Parameters
	----------
	fromLocs: list, Required
		The start node coordinates in format of [[lat, lon], [lat, lon], ... ]
	toLocs: list, Required
		The End node coordinates in format of [[lat, lon], [lat, lon], ... ]
	speedMPS: float, Required
		A constant speed for calculation

	returns
	-------
	timeSecs: dictionary
		A dictionary for time from nodes to nodes, unit is in [seconds]
	distMeters: dictionary
		A dictionary for distance from nodes to nodes, unit is in [meters]
	
	"""

    distMeters = {}
    timeSecs = {}
    for i in range(len(fromLocs)):
        for j in range(len(toLocs)):
            fromLocsDict = locs2Dict(fromLocs)
            toLocsDict = locs2Dict(toLocs)
            manDist = geoDistance2D(fromLocs[i], (
                fromLocsDict[i]['lat'], toLocsDict[j]['lon'])) + geoDistance2D(
                    (fromLocsDict[i]['lat'], toLocsDict[j]['lon']), toLocs[j])
            distMeters[i, j] = manDist
            timeSecs[i, j] = manDist / speedMPS
    return [timeSecs, distMeters]
Esempio n. 2
0
def mqGetSnapToRoadLatLonBatch(locs, APIkey):
    """
	A function to get snapped latlng for one coordinate using MapQuest

	Parameters
	----------
	locs: list of lists
		The locations to be snapped to road
	APIkey: string, Required
		Enables us to access to MapQuest server

	Returns
	-------
	list of lists
		A list of snapped locations in the format of [[lat, lon], [lat, lon], ...], notice that this function will lost the info of altitude of the locations.
	"""

    maxBatchSize = 100
    numBatches = int(math.ceil(len(locs) / float(maxBatchSize)))
    snapToRoadUrlBase = (
        'http://www.mapquestapi.com/geocoding/v1/batch?key=%s&thumbMaps=false&outFormat=json'
    ) % (APIkey)

    dicLocs = locs2Dict(locs)

    try:
        for batch in range(0, numBatches):
            snapToRoadUrl = snapToRoadUrlBase
            for i in range(maxBatchSize * batch,
                           min(len(locs), maxBatchSize * (batch + 1))):
                snapToRoadUrl += ('&location=%s,%s') % (dicLocs[i]['lat'],
                                                        dicLocs[i]['lon'])
            data = []

            http = urllib3.PoolManager()
            response = http.request('GET', snapToRoadUrl)
            data = json.loads(response.data.decode('utf-8'))

            snapLocs = [[
                data['results'][j]['locations'][0]['latLng']['lat'],
                data['results'][j]['locations'][0]['latLng']['lng']
            ] for j in range(0, len(data['results']))]
    except:
        print(
            "Message: Unable to connect MapQuest, the most common causes are 1) that your computer isn't connected to the network; 2) an invalid key is provided."
        )

    return snapLocs
Esempio n. 3
0
def privGetShapepoints2D(
        odID=1,
        objectID=None,
        modelFile=None,
        startLoc=None,
        endLoc=None,
        startTimeSec=0.0,
        expDurationSec=None,
        routeType='euclidean2D',
        speedMPS=None,
        leafletColor=config['VRV_DEFAULT_LEAFLETARCCOLOR'],
        leafletWeight=config['VRV_DEFAULT_LEAFLETARCWEIGHT'],
        leafletStyle=config['VRV_DEFAULT_LEAFLETARCSTYLE'],
        leafletOpacity=config['VRV_DEFAULT_LEAFLETARCOPACITY'],
        leafletCurveType=config['VRV_DEFAULT_ARCCURVETYPE'],
        leafletCurvature=config['VRV_DEFAULT_ARCCURVATURE'],
        useArrows=True,
        modelScale=config['VRV_DEFAULT_CESIUMMODELSCALE'],
        modelMinPxSize=config['VRV_DEFAULT_CESIUMMODELMINPXSIZE'],
        cesiumColor=config['VRV_DEFAULT_CESIUMPATHCOLOR'],
        cesiumWeight=config['VRV_DEFAULT_CESIUMPATHWEIGHT'],
        cesiumStyle=config['VRV_DEFAULT_CESIUMPATHSTYLE'],
        cesiumOpacity=config['VRV_DEFAULT_CESIUMPATHOPACITY'],
        ganttColor=config['VRV_DEFAULT_GANTTCOLOR'],
        popupText=None,
        dataProvider=None,
        dataProviderArgs=None):

    # Replace backslash
    modelFile = replaceBackslashToSlash(modelFile)

    # Ensure leading slash
    modelFile = addHeadSlash(modelFile)

    try:
        dataProvider = dataProvider.lower()
    except:
        pass

    try:
        routeType = routeType.lower()
    except:
        pass

    if (startLoc != endLoc):
        extras = {}
        if (routeType == 'euclidean2d'):
            [path, time,
             dist] = _eucGetShapepointsTimeDist(startLoc, endLoc, speedMPS,
                                                expDurationSec)
        elif (routeType == 'manhattan'):
            [path, time,
             dist] = _manGetShapepointsTimeDist(startLoc, endLoc, speedMPS,
                                                expDurationSec)
        elif (routeType == 'fastest'
              and dataProviderDictionary[dataProvider] == 'pgrouting'):
            databaseName = dataProviderArgs['databaseName']
            [path, time,
             dist] = pgrGetShapepointsTimeDist(startLoc, endLoc, databaseName)
        elif (routeType == 'fastest'
              and dataProviderDictionary[dataProvider] == 'osrm-online'):
            [path, time, dist] = osrmGetShapepointsTimeDist(startLoc, endLoc)
        elif (routeType in ['fastest', 'shortest', 'pedestrian']
              and dataProviderDictionary[dataProvider] == 'mapquest'):
            APIkey = dataProviderArgs['APIkey']
            [path, time,
             dist] = mqGetShapepointsTimeDist(startLoc, endLoc, routeType,
                                              APIkey)
        elif (routeType
              in ['fastest', 'pedestrian', 'cycling', 'truck', 'wheelchair']
              and dataProviderDictionary[dataProvider] == 'ors-online'):
            APIkey = dataProviderArgs['APIkey']
            if ('requestExtras' in dataProviderArgs.keys()):
                requestExtras = dataProviderArgs['requestExtras']
            else:
                requestExtras = True
            [path, extras, time,
             dist] = orsGetShapepointsTimeDist(startLoc, endLoc, routeType,
                                               APIkey, requestExtras)
        elif (routeType in ['fastest', 'pedestrian', 'cycling', 'truck']
              and dataProviderDictionary[dataProvider] == 'ors-local'):
            port = dataProviderArgs['port']
            if ('requestExtras' in dataProviderArgs.keys()):
                requestExtras = dataProviderArgs['requestExtras']
            else:
                requestExtras = True
            [path, extras, time,
             dist] = orsLocalGetShapepointsTimeDist(startLoc, endLoc,
                                                    routeType, port,
                                                    requestExtras)
        else:
            return

        # Check if the original point is too far away from the actual start point of the shapepoints from query
        distOri = geoDistance2D(startLoc, path[0])
        if (distOri >= config['VRV_DEFAULT_DISTANCE_ERROR_TOLERANCE']
            ):  # Go back to 10m after testing
            print(
                "Message: The origin point (lat: %s, lon: %s) is %.1f meters away from the road. You might find a gap between the origin point and the route."
                % (startLoc[0], startLoc[1], distOri))

        # Check if the actual end point is too far away from destination point
        distDes = geoDistance2D(path[-1], endLoc)
        if (distDes >= config['VRV_DEFAULT_DISTANCE_ERROR_TOLERANCE']
            ):  # Go back to 10m after testing
            print(
                "Message: The destination point (lat: %s, lon: %s) is %.1f meters away from the road. You might find a gap between destination point and the route."
                % (endLoc[0], endLoc[1], distDes))

        # convert distance to accumulated distance
        accDist = []
        accDist.append(0)
        for i in range(1, len(dist)):
            accDist.append(accDist[i - 1] + dist[i])

        # If `expDurationSec` is provided, override `speedMPS` and datasource, otherwise, if `speedMPS` is provided, override datasource
        if (expDurationSec != None):
            [newTime, newDist] = distributeTimeDist(path, expDurationSec)
            time = newTime
            dist = newDist
        elif (speedMPS != None and expDurationSec == None):
            newExpDurationSec = accDist[len(accDist) - 1] / speedMPS
            [newTime, newDist] = distributeTimeDist(path, newExpDurationSec)
            time = newTime
            dist = newDist

        # convert time to accumulated time
        accTime = []
        accTime.append(startTimeSec)
        for i in range(1, len(dist)):
            accTime.append(accTime[i - 1] + time[i])

        # For maintainability, convert locs into dictionary
        dicPath = locs2Dict(path)

        # shapepoint dataframe
        assignments = privInitDataframe('Assignments')

        # generate assignments
        for i in range(1, len(path)):
            if (i - 1) in extras:
                startElev = extras[i -
                                   1]['elev'] if 'elev' in extras[i -
                                                                  1] else None
                wayname = extras[i]['wayname'] if 'wayname' in extras[
                    i] else None
                waycategory = extras[i][
                    'waycategory'] if 'waycategory' in extras[i] else None
                surface = extras[i]['surface'] if 'surface' in extras[
                    i] else None
                waytype = extras[i]['waytype'] if 'waytype' in extras[
                    i] else None
                steepness = extras[i]['steepness'] if 'steepness' in extras[
                    i] else None
                tollway = extras[i]['tollway'] if 'tollway' in extras[
                    i] else None
            else:
                startElev = None
                wayname = None
                waycategory = None
                surface = None
                waytype = None
                steepness = None
                tollway = None

            if i in extras:
                endElev = extras[i]['elev'] if 'elev' in extras[i] else None
            else:
                endElev = None

            assignments = assignments.append(
                {
                    'odID': odID,
                    'objectID': objectID,
                    'modelFile': modelFile,
                    'startTimeSec': accTime[i - 1],
                    'startLat': dicPath[i - 1]['lat'],
                    'startLon': dicPath[i - 1]['lon'],
                    'startAltMeters': dicPath[i - 1]['alt'],
                    'endTimeSec': accTime[i],
                    'endLat': dicPath[i]['lat'],
                    'endLon': dicPath[i]['lon'],
                    'endAltMeters': dicPath[i]['alt'],
                    'leafletColor': leafletColor,
                    'leafletWeight': leafletWeight,
                    'leafletStyle': leafletStyle,
                    'leafletCurveType': leafletCurveType,
                    'leafletCurvature': leafletCurvature,
                    'useArrows': useArrows,
                    'leafletOpacity': leafletOpacity,
                    'modelScale': modelScale,
                    'modelMinPxSize': modelMinPxSize,
                    'cesiumColor': stripCesiumColor(cesiumColor),
                    'cesiumWeight': cesiumWeight,
                    'cesiumStyle': cesiumStyle,
                    'cesiumOpacity': cesiumOpacity,
                    'ganttColor': ganttColor,
                    'popupText': popupText,
                    'startElevMeters': startElev,
                    'endElevMeters': endElev,
                    'wayname': wayname,
                    'waycategory': waycategory,
                    'surface': surface,
                    'waytype': waytype,
                    'steepness': steepness,
                    'tollway': tollway
                },
                ignore_index=True)
    else:
        # For maintainability, convert locs into dictionary
        dicStartLoc = loc2Dict(startLoc)

        if (dataProviderDictionary[dataProvider] == 'ors-online'):
            [[lat, lon, elev]] = orsGetElevation([startLoc],
                                                 dataProviderArgs['APIkey'])
        else:
            elev = None

        assignments = privInitDataframe('Assignments')
        assignments = assignments.append(
            {
                'odID':
                odID,
                'objectID':
                objectID,
                'modelFile':
                modelFile,
                'startTimeSec':
                startTimeSec,
                'startLat':
                dicStartLoc['lat'],
                'startLon':
                dicStartLoc['lon'],
                'startAltMeters':
                dicStartLoc['alt'],
                'endTimeSec':
                expDurationSec + startTimeSec if
                (expDurationSec is not None) else startTimeSec,
                'endLat':
                dicStartLoc['lat'],
                'endLon':
                dicStartLoc['lon'],
                'endAltMeters':
                dicStartLoc['alt'],
                'leafletColor':
                leafletColor,
                'leafletWeight':
                leafletWeight,
                'leafletStyle':
                leafletStyle,
                'leafletCurveType':
                leafletCurveType,
                'leafletCurvature':
                leafletCurvature,
                'useArrows':
                useArrows,
                'leafletOpacity':
                leafletOpacity,
                'modelScale':
                modelScale,
                'modelMinPxSize':
                modelMinPxSize,
                'cesiumColor':
                stripCesiumColor(cesiumColor),
                'cesiumWeight':
                cesiumWeight,
                'cesiumStyle':
                cesiumStyle,
                'cesiumOpacity':
                cesiumOpacity,
                'ganttColor':
                ganttColor,
                'popupText':
                popupText,
                'startElevMeters':
                elev,
                'endElevMeters':
                elev,
                'wayname':
                None,
                'waycategory':
                None,
                'surface':
                None,
                'waytype':
                None,
                'steepness':
                None,
                'tollway':
                None
            },
            ignore_index=True)

    return assignments
Esempio n. 4
0
def privGetShapepoints2D(odID=1,
                         objectID=None,
                         modelFile=None,
                         startLoc=None,
                         endLoc=None,
                         startTimeSec=0.0,
                         expDurationSec=None,
                         routeType='euclidean2D',
                         speedMPS=None,
                         leafletColor=VRV_DEFAULT_LEAFLETARCCOLOR,
                         leafletWeight=VRV_DEFAULT_LEAFLETARCWEIGHT,
                         leafletStyle=VRV_DEFAULT_LEAFLETARCSTYLE,
                         leafletOpacity=VRV_DEFAULT_LEAFLETARCOPACITY,
                         useArrows=True,
                         modelScale=VRV_DEFAULT_CESIUMMODELSCALE,
                         modelMinPxSize=VRV_DEFAULT_CESIUMMODELMINPXSIZE,
                         cesiumColor=VRV_DEFAULT_CESIUMPATHCOLOR,
                         cesiumWeight=VRV_DEFAULT_CESIUMPATHWEIGHT,
                         cesiumStyle=VRV_DEFAULT_CESIUMPATHSTYLE,
                         cesiumOpacity=VRV_DEFAULT_CESIUMPATHOPACITY,
                         dataProvider=None,
                         dataProviderArgs=None):

    # Replace backslash
    modelFile = replaceBackslashToSlash(modelFile)

    try:
        dataProvider = dataProvider.lower()
    except:
        pass

    try:
        routeType = routeType.lower()
    except:
        pass

    if (startLoc != endLoc):
        if (routeType == 'euclidean2d'):
            [path, time,
             dist] = _eucGetShapepointsTimeDist(startLoc, endLoc, speedMPS,
                                                expDurationSec)
        elif (routeType == 'manhattan'):
            [path, time,
             dist] = _manGetShapepointsTimeDist(startLoc, endLoc, speedMPS,
                                                expDurationSec)
        elif (routeType == 'fastest'
              and dataProviderDictionary[dataProvider] == 'pgrouting'):
            databaseName = dataProviderArgs['databaseName']
            [path, time,
             dist] = pgrGetShapepointsTimeDist(startLoc, endLoc, databaseName)
        elif (routeType == 'fastest'
              and dataProviderDictionary[dataProvider] == 'osrm-online'):
            [path, time, dist] = osrmGetShapepointsTimeDist(startLoc, endLoc)
        elif (routeType in ['fastest', 'shortest', 'pedestrian']
              and dataProviderDictionary[dataProvider] == 'mapquest'):
            APIkey = dataProviderArgs['APIkey']
            [path, time,
             dist] = mqGetShapepointsTimeDist(startLoc, endLoc, routeType,
                                              APIkey)
        elif (routeType in ['fastest', 'pedestrian', 'cycling', 'truck']
              and dataProviderDictionary[dataProvider] == 'ors-online'):
            APIkey = dataProviderArgs['APIkey']
            [path, time,
             dist] = orsGetShapepointsTimeDist(startLoc, endLoc, routeType,
                                               APIkey)
        else:
            return

        # Check if the original point is too far away from the actual start point of the shapepoints from query
        distOri = geoDistance2D(startLoc, path[0])
        if (distOri >= VRV_DEFAULT_DISTANCE_ERROR_TOLERANCE
            ):  # Go back to 10m after testing
            print(
                "Message: The origin point (lat: %s, lon: %s) is %.1f meters away from the road. You might find a gap between the origin point and the route."
                % (startLoc[0], startLoc[1], distOri))

        # Check if the actual end point is too far away from destination point
        distDes = geoDistance2D(path[-1], endLoc)
        if (distDes >= VRV_DEFAULT_DISTANCE_ERROR_TOLERANCE
            ):  # Go back to 10m after testing
            print(
                "Message: The destination point (lat: %s, lon: %s) is %.1f meters away from the road. You might find a gap between destination point and the route."
                % (endLoc[0], endLoc[1], distDes))

        # convert distance to accumulated distance
        accDist = []
        accDist.append(0)
        for i in range(1, len(dist)):
            accDist.append(accDist[i - 1] + dist[i])

        # If `expDurationSec` is provided, override `speedMPS` and datasource, otherwise, if `speedMPS` is provided, override datasource
        if (expDurationSec != None):
            [newTime, newDist] = distributeTimeDist(path, expDurationSec)
            time = newTime
            dist = newDist
        elif (speedMPS != None and expDurationSec == None):
            newExpDurationSec = accDist[len(accDist) - 1] / speedMPS
            [newTime, newDist] = distributeTimeDist(path, newExpDurationSec)
            time = newTime
            dist = newDist

        # convert time to accumulated time
        accTime = []
        accTime.append(startTimeSec)
        for i in range(1, len(dist)):
            accTime.append(accTime[i - 1] + time[i])

        # For maintainability, convert locs into dictionary
        dicPath = locs2Dict(path)

        # shapepoint dataframe
        assignments = initDataframe('Assignments')

        # generate assignments
        for i in range(1, len(path)):
            assignments = assignments.append(
                {
                    'odID': odID,
                    'objectID': objectID,
                    'modelFile': modelFile,
                    'startTimeSec': accTime[i - 1],
                    'startLat': dicPath[i - 1]['lat'],
                    'startLon': dicPath[i - 1]['lon'],
                    'startAltMeters': dicPath[i - 1]['alt'],
                    'endTimeSec': accTime[i],
                    'endLat': dicPath[i]['lat'],
                    'endLon': dicPath[i]['lon'],
                    'endAltMeters': dicPath[i]['alt'],
                    'leafletColor': leafletColor,
                    'leafletWeight': leafletWeight,
                    'leafletStyle': leafletStyle,
                    'useArrows': useArrows,
                    'leafletOpacity': leafletOpacity,
                    'modelScale': modelScale,
                    'modelMinPxSize': modelMinPxSize,
                    'cesiumColor': cesiumColor,
                    'cesiumWeight': cesiumWeight,
                    'cesiumStyle': cesiumStyle,
                    'cesiumOpacity': cesiumOpacity
                },
                ignore_index=True)
    else:
        # For maintainability, convert locs into dictionary
        dicStartLoc = loc2Dict(startLoc)

        assignments = initDataframe('Assignments')
        assignments = assignments.append(
            {
                'odID':
                odID,
                'objectID':
                objectID,
                'modelFile':
                modelFile,
                'startTimeSec':
                startTimeSec,
                'startLat':
                dicStartLoc['lat'],
                'startLon':
                dicStartLoc['lon'],
                'startAltMeters':
                dicStartLoc['alt'],
                'endTimeSec':
                expDurationSec + startTimeSec if
                (expDurationSec is not None) else startTimeSec,
                'endLat':
                dicStartLoc['lat'],
                'endLon':
                dicStartLoc['lon'],
                'endAltMeters':
                dicStartLoc['alt'],
                'leafletColor':
                leafletColor,
                'leafletWeight':
                leafletWeight,
                'leafletStyle':
                leafletStyle,
                'useArrows':
                useArrows,
                'leafletOpacity':
                leafletOpacity,
                'modelScale':
                modelScale,
                'modelMinPxSize':
                modelMinPxSize,
                'cesiumColor':
                cesiumColor,
                'cesiumWeight':
                cesiumWeight,
                'cesiumStyle':
                cesiumStyle,
                'cesiumOpacity':
                cesiumOpacity
            },
            ignore_index=True)

    return assignments
def privCreateNodesFromLocs(locs=None,
                            initNodes=None,
                            nodeType=None,
                            nodeName=None,
                            startNode=1,
                            incrementName=False,
                            incrementStart=1,
                            snapToRoad=False,
                            dataProvider=None,
                            dataProviderArgs=None,
                            leafletIconPrefix=VRV_DEFAULT_LEAFLETICONPREFIX,
                            leafletIconType=VRV_DEFAULT_LEAFLETICONTYPE,
                            leafletColor=VRV_DEFAULT_LEAFLETICONCOLOR,
                            leafletIconText=None,
                            cesiumIconType=VRV_DEFAULT_CESIUMICONTYPE,
                            cesiumColor=VRV_DEFAULT_CESIUMICONCOLOR,
                            cesiumIconText=None):
    """
	Given a set of nodes lats and lons, return a node dataframe

	Parameters
	----------
	locs: list of lists, Required, default as None
		A list of locations, in the form of [[lat, lon, alt], [lat, lon, alt], ...] or [[lat, lon], [lat, lon], ...]
	initNodes: :ref:`Nodes`, Optional, default as None
		A dataframe containing an existing set of nodes. If `initNodes` is provided, this function will extend to that dataframe.
	nodeType: string, Optional, default as None
		A user-defined text field that can be used to classify nodes. This field is to categorize a batch of nodes (e.g., "restaurants"). If provided, all nodes generated by the `generateNodes()` function call will be given this value. The nodeType is not used by VeRoViz explicitly. 
	nodeName: string, Optional, default as None
		The name of all nodes that are to be generated by this function call. This field is a more detailed description (e.g., "pizza" or "steakhouse"). The nodeName is not used by VeRoViz explicitly. 
	startNode: int, Optional, default as 1
		The starting node number will be the maximum of startNode and any id values contained in the initNodes dataframe (if provided).  
	incrementName: boolean, Optional, default as False
		Toggle to choose if we add increment after nodeName, e.g. 'customer1', 'customer2',...
	incrementStart: int, Optional, default as 1
		The starting number of the increment.
	leafletIconPrefix: string, Optional, default as "glyphicon"
		The collection of Leaflet icons.  Options are "glyphicon" or "fa". See :ref:`Leaflet style`
	leafletIconType: string, Optional, default as "info-sign"
		The specific icon to be used for all generated nodes.  The list of available options depends on the choice of the leafletIconType. See :ref:`Leaflet style`
	leafletColor: string, Optional, default as "blue"
		The icon color of the generated nodes when displayed in Leaflet. One of a collection of pre-specified colors. See :ref:`Leaflet style`
	leafletIconText: string, Optional, default as None
		Text that will be displayed within the node on a Leaflet map. See :ref:`Leaflet style`
	cesiumIconType: string, Optional, default as "pin"
		'pin' is the only option right now. See :ref:`Cesium style`
	cesiumColor: string, Optional, default as "Cesium.Color.BLUE"
		The color of the generated nodes when displayed in Cesium.  One of a collection of pre-specified colors. See :ref:`Cesium style`
	cesiumIconText: string, Optional, default as None
		Text that will be displayed within the node on a Cesium map. See :ref:`Cesium style`

	Return
	------
	:ref:`Nodes`
		A Nodes dataframe with given list of coordinates
	"""

    # Number of nodes
    numNodes = len(locs)

    # Define ids and nodeNames
    if (type(initNodes) is pd.core.frame.DataFrame):
        if (len(initNodes) > 0):
            maxID = max(initNodes['id'])
            startNode = max([maxID + 1, startNode])

    ids = [n for n in range(startNode, startNode + numNodes)]
    if (incrementName):
        nodeNames = [(nodeName + "%s" % (n))
                     for n in range(incrementStart, incrementStart + numNodes)]
    else:
        nodeNames = [nodeName] * numNodes

    # Snap to road
    # FIXME! - Issue #28 - Multiple nodes might be snapped to the same location
    if (snapToRoad):
        locs = privGetSnapLocBatch(locs=locs,
                                   dataProvider=dataProvider,
                                   dataProviderArgs=dataProviderArgs)

    # node dataframe
    nodes = initDataframe('Nodes')

    # generate nodes
    dicLocs = locs2Dict(locs)
    for i in range(len(locs)):
        nodes = nodes.append(
            {
                'id':
                ids[i],
                'lat':
                dicLocs[i]['lat'],
                'lon':
                dicLocs[i]['lon'],
                'altMeters':
                dicLocs[i]['alt'],
                'nodeName':
                nodeNames[i],
                'nodeType':
                nodeType,
                'leafletIconPrefix':
                leafletIconPrefix,
                'leafletIconType':
                leafletIconType,
                'leafletColor':
                leafletColor,
                'leafletIconText':
                leafletIconText if (leafletIconText != None) else ids[i],
                'cesiumIconType':
                cesiumIconType,
                'cesiumColor':
                cesiumColor,
                'cesiumIconText':
                cesiumIconText if (cesiumIconText != None) else ids[i]
            },
            ignore_index=True)

    # if the user provided an initNode dataframe, add the new points after it
    if (type(initNodes) is pd.core.frame.DataFrame):
        nodes = pd.concat([initNodes, nodes], ignore_index=True)

    return nodes
Esempio n. 6
0
def _buildFlightPath(path, speedMPS):
    """
	Since _buildFlightProfile is not very flexible, this function gives a more customized method to generate profile, by listing lists of lats, lons and alts.

	Parameters
	----------
	path: list of lists
		A list of locations along with the flight path, in the format of [lat, lon] (altitude, above sea level, set to be 0) or [lat, lon, alt].
	speedMPS: float
		A constant speed, during this path the vehicle will cruise in this speed.

	Return
	------
	flight dataframe
		A dataframe to be interpreted into assignments dataframe.
	"""

    # Flight Profile dataframe
    flight = pd.DataFrame(columns=[
        'lat', 'lon', 'altAGL', 'accuGroundDistance', 'description',
        'loiterTime', 'groundDistance', 'flightDistance', 'accuFlightDistance',
        'timeFromPreviousPosition', 'pathStartTimeSec', 'pathEndTimeSec'
    ])

    # Check and guarantee that each point in path has 3 dimension
    dicPath = locs2Dict(path)

    # Add flight path one coordinate at a time
    accuGroundDistance = 0
    accuFlightDistance = 0
    accuPathTime = 0
    for i in range(len(path)):
        # Calculate fields for flight dataframe
        if i > 0:
            groundDistance = geoDistance2D(path[i - 1], path[i])
            deltaAGL = dicPath[i]['alt'] - dicPath[i - 1]['alt']
            flightDistance = math.sqrt(groundDistance * groundDistance +
                                       deltaAGL * deltaAGL)
        else:
            groundDistance = 0
            flightDistance = 0
        accuGroundDistance += groundDistance
        accuFlightDistance += flightDistance
        timeFromPreviousPosition = accuFlightDistance / speedMPS
        accuPathTime += timeFromPreviousPosition

        # And one way point to the flight path
        flight = flight.append(
            {
                'lat': dicPath[i]['lat'],
                'lon': dicPath[i]['lon'],
                'altAGL': dicPath[i]['alt'],
                'accuGroundDistance': accuGroundDistance,
                'description': "Waypoint",
                'loiterTime': 0.0,
                'groundDistance': groundDistance,
                'flightDistance': flightDistance,
                'accuFlightDistance': accuFlightDistance,
                'timeFromPreviousPosition': accuFlightDistance / speedMPS,
                'pathStartTimeSec': accuPathTime,
                'pathEndTimeSec': accuPathTime
            },
            ignore_index=True)

    return flight