All files / lib/core network.js

0% Statements 0/310
0% Branches 0/138
0% Functions 0/48
0% Lines 0/286

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
import { forEach } from 'lodash'
import Emitter from 'component-emitter'
 
import Stop from '../point/stop'
import Place from '../point/place'
import PointClusterMap from '../point/pointclustermap'
import RenderedEdge from '../renderer/renderededge'
import RenderedSegment from '../renderer/renderedsegment'
import Graph from '../graph/graph'
import { decode } from '../util/polyline.js'
import { sm } from '../util'
 
import Journey from './journey'
import RoutePattern from './pattern'
import Route from './route'
 
const debug = require('debug')('transitive:network')
 
/**
 * Network
 */
export default class Network {
  constructor(transitive, data) {
    this.transitive = transitive
 
    this.routes = {}
    this.stops = {}
    this.patterns = {}
    this.places = {}
    this.journeys = {}
    this.paths = []
    this.baseVertexPoints = []
    this.graph = new Graph(this, [])
 
    if (data) this.load(data)
  }
 
  /**
   * Load
   *
   * @param {Object} data
   */
 
  load(data) {
    debug('loading', data)
 
    // check data
    if (!data) data = {}
 
    // Store data
    this.data = data
 
    // A list of points (stops & places) that will always become vertices in the network
    // graph (regardless of zoom scale). This includes all points that serve as a segment
    // endpoint and/or a convergence/divergence point between segments
    this.baseVertexPoints = []
 
    // object maps stop ids to arrays of unique stop_ids reachable from that stop
    this.adjacentStops = {}
 
    // maps lat_lon key to unique TurnPoint object
    this.turnPoints = {}
 
    // Copy/decode the streetEdge objects
    this.streetEdges = {}
    forEach(data.streetEdges, (streetEdgeData) => {
      const latLons = decode(streetEdgeData.geometry.points)
      const coords = []
      forEach(latLons, (latLon) => {
        coords.push(sm.forward([latLon[1], latLon[0]]))
      })
      this.streetEdges[streetEdgeData.edge_id] = {
        latLons: latLons,
        length: streetEdgeData.geometry.length,
        worldCoords: coords
      }
    })
 
    // Generate the route objects
    this.routes = {}
    forEach(data.routes, (routeData) => {
      this.routes[routeData.route_id] = new Route(routeData)
    })
 
    // Generate the stop objects
    this.stops = {}
    forEach(data.stops, (stopData) => {
      this.stops[stopData.stop_id] = new Stop(stopData)
    })
 
    // Generate the pattern objects
    this.patterns = {}
    forEach(data.patterns, (patternData) => {
      const pattern = new RoutePattern(patternData, this)
      this.patterns[patternData.pattern_id] = pattern
      const route = this.routes[patternData.route_id]
      if (route) {
        route.addPattern(pattern)
        pattern.route = route
      } else {
        debug(
          'Error: pattern ' +
            patternData.pattern_id +
            ' refers to route that was not found: ' +
            patternData.route_id
        )
      }
      if (pattern.render) this.paths.push(pattern.createPath())
    })
 
    // Generate the place objects
    this.places = {}
    forEach(data.places, (placeData) => {
      const place = (this.places[placeData.place_id] = new Place(
        placeData,
        this
      ))
      this.addVertexPoint(place)
    })
 
    // Generate the internal Journey objects
    this.journeys = {}
    forEach(data.journeys, (journeyData) => {
      const journey = new Journey(journeyData, this)
      this.journeys[journeyData.journey_id] = journey
      this.paths.push(journey.path)
    })
 
    // process the path segments
    for (let p = 0; p < this.paths.length; p++) {
      const path = this.paths[p]
      for (let s = 0; s < path.segments.length; s++) {
        this.processSegment(path.segments[s])
      }
    }
 
    // when rendering pattern paths only, determine convergence/divergence vertex
    // stops by looking for stops w/ >2 adjacent stops
    if (!data.journeys || data.journeys.length === 0) {
      for (const stopId in this.adjacentStops) {
        if (this.adjacentStops[stopId].length > 2) {
          this.addVertexPoint(this.stops[stopId])
        }
      }
    }
 
    // determine which TurnPoints should be base vertices
    const turnLookup = {}
    const addTurn = function (turn1, turn2) {
      if (!(turn1.getId() in turnLookup)) turnLookup[turn1.getId()] = []
      if (turnLookup[turn1.getId()].indexOf(turn2) === -1) {
        turnLookup[turn1.getId()].push(turn2)
      }
    }
    forEach(Object.values(this.streetEdges), (streetEdge) => {
      if (streetEdge.fromTurnPoint && streetEdge.toTurnPoint) {
        addTurn(streetEdge.toTurnPoint, streetEdge.fromTurnPoint)
        addTurn(streetEdge.fromTurnPoint, streetEdge.toTurnPoint)
      }
    })
    for (const turnPointId in turnLookup) {
      const count = turnLookup[turnPointId].length
      if (count > 2) this.addVertexPoint(this.turnPoints[turnPointId])
    }
 
    this.createGraph()
 
    this.loaded = true
    this.emit('load', this)
    return this
  }
 
  /** Graph Creation/Processing Methods **/
 
  clearGraphData() {
    forEach(this.paths, (path) => {
      path.clearGraphData()
    })
  }
 
  createGraph() {
    this.applyZoomFactors(this.transitive.display.activeZoomFactors)
 
    // clear previous graph-specific data
    if (this.pointClusterMap) this.pointClusterMap.clearMultiPoints()
    forEach(Object.values(this.stops), (stop) => {
      stop.setFocused(true)
    })
 
    // create the list of vertex points
    let vertexPoints
    if (this.mergeVertexThreshold && this.mergeVertexThreshold > 0) {
      this.pointClusterMap = new PointClusterMap(
        this,
        this.mergeVertexThreshold
      )
      vertexPoints = this.pointClusterMap.getVertexPoints(this.baseVertexPoints)
    } else vertexPoints = this.baseVertexPoints
 
    // core graph creation steps
    this.graph = new Graph(this, vertexPoints)
    this.populateGraphEdges()
    this.graph.pruneVertices()
    this.createInternalVertexPoints()
    if (this.isSnapping()) this.graph.snapToGrid(this.gridCellSize)
    this.graph.sortVertices()
 
    // other post-processing actions
    this.annotateTransitPoints()
    // this.initPlaceAdjacency();
    this.createRenderedSegments()
    this.transitive.labeler.updateLabelList(this.graph)
    this.updateGeometry(true)
  }
 
  isSnapping() {
    return this.gridCellSize && this.gridCellSize !== 0
  }
 
  /*
   * identify and populate the 'internal' vertex points, which is zoom-level specfic
   */
 
  createInternalVertexPoints() {
    this.internalVertexPoints = []
 
    for (const i in this.graph.edgeGroups) {
      const edgeGroup = this.graph.edgeGroups[i]
 
      const wlen = edgeGroup.getWorldLength()
 
      const splitPoints = []
 
      // compute the maximum number of internal points for this edge to add as graph vertices
      if (edgeGroup.hasTransit()) {
        const vertexFactor = this.internalVertexFactor //! edgeGroup.hasTransit() ? 1 : this.internalVertexFactor;
        const newVertexCount = Math.floor(wlen / vertexFactor)
 
        // get the priority queue of the edge's internal points
        const pq = edgeGroup.getInternalVertexPQ()
 
        // pull the 'best' points from the queue until we reach the maximum
        while (splitPoints.length < newVertexCount && pq.size() > 0) {
          const el = pq.deq()
          splitPoints.push(el.point)
        }
      }
 
      // perform the split operation (if needed)
      if (splitPoints.length > 0) {
        for (let e = 0; e < edgeGroup.edges.length; e++) {
          const edge = edgeGroup.edges[e]
          this.graph.splitEdgeAtInternalPoints(edge, splitPoints)
        }
      } else if (edgeGroup.hasTransit()) {
        // special case: transit edge with no internal vertices (i.e. intermediate stops)
        edgeGroup.edges.forEach((edge) => {
          if (edge.pointGeom && edge.pointGeom.length > 0) {
            edge.geomCoords = edge.pointGeom[0].slice(0)
          }
        })
      }
    }
  }
 
  updateGeometry() {
    // clear the stop render data
    // for (var key in this.stops) this.stops[key].renderData = [];
 
    this.graph.vertices.forEach(function (vertex) {
      // vertex.snapped = false;
      vertex.point.clearRenderData()
    })
 
    // refresh the edge-based points
    this.graph.edges.forEach(function (edge) {
      edge.pointArray.forEach(function (point) {
        point.clearRenderData()
      })
    })
 
    this.renderedEdges.forEach(function (rEdge) {
      rEdge.clearOffsets()
    })
 
    // if (snapGrid)
    // if(this.gridCellSize && this.gridCellSize !== 0) this.graph.snapToGrid(this.gridCellSize);
 
    // this.fixPointOverlaps();
 
    this.graph.calculateGeometry(this.gridCellSize, this.angleConstraint)
 
    this.graph.apply2DOffsets(this)
  }
 
  applyZoomFactors(factors) {
    this.gridCellSize = factors.gridCellSize
    this.internalVertexFactor = factors.internalVertexFactor
    this.angleConstraint = factors.angleConstraint
    this.mergeVertexThreshold = factors.mergeVertexThreshold
    this.useGeographicRendering = factors.useGeographicRendering
  }
 
  /**
   *
   */
 
  processSegment(segment) {
    // iterate through this pattern's stops, associating stops/patterns with
    // each other and initializing the adjacentStops table
    let previousStop = null
    for (let i = 0; i < segment.points.length; i++) {
      const point = segment.points[i]
      point.used = true
 
      // called for each pair of adjacent stops in sequence
      if (previousStop && point.getType() === 'STOP') {
        this.addStopAdjacency(point.getId(), previousStop.getId())
        this.addStopAdjacency(previousStop.getId(), point.getId())
      }
 
      previousStop = point.getType() === 'STOP' ? point : null
 
      // add the start and end points to the vertexStops collection
      const startPoint = segment.points[0]
      this.addVertexPoint(startPoint)
      startPoint.isSegmentEndPoint = true
 
      const endPoint = segment.points[segment.points.length - 1]
      this.addVertexPoint(endPoint)
      endPoint.isSegmentEndPoint = true
    }
  }
 
  /**
   * Helper function for stopAjacency table
   *
   * @param {Stop} adjacent stops list
   * @param {Stop} stopA
   * @param {Stop} stopB
   */
 
  addStopAdjacency(stopIdA, stopIdB) {
    if (!this.adjacentStops[stopIdA]) this.adjacentStops[stopIdA] = []
    if (this.adjacentStops[stopIdA].indexOf(stopIdB) === -1) {
      this.adjacentStops[stopIdA].push(stopIdB)
    }
  }
 
  /**
   * Populate the graph edges
   */
 
  populateGraphEdges() {
    // vertex associated with the last vertex point we passed in this sequence
    let lastVertex = null
 
    // collection of 'internal' (i.e. non-vertex) points passed
    // since the last vertex point
    let internalPoints = []
 
    forEach(this.paths, (path) => {
      forEach(path.segments, (segment) => {
        lastVertex = null
 
        let streetEdgeIndex = 0
 
        // for transit segments, see if there is a pattern with inter-stop geometry defined
        let representativePattern = null
        if (segment.type === 'TRANSIT') {
          for (let i = 0; i < segment.patternGroup.patterns.length; i++) {
            const pattern = segment.patternGroup.patterns[i]
            if (
              pattern.interStopGeometry &&
              pattern.interStopGeometry.length === pattern.stops.length - 1
            ) {
              representativePattern = pattern
              break
            }
          }
        }
 
        /**
         *  geomCoords: The geographic coordinates for the graph edge currently
         *  being constructed, used when rendering edges in "real-world" (i.e.
         *  non-schematic) mode. geomCoords data is only initialized here for
         *  street-based segments, using the segment's embedded street geometry
         *  data (if provided).
         */
        let geomCoords = []
 
        /**
         *  pointGeom: An array of point-specific geometry (i.e. the alignment
         *  connecting this point to the following point in the containing
         *  segment's point sequence. Currently applies to transit segments only.
         *  pointGeom data is converted to geomCoords for rendering in the
         *  splitEdgeAtInternalPoints method of NetworkGraph
         */
        let pointGeom = []
 
        forEach(segment.points, (point, index) => {
          if (segment.streetEdges) {
            // street-based segment with street-edge geometry
            for (let i = streetEdgeIndex; i < segment.streetEdges.length; i++) {
              if (index === 0) break
 
              geomCoords = geomCoords.concat(
                geomCoords.length > 0
                  ? segment.streetEdges[i].worldCoords.slice(1)
                  : segment.streetEdges[i].worldCoords
              )
              if (segment.streetEdges[i].toTurnPoint === point) {
                streetEdgeIndex = i + 1
                break
              }
            }
          } else if (representativePattern) {
            // transit-based segment with known geometry
            const fromIndex = segment.patternGroup.getFromIndex(
              representativePattern
            )
 
            // ignore the first stop, since the geometry at this index represents
            // the alignment leading into that stop
            if (index > 0) {
              // add the alignment extending from this stop to the pointGeom array
              const geom =
                representativePattern.interStopGeometry[fromIndex + index - 1]
              pointGeom.push(geom)
            }
          }
 
          if (point.multipoint) point = point.multipoint
 
          if (point.graphVertex) {
            // this is a vertex point
            if (lastVertex !== null) {
              if (lastVertex.point === point) return
 
              // see if an equivalent graph edge already exists
              const fromVertex = lastVertex
              const toVertex = point.graphVertex
              let edge = this.graph.getEquivalentEdge(
                internalPoints,
                fromVertex,
                toVertex
              )
 
              // create a new graph edge if necessary
              if (!edge) {
                edge = this.graph.addEdge(
                  internalPoints,
                  fromVertex,
                  toVertex,
                  segment.getType()
                )
                if (geomCoords && geomCoords.length > 0) {
                  edge.geomCoords = geomCoords
                }
                if (pointGeom && pointGeom.length > 0) {
                  edge.pointGeom = pointGeom
                }
              }
 
              // associate the graph edge and path segment with each other
              segment.addEdge(edge, fromVertex)
              edge.addPathSegment(segment)
 
              // reset the geomCoords and pointGeom arrays for the next edge
              geomCoords = []
              pointGeom = []
            }
 
            lastVertex = point.graphVertex
            internalPoints = []
          } else {
            // this is an internal point
            internalPoints.push(point)
          }
        })
      })
    })
  }
 
  createGraphEdge(segment, fromVertex, toVertex, internalPoints, geomCoords) {
    let edge = this.graph.getEquivalentEdge(
      internalPoints,
      fromVertex,
      toVertex
    )
 
    if (!edge) {
      edge = this.graph.addEdge(
        internalPoints,
        fromVertex,
        toVertex,
        segment.getType()
      )
 
      // calculate the angle and apply to edge stops
      /* var dx = fromVertex.x - toVertex.x;
      var dy = fromVertex.y - toVertex.y;
      var angle = Math.atan2(dy, dx) * 180 / Math.PI;
      point.angle = lastVertex.point.angle = angle;
      for (var is = 0; is < internalPoints.length; is++) {
        internalPoints[is].angle = angle;
      } */
 
      if (geomCoords) edge.geomCoords = geomCoords
 
      debug('--- created edge ' + edge.toString())
    }
 
    segment.addEdge(edge, fromVertex)
    edge.addPathSegment(segment)
  }
 
  annotateTransitPoints() {
    this.paths.forEach(function (path) {
      const transitSegments = []
      path.segments.forEach(function (pathSegment) {
        if (pathSegment.type === 'TRANSIT') transitSegments.push(pathSegment)
      })
 
      path.segments.forEach(function (pathSegment) {
        if (pathSegment.type === 'TRANSIT') {
          // if first transit segment in path, mark 'from' endpoint as board point
          if (transitSegments.indexOf(pathSegment) === 0) {
            pathSegment.points[0].isBoardPoint = true
 
            // if there are additional transit segments, mark the 'to' endpoint as a transfer point
            if (transitSegments.length > 1) {
              pathSegment.points[
                pathSegment.points.length - 1
              ].isTransferPoint = true
            }
 
            // if last transit segment in path, mark 'to' endpoint as alight point
          } else if (
            transitSegments.indexOf(pathSegment) ===
            transitSegments.length - 1
          ) {
            pathSegment.points[
              pathSegment.points.length - 1
            ].isAlightPoint = true
 
            // if there are additional transit segments, mark the 'from' endpoint as a transfer point
            if (transitSegments.length > 1) {
              pathSegment.points[0].isTransferPoint = true
            }
 
            // if this is an 'internal' transit segment, mark both endpoints as transfer points
          } else if (transitSegments.length > 2) {
            pathSegment.points[0].isTransferPoint = true
            pathSegment.points[
              pathSegment.points.length - 1
            ].isTransferPoint = true
          }
        }
      })
    })
  }
 
  initPlaceAdjacency() {
    forEach(Object.values(this.places), (place) => {
      if (!place.graphVertex) return
      forEach(place.graphVertex.incidentEdges(), (edge) => {
        const oppVertex = edge.oppositeVertex(place.graphVertex)
        if (oppVertex.point) {
          oppVertex.point.adjacentPlace = place
        }
      })
    })
  }
 
  createRenderedSegments() {
    this.reLookup = {}
    this.renderedEdges = []
    this.renderedSegments = []
 
    for (const patternId in this.patterns) {
      this.patterns[patternId].renderedEdges = []
    }
 
    forEach(this.paths, (path) => {
      forEach(path.segments, (pathSegment) => {
        pathSegment.renderedSegments = []
 
        if (pathSegment.type === 'TRANSIT') {
          // create a RenderedSegment for each pattern, except for buses which are collapsed to a single segment
          const busPatterns = []
          forEach(pathSegment.getPatterns(), (pattern) => {
            if (pattern.route.route_type === 3) busPatterns.push(pattern)
            else this.createRenderedSegment(pathSegment, [pattern])
          })
          if (busPatterns.length > 0) {
            this.createRenderedSegment(pathSegment, busPatterns)
          }
        } else {
          // non-transit segments
          this.createRenderedSegment(pathSegment)
        }
      })
    })
 
    this.renderedEdges.sort(function (a, b) {
      // process render transit segments before walk
      if (a.getType() === 'WALK') return 1
      if (b.getType() === 'WALK') return -1
    })
  }
 
  createRenderedSegment(pathSegment, patterns) {
    const rSegment = new RenderedSegment(pathSegment)
 
    forEach(pathSegment.edges, (edge) => {
      const rEdge = this.createRenderedEdge(
        pathSegment,
        edge.graphEdge,
        edge.forward,
        patterns
      )
      rSegment.addRenderedEdge(rEdge)
    })
    if (patterns) {
      rSegment.patterns = patterns
      rSegment.mode = patterns[0].route.route_type
    }
 
    pathSegment.addRenderedSegment(rSegment)
  }
 
  createRenderedEdge(pathSegment, gEdge, forward, patterns) {
    let rEdge
 
    // construct the edge key, disregarding mode qualifiers (e.g. "_RENT")
    const type = pathSegment.getType().split('_')[0]
    let key = gEdge.id + (forward ? 'F' : 'R') + '_' + type
 
    // for non-bus transit edges, append an exemplar pattern ID to the key
    if (patterns && patterns[0].route.route_type !== 3) {
      key += '_' + patterns[0].getId()
    }
 
    // see if this r-edge already exists
    if (key in this.reLookup) {
      rEdge = this.reLookup[key]
    } else {
      // if not, create it
      rEdge = new RenderedEdge(
        gEdge,
        forward,
        type,
        this.useGeographicRendering
      )
      if (patterns) {
        forEach(patterns, (pattern) => {
          pattern.addRenderedEdge(rEdge)
          rEdge.addPattern(pattern)
        })
        rEdge.mode = patterns[0].route.route_type
      }
      rEdge.points.push(gEdge.fromVertex.point)
      rEdge.points.push(gEdge.toVertex.point)
      gEdge.addRenderedEdge(rEdge)
      rEdge.addPathSegment(pathSegment)
 
      this.renderedEdges.push(rEdge)
      this.reLookup[key] = rEdge
    }
    return rEdge
  }
 
  addVertexPoint(point) {
    if (this.baseVertexPoints.indexOf(point) !== -1) return
    this.baseVertexPoints.push(point)
  }
}
 
/**
 * Mixin `Emitter`
 */
 
Emitter(Network.prototype)