Esempio n. 1
0
  public JSONArray buildSpotifyJsonObject(ArrayList<Trip> list) {
    JSONArray array = new JSONArray();

    try {
      for (Trip trip : list) {
        JSONArray tracks = new JSONArray();

        for (Track track : trip.getTracks()) {
          tracks.put(
              new JSONObject()
                  .put("name", track.getName())
                  .put("artist", track.getArtist())
                  .put("duration", track.getDuration())
                  .put("url", track.getUrl()));
        }
        array.put(
            new JSONObject()
                .put("origin", trip.getOrigin())
                .put("destination", trip.getDest())
                .put("id", trip.getId())
                .put("duration", trip.getDurationMs())
                .put("originDate", trip.getOriginDate())
                .put("destinationDate", trip.getDestDate())
                .put("originTime", trip.getOriginTime())
                .put("destinationTime", trip.getDestTime())
                .put("playlist", tracks));
      }

    } catch (Exception E) {

    }
    System.out.println(array);
    return array;
  }
Esempio n. 2
0
 /**
  * calculate the total price for a the companion trips
  *
  * @return int
  */
 public int calculateTripsPrice() {
   int total = 0;
   for (Trip tr : trips) {
     total += tr.getPrice();
   }
   return total;
 }
Esempio n. 3
0
  public JSONArray buildJsonObject(ArrayList<Trip> list) {
    JSONArray array = new JSONArray();

    try {
      for (Trip trip : list) {
        JSONArray tracks = new JSONArray();

        array.put(
            new JSONObject()
                .put("origin", trip.getOrigin())
                .put("destination", trip.getDest())
                .put("id", trip.getId())
                .put("duration", trip.getDurationMs())
                .put("originDate", trip.getOriginDate())
                .put("destinationDate", trip.getDestDate())
                .put("originTime", trip.getOriginTime())
                .put("destinationTime", trip.getDestTime())
                .put("playlist", tracks));
      }

    } catch (Exception E) {

    }
    System.out.println(array);
    return array;
  }
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    menu.clear();
    getMenuInflater().inflate(R.menu.triplistmenu, menu);

    if (trip.isFreeTrip() == false && trip.isEmpty() == false) {
      menu.findItem(R.id.triplistMenuCalendar).setVisible(true);
    }

    return true;
  } // onCreateOptionsMenu
  public void approve(
      int notificationId,
      int tripNo,
      int routeNo,
      RouteType routeType,
      String startTime,
      String endTime) {

    TripDAO tripDAO = new TripDAO();
    RouteDAO routeDAO = new RouteDAO();
    Route route = routeDAO.getRoutebyRouteNo(routeNo, routeType);
    Trip trip = tripDAO.readTripByRouteAndNo(route, tripNo);

    // if cannot find trip -> return and do nothing
    if (trip == null) {
      System.out.println("Approve Action have something wrong");
      return;
    }

    boolean canApprove = false;
    LocalTime start = null;
    if (startTime != null) {
      start = parseTimeFromClient(startTime);
      canApprove = true;
    }
    LocalTime end = null;
    if (endTime != null) {
      end = parseTimeFromClient(endTime);
      canApprove = true;
    }

    if (canApprove) {
      if (start != null) {
        trip.setStartTime(start);
      }
      if (end != null) {
        trip.setEndTime(end);
      }
      tripDAO.update(trip);
    }

    // delete trip notification
    TripNotificationDAO tripNotificationDAO = new TripNotificationDAO();
    TripNotification tripNof = tripNotificationDAO.read(notificationId);
    tripNotificationDAO.delete(tripNof);

    // delete notification
    NotificationDAO notificationDAO = new NotificationDAO();
    Notification nof = notificationDAO.read(notificationId);
    notificationDAO.delete(nof);

    System.out.println("Trip Notification Approved");
  }
 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   debug(
       0,
       "requestCode="
           + requestCode
           + ", REQUEST_ADD_TO_TRIP="
           + ADD_TO_TRIP
           + ", CALENDER="
           + CALENDAR
           + ", etc...");
   if (resultCode == Activity.RESULT_CANCELED) {
     return;
   }
   switch (requestCode) {
     case ADD_TO_TRIP:
       debug(
           2, "Returned pois to add to trip!"); // From using PoiList to select new POIs to add to
       // trip
       trip = data.getParcelableExtra(IntentPassable.TRIP);
       pois = trip.getPois();
       poiAdapter.replaceAll(pois);
       lv.setAdapter(poiAdapter);
       poiAdapter.notifyDataSetChanged();
       break;
     case CALENDAR:
       this.trip = data.getParcelableExtra(IntentPassable.TRIP);
       poiAdapter.notifyDataSetChanged();
       break;
     default:
       debug(0, "No handler for result=" + resultCode);
       break;
   }
 } // onActivityResult
Esempio n. 7
0
  /**
   * Parses a url pointing to a Google JSON object to a Route object.
   *
   * @throws Exception
   */
  private void parse() throws Exception {
    String response = getUrlContent(result);

    JSONObject jObject = new JSONObject(response);
    status = jObject.getString("status");

    // checks to make sure there are no errors in getting content.
    if (checkStatus(status) == 0) {
      // drills down the JSON object to find each individual step.
      JSONObject jsonRoute = jObject.getJSONArray("routes").getJSONObject(0);
      JSONObject leg = jsonRoute.getJSONArray("legs").getJSONObject(0);
      JSONObject tripDistObj = leg.getJSONObject("distance");
      JSONObject tripDurObj = leg.getJSONObject("duration");
      int distance = tripDistObj.getInt("value");
      int duration = tripDurObj.getInt("value");
      JSONArray steps = leg.getJSONArray("steps");
      routes = new Route[steps.length()];

      for (int i = 0; i < steps.length(); i++) {
        // updates more information about route for each step in trip in a array of routes.
        JSONObject step = steps.getJSONObject(i);
        routes[i] = new Route();
        routes[i].setInstruction(step.getString("html_instructions"));
        routes[i].setDuration((step.getJSONObject("duration").getInt("value")));
        routes[i].setStartLoc(
            new Location(
                step.getJSONObject("start_location").getDouble("lat"),
                step.getJSONObject("start_location").getDouble("lng")));
        routes[i].setEndLoc(
            new Location(
                step.getJSONObject("end_location").getDouble("lat"),
                step.getJSONObject("end_location").getDouble("lng")));
        // Get google's copyright notice (requirement)
        routes[i].setCopyright(jsonRoute.getString("copyrights"));
        // Get the total length of this step.
        routes[i].setLength(step.getJSONObject("distance").getInt("value"));
        // Get any warnings provided (requirement)
        if (!jsonRoute.getJSONArray("warnings").isNull(0)) {
          routes[i].setWarning(jsonRoute.getJSONArray("warnings").getString(0));
        }
      }
      trip = new Trip();
      trip.setRoute(routes);
      trip.setDuration(duration);
      trip.setDistance(distance);
    }
  }
Esempio n. 8
0
 public String getInfo() {
   return "Name: "
       + name
       + "\nAddress: "
       + address
       + "\nHas the following trip: "
       + trip.getInfo()
       + "\n";
 }
Esempio n. 9
0
  /**
   * Returns a String containing trip fares to be displayed as the snippet for the map maker of the
   * specified destination station.
   *
   * @param dest The name of the destination station.
   * @return The String to display.
   */
  public String generateSnippet(String dest) {
    Station destStation = mBService.lookupStationByName(dest);
    Station origStation;
    if (originStation != null) {
      origStation = originStation;
    } else {
      origStation = mBService.lookupStationByAbbreviation("DBRK");
    }
    DateFormat df = new SimpleDateFormat("hh:mma", Locale.US);
    Date now = Calendar.getInstance(TimeZone.getDefault()).getTime();
    Trip mTrip = mBService.generateTrip(origStation, destStation, df.format(now));

    float fare = mTrip.getFare();
    DecimalFormat decim = new DecimalFormat("0.00");
    String fareOneWay = decim.format(fare);
    String fareRoundTrip = decim.format(2 * fare);

    String mSnippet = "$" + fareOneWay + " | $" + fareRoundTrip;
    return mSnippet;
  }
  @Override
  public void handleEvent(PersonLeavesVehicleEvent event) {
    if (transitDriverIds.contains(event.getPersonId())) return;
    try {
      if (ptVehicles.keySet().contains(event.getVehicleId())) {
        TravellerChain chain = chains.get(event.getPersonId());
        chain.traveledVehicle = true;
        PTVehicle vehicle = ptVehicles.get(event.getVehicleId());
        double stageDistance = vehicle.removePassenger(event.getPersonId());
        Trip trip = chain.getJourneys().getLast().getTrips().getLast();
        trip.setDistance(stageDistance);
        trip.setAlightingStop(vehicle.lastStop);
      } else {
        driverIdFromVehicleId.remove(event.getVehicleId());
      }

    } catch (Exception e) {
      System.err.println(e.getStackTrace());
      System.err.println(event.toString());
    }
  }
Esempio n. 11
0
 private void parseTrips(BufferedReader reader) throws IOException {
   String line = reader.readLine(); // skip column names
   HashMap<String, Trip> processedTrips = new HashMap<>();
   // route_id,service_id,trip_id,trip_headsign,direction_id,block_id,shape_id,wheelchair_accessible,trips_bkk_ref
   Pattern pattern =
       Pattern.compile("^([^,]+),[^,]*,([^,]+),(?:\"([^\"]+)\"|([^,]+)),(0|1),[^,]*,([^,]+),.*");
   while ((line = reader.readLine()) != null) {
     Matcher matcher = pattern.matcher(line);
     if (!matcher.matches()) {
       write(line);
       continue;
     }
     Integer routeId = routes.get(matcher.group(1));
     Route route = routeId != null ? Route.findRoute(routeId) : null;
     if (route != null) {
       String direction = matcher.group(5);
       String quotedHeadsign = matcher.group(3);
       String headSign = quotedHeadsign != null ? quotedHeadsign : matcher.group(4);
       String tripKey = headSign + ":" + direction + ":" + matcher.group(6) + ":" + routeId;
       Trip trip = processedTrips.get(tripKey);
       if (trip == null) {
         trip = new Trip();
         trip.setHeadSign(headSign);
         trip.setIsReturn("1".equals(direction));
         trip.setRoute(route);
         processedTrips.put(tripKey, trip);
         trip.persist();
       }
       trips.put(matcher.group(2), trip.getId());
     }
   }
 }
        @Override
        public void onClick(View paramView) {
          String errorMessage = "";
          int litres = 0;

          try {
            // Leave breadcrumb.
            CrashReporter.leaveBreadcrumb("Trip_Stock_Load: onOK");

            // Check for product.
            if (product == null) {
              errorMessage = "Please select a product";
              return;
            }

            // Check loaded quantity.
            try {
              litres = decimalFormat.parse(etLoaded.getText().toString()).intValue();
            } catch (ParseException e) {
              e.printStackTrace();
            }

            if (litres <= 0) {
              errorMessage = "Litres missing";
              return;
            }

            // Update stock locally.
            Active.vehicle.recordLoad(product, litres);

            // Update stock on server.
            trip.sendVehicleStock();

            // Reset UI.
            etLoaded.setText("");

            // Notify user.
            Toast t = Toast.makeText(trip, litres + " loaded", Toast.LENGTH_SHORT);
            t.setGravity(Gravity.CENTER, 0, 0);
            t.show();
          } catch (Exception e) {
            CrashReporter.logHandledException(e);
          } finally {
            // Show error message?
            if (errorMessage.length() > 0) {
              Toast t = Toast.makeText(trip, errorMessage, Toast.LENGTH_SHORT);
              t.setGravity(Gravity.CENTER, 0, 0);
              t.show();
            }
          }
        }
  /** Initializes the activity. */
  private void init() {
    db = DBFactory.getInstance(context);
    res = getResources();

    if (getIntent().getParcelableExtra("trip") != null) {
      trip = (Trip) getIntent().getParcelableExtra("trip");
      title = (TextView) findViewById(R.id.triplabel);
      title.setText(trip.getLabel());
    } else {
      debug(0, "No trip supplied.. exit activity");
      this.finish();
    }
    debug(2, "FreeTrip=" + trip.isFreeTrip());

    lv = getListView();
    lv.setOnItemLongClickListener(new DrawPopup());
    poiAdapter = new PoiAdapter(this, R.layout.plan_listitem, pois);
    lv.setAdapter(poiAdapter);

    for (Poi p : trip.getPois()) {
      pois.add(p);
    }
  } // init
 @Override
 public void handleEvent(PersonArrivalEvent event) {
   try {
     if (isTransitScenario) {
       if (transitDriverIds.contains(event.getPersonId())) return;
     }
     TravellerChain chain = chains.get(event.getPersonId());
     switch (event.getLegMode()) {
       case "walk":
       case "transit_walk":
         {
           Journey journey = chain.getJourneys().getLast();
           Walk walk = journey.getWalks().getLast();
           walk.setDest(network.getLinks().get(event.getLinkId()).getCoord());
           walk.setEndTime(event.getTime());
           walk.setDistance(walk.getDuration() * walkSpeed);
           break;
         }
       case TransportMode.car:
         {
           Journey journey = chain.getJourneys().getLast();
           journey.setDest(network.getLinks().get(event.getLinkId()).getCoord());
           journey.setEndTime(event.getTime());
           Trip trip = journey.getTrips().getLast();
           trip.setDistance(journey.getDistance());
           trip.setEndTime(event.getTime());
           chain.inCar = false;
           break;
         }
       case "pt":
         if (isTransitScenario) {
           Journey journey = chain.getJourneys().getLast();
           Trip trip = journey.getTrips().getLast();
           trip.setDest(network.getLinks().get(event.getLinkId()).getCoord());
           trip.setEndTime(event.getTime());
           journey.setPossibleTransfer(new Transfer());
           journey.getPossibleTransfer().setStartTime(event.getTime());
           journey.getPossibleTransfer().setFromTrip(trip);
         } else {
           Journey journey = chain.getJourneys().getLast();
           journey.setEndTime(event.getTime());
           journey.setDest(network.getLinks().get(event.getLinkId()).getCoord());
           journey.setEndTime(event.getTime());
         }
         break;
       default:
         Journey journey = chain.getJourneys().getLast();
         journey.setEndTime(event.getTime());
         journey.setDest(network.getLinks().get(event.getLinkId()).getCoord());
         journey.setEndTime(event.getTime());
         break;
     }
   } catch (Exception e) {
     System.err.println(e.getStackTrace());
     System.err.println(event.toString());
   }
 }
        @Override
        public void onClick(View paramView) {
          try {
            // Leave breadcrumb.
            CrashReporter.leaveBreadcrumb("Trip_Stock_Load: onCancel");

            if (btnCancel.getText().equals("Close")) {
              // Close view.
              btnCancel.setEnabled(false);

              // Switch back to previous view.
              trip.selectView(previousViewName, -1);
            } else {
              // Cancel input.
              etLoaded.setText("");
            }
          } catch (Exception e) {
            CrashReporter.logHandledException(e);
          }
        }
 @Override
 public void handleEvent(PersonEntersVehicleEvent event) {
   try {
     if (transitDriverIds.contains(event.getPersonId())) return;
     if (ptVehicles.keySet().contains(event.getVehicleId())) {
       TravellerChain chain = chains.get(event.getPersonId());
       Journey journey = chain.getJourneys().getLast();
       // first, handle the end of the wait
       journey.getWaits().getLast().setEndTime(event.getTime());
       // now, create a new trip
       ptVehicles.get(event.getVehicleId()).addPassenger(event.getPersonId());
       Trip trip = journey.addTrip();
       PTVehicle vehicle = ptVehicles.get(event.getVehicleId());
       trip.setLine(vehicle.transitLineId);
       trip.setMode(
           transitSchedule
               .getTransitLines()
               .get(vehicle.transitLineId)
               .getRoutes()
               .get(vehicle.transitRouteId)
               .getTransportMode());
       trip.setBoardingStop(vehicle.lastStop);
       trip.setOrig(journey.getWaits().getLast().getCoord());
       trip.setRoute(ptVehicles.get(event.getVehicleId()).transitRouteId);
       trip.setStartTime(event.getTime());
       // check for the end of a transfer
       if (journey.getPossibleTransfer() != null) {
         journey.getPossibleTransfer().setToTrip(trip);
         journey.getPossibleTransfer().setEndTime(event.getTime());
         journey.addTransfer(journey.getPossibleTransfer());
         journey.setPossibleTransfer(null);
       }
     } else {
       // add the person to the map that keeps track of who drives what
       // vehicle
       driverIdFromVehicleId.put(event.getVehicleId(), event.getPersonId());
     }
   } catch (Exception e) {
     System.err.println(e.getStackTrace());
     System.err.println(event.toString());
   }
 }
Esempio n. 17
0
 /**
  * Removes a trip
  *
  * @param trip != null
  */
 public void removeTrip(Trip trip) {
   if (trips.contains(trip)) {
     trips.remove(trip);
     trip.removeCompanion(this);
   }
 }
 @Override
 public void handleEvent(PersonDepartureEvent event) {
   try {
     if (transitDriverIds.contains(event.getPersonId())) return;
     TravellerChain chain = chains.get(event.getPersonId());
     Journey journey;
     Trip trip;
     switch (event.getLegMode()) {
       case TransportMode.walk:
         // fall through to the next
       case TransportMode.transit_walk:
         if (!chain.traveling) {
           chain.traveling = true;
           journey = chain.addJourney();
           journey.setOrig(network.getLinks().get(event.getLinkId()).getCoord());
           journey.setFromAct(chain.getActs().getLast());
           journey.setStartTime(event.getTime());
           Walk walk = journey.addWalk();
           walk.setAccessWalk(true);
           walk.setStartTime(event.getTime());
           walk.setOrig(journey.getOrig());
         } else {
           journey = chain.getJourneys().getLast();
           Walk walk = journey.addWalk();
           walk.setStartTime(event.getTime());
           walk.setOrig(network.getLinks().get(event.getLinkId()).getCoord());
           journey.getPossibleTransfer().getWalks().add(walk);
         }
         break;
       case TransportMode.car:
         chain.inCar = true;
         journey = chain.addJourney();
         journey.setCarJourney(true);
         journey.setOrig(network.getLinks().get(event.getLinkId()).getCoord());
         journey.setFromAct(chain.getActs().getLast());
         journey.setStartTime(event.getTime());
         trip = journey.addTrip();
         trip.setMode("car");
         trip.setStartTime(event.getTime());
         break;
       case TransportMode.pt:
         if (isTransitScenario) {
           // person waits till they enter the vehicle
           journey = chain.getJourneys().getLast();
           Wait wait = journey.addWait();
           if (journey.getWaits().size() == 1) wait.setAccessWait(true);
           wait.setStartTime(event.getTime());
           wait.setCoord(network.getLinks().get(event.getLinkId()).getCoord());
           if (!wait.isAccessWait()) {
             journey.getPossibleTransfer().getWaits().add(wait);
           }
         } else {
           journey = chain.addJourney();
           journey.setTeleportJourney(true);
           journey.setOrig(network.getLinks().get(event.getLinkId()).getCoord());
           journey.setFromAct(chain.getActs().getLast());
           journey.setStartTime(event.getTime());
           journey.setMainmode(event.getLegMode());
           trip = journey.addTrip();
           trip.setMode(event.getLegMode());
           trip.setStartTime(event.getTime());
         }
         break;
       default:
         journey = chain.addJourney();
         journey.setTeleportJourney(true);
         journey.setOrig(network.getLinks().get(event.getLinkId()).getCoord());
         journey.setFromAct(chain.getActs().getLast());
         journey.setStartTime(event.getTime());
         journey.setMainmode(event.getLegMode());
         trip = journey.addTrip();
         trip.setMode(event.getLegMode());
         trip.setStartTime(event.getTime());
         break;
     }
   } catch (Exception e) {
     System.err.println(e.getStackTrace());
     System.err.println(event.toString());
   }
 }
  @Override
  public void run() {
    GTFSFeed feed = new GTFSFeed();

    GlobalTx gtx = VersionedDataStore.getGlobalTx();
    AgencyTx atx = null;

    try {
      for (Tuple2<String, Integer> ssid : snapshots) {
        String agencyId = ssid.a;
        Agency agency = gtx.agencies.get(agencyId);
        com.conveyal.gtfs.model.Agency gtfsAgency = agency.toGtfs();
        Logger.info("Exporting agency %s", gtfsAgency);

        if (ssid.b == null) {
          atx = VersionedDataStore.getAgencyTx(agencyId);
        } else {
          atx = VersionedDataStore.getAgencyTx(agencyId, ssid.b);
        }

        // write the agencies.txt entry
        feed.agency.put(agencyId, agency.toGtfs());

        // write all of the calendars and calendar dates
        for (ServiceCalendar cal : atx.calendars.values()) {
          com.conveyal.gtfs.model.Service gtfsService =
              cal.toGtfs(toGtfsDate(startDate), toGtfsDate(endDate));
          // note: not using user-specified IDs

          // add calendar dates
          if (atx.exceptions != null) {
            for (ScheduleException ex : atx.exceptions.values()) {
              for (LocalDate date : ex.dates) {
                if (date.isBefore(startDate) || date.isAfter(endDate))
                  // no need to write dates that do not apply
                  continue;

                CalendarDate cd = new CalendarDate();
                cd.date = date;
                cd.service = gtfsService;
                cd.exception_type = ex.serviceRunsOn(cal) ? 1 : 2;

                if (gtfsService.calendar_dates.containsKey(date))
                  throw new IllegalArgumentException(
                      "Duplicate schedule exceptions on " + date.toString());

                gtfsService.calendar_dates.put(date, cd);
              }
            }
          }

          feed.services.put(gtfsService.service_id, gtfsService);
        }

        Map<String, com.conveyal.gtfs.model.Route> gtfsRoutes = Maps.newHashMap();

        // write the routes
        for (Route route : atx.routes.values()) {
          com.conveyal.gtfs.model.Route gtfsRoute = route.toGtfs(gtfsAgency, gtx);
          feed.routes.put(route.getGtfsId(), gtfsRoute);

          gtfsRoutes.put(route.id, gtfsRoute);
        }

        // write the trips on those routes
        // we can't use the trips-by-route index because we may be exporting a snapshot database
        // without indices
        for (Trip trip : atx.trips.values()) {
          if (!gtfsRoutes.containsKey(trip.routeId)) {
            Logger.warn("Trip {} has not matching route", trip);
            continue;
          }

          com.conveyal.gtfs.model.Route gtfsRoute = gtfsRoutes.get(trip.routeId);
          Route route = atx.routes.get(trip.routeId);

          com.conveyal.gtfs.model.Trip gtfsTrip = new com.conveyal.gtfs.model.Trip();

          gtfsTrip.block_id = trip.blockId;
          gtfsTrip.route = gtfsRoute;
          gtfsTrip.trip_id = trip.getGtfsId();
          // not using custom ids for calendars
          gtfsTrip.service = feed.services.get(trip.calendarId);
          gtfsTrip.trip_headsign = trip.tripHeadsign;
          gtfsTrip.trip_short_name = trip.tripShortName;
          gtfsTrip.direction_id = trip.tripDirection == TripDirection.A ? 0 : 1;

          TripPattern pattern = atx.tripPatterns.get(trip.patternId);

          Tuple2<String, Integer> nextKey =
              feed.shapePoints.ceilingKey(new Tuple2(pattern.id, null));
          if ((nextKey == null || !pattern.id.equals(nextKey.a))
              && pattern.shape != null
              && !pattern.useStraightLineDistances) {
            // this shape has not yet been saved
            double[] coordDistances = GeoUtils.getCoordDistances(pattern.shape);

            for (int i = 0; i < coordDistances.length; i++) {
              Coordinate coord = pattern.shape.getCoordinateN(i);
              Shape shape = new Shape(pattern.id, coord.y, coord.x, i + 1, coordDistances[i]);
              feed.shapePoints.put(new Tuple2(pattern.id, shape.shape_pt_sequence), shape);
            }
          }

          if (pattern.shape != null && !pattern.useStraightLineDistances)
            gtfsTrip.shape_id = pattern.id;

          if (trip.wheelchairBoarding != null) {
            if (trip.wheelchairBoarding.equals(AttributeAvailabilityType.AVAILABLE))
              gtfsTrip.wheelchair_accessible = 1;
            else if (trip.wheelchairBoarding.equals(AttributeAvailabilityType.UNAVAILABLE))
              gtfsTrip.wheelchair_accessible = 2;
            else gtfsTrip.wheelchair_accessible = 0;

          } else if (route.wheelchairBoarding != null) {
            if (route.wheelchairBoarding.equals(AttributeAvailabilityType.AVAILABLE))
              gtfsTrip.wheelchair_accessible = 1;
            else if (route.wheelchairBoarding.equals(AttributeAvailabilityType.UNAVAILABLE))
              gtfsTrip.wheelchair_accessible = 2;
            else gtfsTrip.wheelchair_accessible = 0;
          }

          feed.trips.put(gtfsTrip.trip_id, gtfsTrip);

          TripPattern patt = atx.tripPatterns.get(trip.patternId);

          Iterator<TripPatternStop> psi = patt.patternStops.iterator();

          int stopSequence = 1;

          // write the stop times
          for (StopTime st : trip.stopTimes) {
            TripPatternStop ps = psi.next();
            if (st == null) continue;

            Stop stop = atx.stops.get(st.stopId);

            if (!st.stopId.equals(ps.stopId)) {
              throw new IllegalStateException("Trip " + trip.id + " does not match its pattern!");
            }

            com.conveyal.gtfs.model.StopTime gst = new com.conveyal.gtfs.model.StopTime();
            gst.arrival_time = st.arrivalTime != null ? st.arrivalTime : Entity.INT_MISSING;
            gst.departure_time = st.departureTime != null ? st.departureTime : Entity.INT_MISSING;

            if (st.dropOffType != null) gst.drop_off_type = st.dropOffType.toGtfsValue();
            else if (stop.dropOffType != null) gst.drop_off_type = stop.dropOffType.toGtfsValue();

            if (st.pickupType != null) gst.pickup_type = st.pickupType.toGtfsValue();
            else if (stop.dropOffType != null) gst.drop_off_type = stop.dropOffType.toGtfsValue();

            gst.shape_dist_traveled = ps.shapeDistTraveled;
            gst.stop_headsign = st.stopHeadsign;
            gst.stop_id = stop.getGtfsId();

            // write the stop as needed
            if (!feed.stops.containsKey(gst.stop_id)) {
              feed.stops.put(gst.stop_id, stop.toGtfs());
            }

            gst.stop_sequence = stopSequence++;

            if (ps.timepoint != null) gst.timepoint = ps.timepoint ? 1 : 0;
            else gst.timepoint = Entity.INT_MISSING;

            gst.trip_id = gtfsTrip.trip_id;

            feed.stop_times.put(new Tuple2(gtfsTrip.trip_id, gst.stop_sequence), gst);
          }

          // create frequencies as needed
          if (trip.useFrequency != null && trip.useFrequency) {
            Frequency f = new Frequency();
            f.trip = gtfsTrip;
            f.start_time = trip.startTime;
            f.end_time = trip.endTime;
            f.exact_times = 0;
            f.headway_secs = trip.headway;
            feed.frequencies.put(gtfsTrip.trip_id, f);
          }
        }
      }

      feed.toFile(output.getAbsolutePath());
    } finally {
      gtx.rollbackIfOpen();
      if (atx != null) atx.rollbackIfOpen();
    }
  }
Esempio n. 20
0
  @Override
  public void handleEvent(ActivityEndEvent event) {
    // store information from event to variables and print the information on console
    // String eventType = event.getEventType();
    Id<Link> linkId = event.getLinkId();
    // String linkShortened = linkId.toString().substring(0, 10) + "...";
    Id<Person> personId = event.getPersonId();
    double time = event.getTime();
    String actType = event.getActType();
    // Id facilityId =	event.getFacilityId();
    // System.out.println("Type: " + eventType + " - LinkId: " + linkShortened + " - PersonId: " +
    // personId.toString()
    //		+ " - Time: " + time/60/60 + " - ActType: " + actType + " - FacilityId: " + facilityId);

    // count number of activity ends for every agent and store these numbers in a map
    if (!activityEndCount.containsKey(personId)) {
      activityEndCount.put(personId, 1);
    } else {
      int numberOfCompletedDepartures = activityEndCount.get(personId);
      activityEndCount.put(personId, numberOfCompletedDepartures + 1);
    }
    // System.out.println("Agent " + personId + " has " + activityEndCount.get(personId) + "
    // activity ends.");

    // create an instance of the object "Trip"
    Trip trip = new Trip();
    Id<Trip> tripId = Id.create(personId + "_" + activityEndCount.get(personId), Trip.class);
    trip.setTripId(tripId);
    trip.setPersonId(personId);
    trip.setDepartureLinkId(linkId);
    trip.setDepartureTime(time);
    // trip.setDepartureLegMode(legMode);
    trip.setActivityEndActType(actType);
    trips.put(tripId, trip);

    // check if activity end link is the same as previous activity start link
    if (activityEndCount.get(personId) >= 2) {
      int numberOfLastArrival = activityStartCount.get(personId);
      Id<Trip> lastTripId = Id.create(personId + "_" + numberOfLastArrival, Trip.class);
      if (!trips
          .get(tripId)
          .getDepartureLinkId()
          .equals(trips.get(lastTripId).getArrivalLinkId())) {
        // System.err.println("Activity end link differs from previous activity start link.");
        throw new RuntimeException("Activity end link differs from previous activity start link.");
      }
    }

    // check if type of ending activity is the same as type of previously started activity
    if (activityEndCount.get(personId) >= 2) {
      int numberOfLastArrival = activityStartCount.get(personId);
      Id<Trip> lastTripId = Id.create(personId + "_" + numberOfLastArrival, Trip.class);
      if (!trips
          .get(tripId)
          .getActivityEndActType()
          .equals(trips.get(lastTripId).getActivityStartActType())) {
        // System.err.println("Type of ending activity is not the same as type of previously started
        // activity.");
        throw new RuntimeException(
            "Type of ending activity is not the same as type of previously started activity.");
      }
    }
  }
Esempio n. 21
0
  public static void main(String[] args) {
    City a = new City("A");
    City b = new City("B");
    City c = new City("C");
    City d = new City("D");
    City e = new City("E");
    a.neighbours = new Vector<Route>();
    a.neighbours.add(new Route(b, 5));
    a.neighbours.add(new Route(d, 5));
    a.neighbours.add(new Route(e, 7));
    b.neighbours = new Vector<Route>();
    b.neighbours.add(new Route(c, 4));
    c.neighbours = new Vector<Route>();
    c.neighbours.add(new Route(d, 8));
    c.neighbours.add(new Route(e, 2));
    d.neighbours = new Vector<Route>();
    d.neighbours.add(new Route(c, 8));
    d.neighbours.add(new Route(e, 6));
    e.neighbours = new Vector<Route>();
    e.neighbours.add(new Route(b, 3));

    City[] vertices = {a, b, c, d, e};
    HashMap<String, City> edges = new HashMap<String, City>();
    for (City _city : vertices) {
      edges.put(_city.name, _city);
    }
    String[] cities = new String[vertices.length];
    for (int i = 0; i < vertices.length; i++) {
      cities[i] = vertices[i].name;
    }

    computePaths(a);
    /**
     * for (City v : vertices) { System.out.println("Distance to " + v + ": " + v.minDistance);
     * List<City> path = getShortestPathTo(v); System.out.println("Path: " + path); }
     */
    Scanner scanner = new Scanner(System.in);
    String input = null;
    String[] inputsplit = null;
    while (true) {
      input = scanner.next();
      if (input.equalsIgnoreCase("quit")) {
        break;
      }
      inputsplit = input.split("-");
      Trip trip = new Trip();
      Route lastvisited = trip.route.lastElement();
      for (String str : inputsplit) {
        System.out.print(str + ' ');
        City city;
        if (edges.containsKey(str)) {
          city = edges.get(str);
        } else {
          System.out.println("NO SUCH City"); // TODO change name
          break;
        }

        if (trip.route == null) {
          trip.addRoute(edges.get(city.name));
        }

        System.out.println(trip.toString());
      }
      System.out.println(trip.distance);
    }
  }
Esempio n. 22
0
 private void parseStopTimes(BufferedReader reader) throws IOException {
   HashSet<String> processedStopTimes = new HashSet<>();
   Calendar wholeDay = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
   wholeDay.setTimeInMillis(0);
   Date dayBeginning = wholeDay.getTime();
   wholeDay.add(Calendar.DAY_OF_YEAR, 1);
   wholeDay.add(Calendar.MILLISECOND, -1);
   Date dayEnd = wholeDay.getTime();
   SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
   String line = reader.readLine(); // skip column names
   while ((line = reader.readLine()) != null) {
     // trip_id,arrival_time,departure_time,stop_id,stop_sequence,shape_dist_traveled
     String[] split = line.split(",");
     if (split.length < 6) {
       write(line);
       continue;
     }
     Integer tripId = trips.get(split[0]);
     Trip trip = tripId != null ? Trip.findTrip(tripId) : null;
     Integer stopId = stops.get(split[3]);
     Stop stop = Stop.findStop(stopId);
     if (trip != null && stop != null) {
       try {
         Date arrival = format.parse(split[1].replace("\"", ""));
         Date startTime = trip.getStartTime();
         if (startTime == null || arrival.before(startTime)) {
           trip.setStartTime(arrival);
         }
       } catch (ParseException e) {
         write(line);
         continue;
       }
       try {
         Date departure = format.parse(split[2].replace("\"", ""));
         Date endTime = trip.getEndTime();
         if (endTime == null || departure.after(endTime)) {
           trip.setEndTime(departure);
         }
       } catch (ParseException e) {
         write(line);
         continue;
       }
       if (trip.getStartTime() != null && trip.getEndTime() != null) {
         Calendar diff = Calendar.getInstance();
         diff.setTimeInMillis(trip.getEndTime().getTime() - trip.getStartTime().getTime());
         if (diff.get(Calendar.DAY_OF_YEAR) > 1) {
           trip.setStartTime(dayBeginning);
           trip.setEndTime(dayEnd);
         }
       }
       String stopTimeKey = split[3] + ":" + tripId + ":" + stopId;
       if (!processedStopTimes.contains(stopTimeKey)) {
         StopTime stopTime = new StopTime();
         stopTime.setSequence(Integer.parseInt(split[4].replace("\"", "").trim()));
         stopTime.setTrip(trip);
         stopTime.setStop(stop);
         processedStopTimes.add(stopTimeKey);
         stopTime.persist();
       }
     }
   }
 }
  public void writeSimulationResultsToTabSeparated(String path, String appendage)
      throws IOException {
    String actTableName;
    String journeyTableName;
    String transferTableName;
    String tripTableName;
    if (appendage.matches("[a-zA-Z0-9]*[_]*")) {
      actTableName = appendage + "matsim_activities.txt";
      journeyTableName = appendage + "matsim_journeys.txt";
      transferTableName = appendage + "matsim_transfers.txt";
      tripTableName = appendage + "matsim_trips.txt";
    } else {
      if (appendage.matches("[a-zA-Z0-9]*")) appendage = "_" + appendage;
      actTableName = "matsim_activities" + appendage + ".txt";
      journeyTableName = "matsim_journeys" + appendage + ".txt";
      transferTableName = "matsim_transfers" + appendage + ".txt";
      tripTableName = "matsim_trips" + appendage + ".txt";
    }
    BufferedWriter activityWriter = IOUtils.getBufferedWriter(path + "/" + actTableName);

    activityWriter.write(
        "activity_id\tperson_id\tfacility_id\ttype\t"
            + "start_time\tend_time\tx\ty\tsample_selector\n");

    BufferedWriter journeyWriter = IOUtils.getBufferedWriter(path + "/" + journeyTableName);
    journeyWriter.write(
        "journey_id\tperson_id\tstart_time\t"
            + "end_time\tdistance\tmain_mode\tfrom_act\tto_act\t"
            + "in_vehicle_distance\tin_vehicle_time\t"
            + "access_walk_distance\taccess_walk_time\taccess_wait_time\t"
            + "first_boarding_stop\tegress_walk_distance\t"
            + "egress_walk_time\tlast_alighting_stop\t"
            + "transfer_walk_distance\ttransfer_walk_time\t"
            + "transfer_wait_time\tsample_selector\n");

    BufferedWriter tripWriter = IOUtils.getBufferedWriter(path + "/" + tripTableName);
    tripWriter.write(
        "trip_id\tjourney_id\tstart_time\tend_time\t"
            + "distance\tmode\tline\troute\tboarding_stop\t"
            + "alighting_stop\tsample_selector\n");

    BufferedWriter transferWriter = IOUtils.getBufferedWriter(path + "/" + transferTableName);
    transferWriter.write(
        "transfer_id\tjourney_id\tstart_time\t"
            + "end_time\tfrom_trip\tto_trip\twalk_distance\t"
            + "walk_time\twait_time\tsample_selector\n");

    // read a static field that increments with every inheriting object constructed
    Counter counter = new Counter("Output lines written: ");
    for (Entry<Id, TravellerChain> entry : chains.entrySet()) {
      String pax_id = entry.getKey().toString();
      TravellerChain chain = entry.getValue();
      for (Activity act : chain.getActs()) {
        try {
          activityWriter.write(
              String.format(
                  "%d\t%s\t%s\t%s\t%d\t%d\t%f\t%f\t%f\n",
                  act.getElementId(),
                  pax_id,
                  act.getFacility(),
                  act.getType(),
                  (int) act.getStartTime(),
                  (int) act.getEndTime(),
                  act.getCoord().getX(),
                  act.getCoord().getY(),
                  MatsimRandom.getRandom().nextDouble()));
        } catch (Exception e) {
          System.out.println("Couldn't print activity chain!");
        }
      }
      for (Journey journey : chain.getJourneys()) {
        try {
          journeyWriter.write(
              String.format(
                  "%d\t%s\t%d\t%d\t%.3f\t%s\t%d\t%d\t%.3f\t%d\t%.3f\t%d\t%d\t%s\t%.3f\t%d\t%s\t%.3f\t%d\t%d\t%f\n",
                  journey.getElementId(),
                  pax_id,
                  (int) journey.getStartTime(),
                  (int) journey.getEndTime(),
                  journey.getDistance(),
                  journey.getMainMode(),
                  journey.getFromAct().getElementId(),
                  journey.getToAct().getElementId(),
                  journey.getInVehDistance(),
                  (int) journey.getInVehTime(),
                  journey.getAccessWalkDistance(),
                  (int) journey.getAccessWalkTime(),
                  (int) journey.getAccessWaitTime(),
                  journey.getFirstBoardingStop(),
                  journey.getEgressWalkDistance(),
                  (int) journey.getEgressWalkTime(),
                  journey.getLastAlightingStop(),
                  journey.getTransferWalkDistance(),
                  (int) journey.getTransferWalkTime(),
                  (int) journey.getTransferWaitTime(),
                  MatsimRandom.getRandom().nextDouble()));
          counter.incCounter();

          if (!(journey.isCarJourney() || journey.isTeleportJourney())) {
            for (Trip trip : journey.getTrips()) {
              tripWriter.write(
                  String.format(
                      "%d\t%d\t%d\t%d\t%.3f\t%s\t%s\t%s\t%s\t%s\t%f\n",
                      trip.getElementId(),
                      journey.getElementId(),
                      (int) trip.getStartTime(),
                      (int) trip.getEndTime(),
                      trip.getDistance(),
                      trip.getMode(),
                      trip.getLine(),
                      trip.getRoute(),
                      trip.getBoardingStop(),
                      trip.getAlightingStop(),
                      MatsimRandom.getRandom().nextDouble()));
              counter.incCounter();
            }
            for (Transfer transfer : journey.getTransfers()) {
              transferWriter.write(
                  String.format(
                      "%d\t%d\t%d\t%d\t%d\t%d\t%.3f\t%d\t%d\t%f\n",
                      transfer.getElementId(),
                      journey.getElementId(),
                      (int) transfer.getStartTime(),
                      (int) transfer.getEndTime(),
                      transfer.getFromTrip().getElementId(),
                      transfer.getToTrip().getElementId(),
                      transfer.getWalkDistance(),
                      (int) transfer.getWalkTime(),
                      (int) transfer.getWaitTime(),
                      MatsimRandom.getRandom().nextDouble()));

              counter.incCounter();
            }
          } else {
            for (Trip trip : journey.getTrips()) {

              tripWriter.write(
                  String.format(
                      "%d\t%d\t%d\t%d\t%.3f\t%s\t%s\t%s\t%s\t%s\t%f\n",
                      trip.getElementId(),
                      journey.getElementId(),
                      (int) trip.getStartTime(),
                      (int) trip.getEndTime(),
                      journey.isTeleportJourney() ? 0.000 : trip.getDistance(),
                      trip.getMode(),
                      "",
                      "",
                      "",
                      "",
                      MatsimRandom.getRandom().nextDouble()));

              counter.incCounter();
            }
          }
        } catch (NullPointerException e) {
          setStuck(getStuck() + 1);
        }
      }
    }

    activityWriter.close();
    journeyWriter.close();
    tripWriter.close();
    transferWriter.close();
    counter.printCounter();
  }
Esempio n. 24
0
 /**
  * Adds a trip
  *
  * @param trip != null
  */
 public void addTrip(Trip trip) {
   if (!trips.contains(trip)) {
     trips.add(trip);
     trip.addCompanion(this);
   }
 }
  @Override
  public String execute(ApplicationContext context) {

    String authenticated = super.execute(context);
    if (authenticated == null || !authenticated.equals(Role.STAFF.name())) {
      return PAGE.COMMON.LOGIN;
    }

    System.out.println("Approving... Trip Notification!");

    // get parameter from browser
    String notificationIdParam = context.getParameter("nofId");
    String notificationParam = context.getParameter("notification");
    String tripNoParam = context.getParameter("tripNo");
    String routeNoParam = context.getParameter("routeNo");
    String routeTypeParam = context.getParameter("routeType");

    if (tripNoParam == null
        || routeNoParam == null
        || notificationParam == null
        || notificationIdParam == null) {
      return Config.AJAX_FORMAT;
    }

    int nofId, tripNo, routeNo;
    try {
      tripNo = Integer.parseInt(tripNoParam);
      routeNo = Integer.parseInt(routeNoParam);
      nofId = Integer.parseInt(notificationIdParam);
      RouteType routeType = RouteType.valueOf(routeTypeParam);

      TripDAO tripDAO = new TripDAO();
      RouteDAO routeDAO = new RouteDAO();
      TripNotificationDAO tripNofDao = new TripNotificationDAO();

      Route route = routeDAO.getRoutebyRouteNo(routeNo, routeType);
      if (route != null) {
        Trip trip = tripDAO.readTripByRouteAndNo(route, tripNo);
        if (trip != null) {
          TripNotification tripNof = tripNofDao.readTripNof(routeNo, tripNo, routeType);
          if (tripNof != null) {
            // if type = 0 -> update change
            if (tripNof.getType() == 0) {
              if (tripNof.getChangeStartTime() != null) {
                trip.setStartTime(tripNof.getChangeStartTime());
              }
              if (tripNof.getChangeEndTime() != null) {
                trip.setEndTime(tripNof.getChangeEndTime());
              }
            }
            // if type = 1 -> insert new trip
            if (tripNof.getType() == 1) {
              Trip tripNew = new Trip();
              tripNew.setStartTime(tripNof.getChangeStartTime());
              tripNew.setEndTime(tripNof.getChangeEndTime());
              tripNew.setTripNo(tripNo);
              tripNew.setRoute(route);
              // build connection
              BuildUtils build = new BuildUtils();
              build.buildCon(route, trip);
              tripDAO.create(tripNew);
            }
            // if type = 2 -> remove trip
            if (tripNof.getType() == 2) {
              tripDAO.deleteTrip(trip);
            }
          }
        }
      }

    } catch (NumberFormatException ex) {
      ex.printStackTrace();
    }

    // reverse string
    /*String[] content = notificationParam.split("~");
            String[] nof = content[1].trim().split(",");

            Map<String, String> result = new HashMap<String, String>();
            for (String str : nof) {
                TripNofUtils utils = new TripNofUtils(str.trim());
                utils.reverse(result);
            }

            String startTime = null, endTime = null;
            String resultStartTime = result.get(TripNofUtils.KEY_STARTTIME);
            if (resultStartTime != null) {
                startTime = resultStartTime;
            }
            String resultEndTime = result.get(TripNofUtils.KEY_ENDTIME);
            if (resultEndTime != null) {
                endTime = resultEndTime;
            }
    */
    // approve trip
    // approve(nofId, tripNo, routeNo, RouteType.valueOf(routeTypeParam.toUpperCase()), startTime,
    // endTime);

    return Config.AJAX_FORMAT;
  }
Esempio n. 26
0
  public static void main(String[] args) throws ClassNotFoundException {
    String username = "******"; // Ändra username här
    // Ändra Auth tillhörande ditt spotify-account
    String OAuthToken =
        "BQB3W-ODBi1wq3gQWYwByWrRzshSd_LxRDBWBmI9L1VIh9MVGJeDm9vDYib2T1aebBiR9ghPbqqU8aI9oyeI3PWR-sggQtNfOjjNNXA3bo9AQxlIb3zNVJ24ZcmXGrPQ6pp3epObUrxC9lLohP39w-B8TQlGunisPxiwQrg9C-2K_K_dC5-3Dq9-wgdohH61RzXv32zwiNjNLcmrVFdARzgjNjFdY2Wo1Jiu";

    WebService ws = new WebService();
    JsonReader jr = new JsonReader(OAuthToken);

    setPort(8081);

    get(
        "/trip",
        (req, res) -> {
          System.out.println("-- Trip called --");
          res.header("Access-Control-Allow-Origin", "*");
          String from = req.queryParams("from");
          String to = req.queryParams("to");
          String key = "4651be79-347f-45e5-8eac-2062d752068c";
          ArrayList<Trip> trips =
              jr.getTrips(
                  "https://api.resrobot.se/trip?key="
                      + key
                      + "&originId="
                      + from
                      + "&destId="
                      + to
                      + "&format=json");
          System.out.println(ws.buildJsonObject(trips));
          return ws.buildJsonObject(trips);
        });

    get(
        "/location",
        (req, res) -> {
          System.out.println("-- Station called --");
          res.header("Access-Control-Allow-Origin", "*");
          String name = req.queryParams("name");
          String key = "4651be79-347f-45e5-8eac-2062d752068c";
          return jr.getLocations(
              "https://api.resrobot.se/location.name.json?key=" + key + "&input=" + name);
        });

    get(
        "/trip/playlist",
        (req, res) -> {
          res.header("Access-Control-Allow-Origin", "*");
          String from = req.queryParams("from");
          String to = req.queryParams("to");
          String x = req.queryParams("id");
          int identi = Integer.parseInt(x);
          String key = "4651be79-347f-45e5-8eac-2062d752068c";
          ArrayList<Trip> trips =
              jr.getSpotifyTrips(
                  "https://api.resrobot.se/trip?key="
                      + key
                      + "&originId="
                      + from
                      + "&destId="
                      + to
                      + "&format=json");
          JSONObject jsonPlaylist =
              jr.createPlaylist(
                  "https://api.spotify.com/v1/users/" + username + "/playlists", "Spellista " + x);
          String url = "";
          for (Trip trip : trips) {
            if (Integer.parseInt(trip.getId()) == identi) {
              for (Track track : trip.getTracks()) {
                if (url.length() < 1) {
                  url += track.getUrl();
                } else {
                  url += "," + track.getUrl();
                }
              }
            }
          }
          String playlistID = jsonPlaylist.getString("id");
          jr.addTracks(
              "https://api.spotify.com/v1/users/"
                  + username
                  + "/playlists/"
                  + playlistID
                  + "/tracks?uris="
                  + url);
          return jsonPlaylist.getJSONObject("external_urls").getString("spotify");
        });

    get(
        "/playlist",
        (req, res) -> {
          res.header("Access-Control-Allow-Origin", "*");
          String x = req.queryParams("ms");
          String playlistName = req.queryParams("name");
          int duration = Integer.parseInt(x);
          ArrayList<Track> tracks = jr.getSpotifyTracks(duration);
          JSONObject jsonPlaylist =
              jr.createPlaylist(
                  "https://api.spotify.com/v1/users/" + username + "/playlists", playlistName);
          String url = "";
          for (Track track : tracks) {
            if (url.length() < 1) {
              url += track.getUrl();
            } else {
              url += "," + track.getUrl();
            }
          }
          String playlistID = jsonPlaylist.getString("id");
          jr.addTracks(
              "https://api.spotify.com/v1/users/"
                  + username
                  + "/playlists/"
                  + playlistID
                  + "/tracks?uris="
                  + url);
          return jsonPlaylist.getJSONObject("external_urls").getString("spotify");
        });
  }
Esempio n. 27
0
  public static void main(String[] args) {
    // Parameters
    Integer planningAreaId = 11000000;

    boolean onlyCar = false; // car; new, should be used for runs with ChangeLedModes enabled

    boolean onlyInterior = false; // int
    boolean onlyBerlinBased = true; // ber; usually varied for analysis

    boolean distanceFilter = true; // dist; usually varied for analysis
    // double minDistance = 0;
    double maxDistance = 100;

    boolean onlyWorkTrips = false; // NEW

    // --------------------------------------------------------------------------------------------------
    boolean ageFilter = false;
    Integer minAge = 80;
    Integer maxAge = 119;
    // --------------------------------------------------------------------------------------------------

    String runId = "run_168a";
    //		String runId = "run791";
    String usedIteration = "300"; // most frequently used value: 150
    //		String usedIteration = "600";

    int maxBinDuration = 120;
    int binWidthDuration = 1;
    // int binWidthDuration = 5;

    int maxBinTime = 23;
    int binWidthTime = 1;

    int maxBinDistance = 60;
    int binWidthDistance = 1;
    // int binWidthDistance = 5;

    int maxBinSpeed = 60;
    int binWidthSpeed = 1;
    // int binWidthSpeed = 5;

    // Input and output files
    String networkFile =
        "/Users/dominik/Workspace/shared-svn/studies/countries/de/berlin/counts/iv_counts/network.xml";
    //	    String networkFile =
    // "D:/Workspace/shared-svn/studies/countries/de/berlin/counts/iv_counts/network.xml";
    //	    String networkFile = "D:/Workspace/runs-svn/"  + runId +
    // "/counts_network_merged.xml_cl.xml.gz";

    //	    String eventsFile = "D:/Workspace/data/cemdapMatsimCadyts/output/" + runId + "/ITERS/it."
    // + usedIteration + "/"
    //	    String eventsFile = "D:/Workspace/runs-svn/" + runId + "/output_rerun/ITERS/it." +
    // usedIteration + "/"
    //	    		+ runId + "." + usedIteration + ".events.txt.gz";
    //	    String eventsFile = "D:/Workspace/runs-svn/cemdapMatsimCadyts/" + runId + "/ITERS/it." +
    // usedIteration + "/"
    //				+ runId + "." + usedIteration + ".events.xml.gz";
    String eventsFile =
        "/Users/dominik/Workspace/runs-svn/cemdapMatsimCadyts/"
            + runId
            + "/ITERS/it."
            + usedIteration
            + "/"
            + runId
            + "."
            + usedIteration
            + ".events.xml.gz";

    //	    String cemdapPersonFile =
    // "D:/Workspace/data/cemdapMatsimCadyts/input/cemdap_berlin/19/persons1.dat"; // wrong!!!
    //	    String cemdapPersonFile =
    // "D:/Workspace/data/cemdapMatsimCadyts/input/cemdap_berlin/18/persons1.dat";
    //	    String cemdapPersonFile =
    // "D:/Workspace/data/cemdapMatsimCadyts/input/cemdap_berlin/21/persons1.dat";
    String cemdapPersonFile =
        "/Users/dominik/Workspace/data/cemdapMatsimCadyts/input/cemdap_berlin/21/persons1.dat";

    // String outputDirectory = "D:/Workspace/data/cemdapMatsimCadyts/output/" + runId +
    // "/analysis";
    //	    String outputDirectory = "D:/Workspace/runs-svn/cemdapMatsimCadyts/" + runId +
    // "/analysis";
    String outputDirectory =
        "/Users/dominik/Workspace/runs-svn/cemdapMatsimCadyts/" + runId + "/analysis";
    //	    String outputDirectory = "D:/Workspace/runs-svn/other/" + runId + "/analysis";

    //	    String shapeFileBerlin =
    // "D:/Workspace/data/cemdapMatsimCadyts/input/shapefiles/Berlin_DHDN_GK4.shp";
    String shapeFileBerlin =
        "/Users/dominik/Workspace/data/cemdapMatsimCadyts/input/shapefiles/Berlin_DHDN_GK4.shp";
    Map<Integer, Geometry> zoneGeometries = ShapeReader.read(shapeFileBerlin, "NR");
    Geometry berlinGeometry = zoneGeometries.get(planningAreaId);

    // Output naming
    Integer usedIt = Integer.parseInt(usedIteration);
    if (!usedIt.equals(150)) {
      outputDirectory = outputDirectory + "_" + usedIteration;
    }

    // --------------------------------------------------------------------------------------------------
    if (onlyCar == true) {
      outputDirectory = outputDirectory + "_car";
    }
    // --------------------------------------------------------------------------------------------------

    if (onlyInterior == true) {
      outputDirectory = outputDirectory + "_int";
    }

    if (onlyBerlinBased == true) {
      outputDirectory = outputDirectory + "_ber";
    }

    if (distanceFilter == true) {
      outputDirectory = outputDirectory + "_dist";
    }

    // --------------------------------------------------------------------------------------------------
    if (onlyWorkTrips == true) {
      outputDirectory = outputDirectory + "_work";
    }
    // --------------------------------------------------------------------------------------------------

    // --------------------------------------------------------------------------------------------------
    if (ageFilter == true) {
      outputDirectory = outputDirectory + "_" + minAge.toString();
      outputDirectory = outputDirectory + "_" + maxAge.toString();
    }
    // --------------------------------------------------------------------------------------------------

    // Create an EventsManager instance (MATSim infrastructure)
    EventsManager eventsManager = EventsUtils.createEventsManager();
    TripHandler handler = new TripHandler();
    eventsManager.addHandler(handler);

    // Connect a file reader to the EventsManager and read in the event file
    MatsimEventsReader reader = new MatsimEventsReader(eventsManager);
    reader.readFile(eventsFile);
    System.out.println("Events file read!");

    // check if all trips have been completed; if so, result will be zero
    int numberOfIncompleteTrips = 0;
    for (Trip trip : handler.getTrips().values()) {
      if (!trip.getTripComplete()) {
        numberOfIncompleteTrips++;
      }
    }
    System.out.println(numberOfIncompleteTrips + " trips are incomplete.");

    // --------------------------------------------------------------------------------------------------
    CemdapPersonFileReader cemdapPersonFileReader = new CemdapPersonFileReader();
    if (ageFilter == true) {
      // TODO needs to be adapted for other analyses that are based on person-specific attributes as
      // well
      // so far age is the only one
      // parse person file

      cemdapPersonFileReader.parse(cemdapPersonFile);
    }
    // --------------------------------------------------------------------------------------------------

    // get network, which is needed to calculate distances
    Config config = ConfigUtils.createConfig();
    Scenario scenario = ScenarioUtils.createScenario(config);
    MatsimNetworkReader networkReader = new MatsimNetworkReader(scenario);
    networkReader.readFile(networkFile);
    Network network = scenario.getNetwork();

    // create objects
    int tripCounter = 0;
    int tripCounterSpeed = 0;
    int tripCounterIncomplete = 0;

    Map<Integer, Double> tripDurationMap = new TreeMap<Integer, Double>();
    double aggregateTripDuration = 0.;

    Map<Integer, Double> departureTimeMap = new TreeMap<Integer, Double>();

    Map<String, Double> activityTypeMap = new TreeMap<String, Double>();

    Map<Integer, Double> tripDistanceRoutedMap = new TreeMap<Integer, Double>();
    double aggregateTripDistanceRouted = 0.;

    Map<Integer, Double> tripDistanceBeelineMap = new TreeMap<Integer, Double>();
    double aggregateTripDistanceBeeline = 0.;

    Map<Integer, Double> averageTripSpeedRoutedMap = new TreeMap<Integer, Double>();
    double aggregateOfAverageTripSpeedsRouted = 0.;

    Map<Integer, Double> averageTripSpeedBeelineMap = new TreeMap<Integer, Double>();
    double aggregateOfAverageTripSpeedsBeeline = 0.;

    int numberOfTripsWithNoCalculableSpeed = 0;

    Map<Id<Trip>, Double> distanceRoutedMap = new TreeMap<Id<Trip>, Double>();
    Map<Id<Trip>, Double> distanceBeelineMap = new TreeMap<Id<Trip>, Double>();

    Map<String, Integer> otherInformationMap = new TreeMap<String, Integer>();

    // --------------------------------------------------------------------------------------------------
    ObjectAttributes personActivityAttributes = new ObjectAttributes();
    // --------------------------------------------------------------------------------------------------

    // do calculations
    for (Trip trip : handler.getTrips().values()) {
      if (trip.getTripComplete()) {
        boolean considerTrip = false;

        // get coordinates of links
        Id<Link> departureLinkId = trip.getDepartureLinkId();
        Id<Link> arrivalLinkId = trip.getArrivalLinkId();

        Link departureLink = network.getLinks().get(departureLinkId);
        Link arrivalLink = network.getLinks().get(arrivalLinkId);

        double arrivalCoordX = arrivalLink.getCoord().getX();
        double arrivalCoordY = arrivalLink.getCoord().getY();
        double departureCoordX = departureLink.getCoord().getX();
        double departureCoordY = departureLink.getCoord().getY();

        // calculate (beeline) distance
        double horizontalDistanceInMeter = (Math.abs(departureCoordX - arrivalCoordX)) / 1000;
        double verticalDistanceInMeter = (Math.abs(departureCoordY - arrivalCoordY)) / 1000;

        double tripDistanceBeeline =
            Math.sqrt(
                horizontalDistanceInMeter * horizontalDistanceInMeter
                    + verticalDistanceInMeter * verticalDistanceInMeter);

        // create points
        Point arrivalLocation = MGC.xy2Point(arrivalCoordX, arrivalCoordY);
        Point departureLocation = MGC.xy2Point(departureCoordX, departureCoordY);

        // choose if trip will be considered
        // Note: Check of "interior"/"berlinBased" has to come first since this sets the
        // "considerTrip"
        // variable to true.
        if (onlyInterior == true) {
          if (berlinGeometry.contains(arrivalLocation)
              && berlinGeometry.contains(departureLocation)) {
            considerTrip = true;
          }
        } else if (onlyBerlinBased == true) {
          if (berlinGeometry.contains(arrivalLocation)
              || berlinGeometry.contains(departureLocation)) {
            considerTrip = true;
          }
        } else {
          considerTrip = true;
        }

        // --------------------------------------------------------------------------------------------------
        //				if (!trip.getMode().equals("car") && !trip.getMode().equals("pt")) {
        //					throw new RuntimeException("In current implementation leg mode must either be car or
        // pt");
        //				}

        if (onlyCar == true) {
          if (!trip.getMode().equals("car")) {
            considerTrip = false;
          }
        }
        // --------------------------------------------------------------------------------------------------

        if (distanceFilter == true && tripDistanceBeeline >= maxDistance) {
          considerTrip = false;
        }

        //	    		if (distanceFilter == true && tripDistanceBeeline <= minDistance) {
        //	    			considerTrip = false;
        //	    		}

        // --------------------------------------------------------------------------------------------------------------------
        if (onlyWorkTrips == true) {
          boolean doesWorkTrip = false;
          if (trip.getActivityEndActType().equals("work")) {
            doesWorkTrip = true;
          }

          if (doesWorkTrip == true) { // can be varied
            considerTrip = false;
          }
        }
        // --------------------------------------------------------------------------------------------------------------------

        // write person activity attributes
        //	    		if (trip.getActivityEndActType().equals("work")) {
        //	    			personActivityAttributes.putAttribute(trip.getDriverId(), "hasWorkActivity",
        // true);
        //	    		}
        // TODO The plan was to claculated activity-chain frequencies here...

        // --------------------------------------------------------------------------------------------------
        // PERSON-SPECIFIC ATTRIBUTES
        if (ageFilter == true) {
          // TODO needs to be adapted for other analyses that are based on person-specific
          // attributes as well
          // so far age is the only one
          String personId = trip.getPersonId().toString();
          int age =
              (int) cemdapPersonFileReader.getPersonAttributes().getAttribute(personId, "age");

          if (age < minAge) {
            considerTrip = false;
          }
          if (age > maxAge) {
            considerTrip = false;
          }
        }
        // --------------------------------------------------------------------------------------------------

        if (considerTrip == true) {
          tripCounter++;

          // calculate travel times and store them in a map
          // trip.getArrivalTime() / trip.getDepartureTime() yields values in seconds!
          double departureTimeInSeconds = trip.getDepartureTime();
          double arrivalTimeInSeconds = trip.getArrivalTime();
          double tripDurationInSeconds = arrivalTimeInSeconds - departureTimeInSeconds;
          double tripDurationInMinutes = tripDurationInSeconds / 60.;
          double tripDurationInHours = tripDurationInMinutes / 60.;
          // addToMapIntegerKey(tripDurationMap, tripDurationInMinutes, 5, 120);
          addToMapIntegerKey(
              tripDurationMap, tripDurationInMinutes, binWidthDuration, maxBinDuration, 1.);
          aggregateTripDuration = aggregateTripDuration + tripDurationInMinutes;

          // store departure times in a map
          double departureTimeInHours = departureTimeInSeconds / 3600.;
          addToMapIntegerKey(departureTimeMap, departureTimeInHours, binWidthTime, maxBinTime, 1.);

          // store activities in a map
          String activityType = trip.getActivityStartActType();
          addToMapStringKey(activityTypeMap, activityType);

          // calculate (routed) distances and and store them in a map
          double tripDistanceMeter = 0.;
          for (int i = 0; i < trip.getLinks().size(); i++) {
            Id<Link> linkId = trip.getLinks().get(i);
            Link link = network.getLinks().get(linkId);
            double length = link.getLength();
            tripDistanceMeter = tripDistanceMeter + length;
          }
          // TODO here, the distances from activity to link and link to activity are missing!
          double tripDistanceRouted = tripDistanceMeter / 1000.;

          // store (routed) distances  in a map
          addToMapIntegerKey(
              tripDistanceRoutedMap, tripDistanceRouted, binWidthDistance, maxBinDistance, 1.);
          aggregateTripDistanceRouted = aggregateTripDistanceRouted + tripDistanceRouted;
          distanceRoutedMap.put(trip.getTripId(), tripDistanceRouted);

          // store (beeline) distances in a map
          addToMapIntegerKey(
              tripDistanceBeelineMap, tripDistanceBeeline, binWidthDistance, maxBinDistance, 1.);
          aggregateTripDistanceBeeline = aggregateTripDistanceBeeline + tripDistanceBeeline;
          distanceBeelineMap.put(trip.getTripId(), tripDistanceBeeline);

          // calculate speeds and and store them in a map
          if (tripDurationInHours > 0.) {
            // System.out.println("trip distance is " + tripDistance + " and time is " +
            // timeInHours);
            double averageTripSpeedRouted = tripDistanceRouted / tripDurationInHours;
            addToMapIntegerKey(
                averageTripSpeedRoutedMap, averageTripSpeedRouted, binWidthSpeed, maxBinSpeed, 1.);
            aggregateOfAverageTripSpeedsRouted =
                aggregateOfAverageTripSpeedsRouted + averageTripSpeedRouted;

            double averageTripSpeedBeeline = tripDistanceBeeline / tripDurationInHours;
            addToMapIntegerKey(
                averageTripSpeedBeelineMap,
                averageTripSpeedBeeline,
                binWidthSpeed,
                maxBinSpeed,
                1.);
            aggregateOfAverageTripSpeedsBeeline =
                aggregateOfAverageTripSpeedsBeeline + averageTripSpeedBeeline;

            tripCounterSpeed++;
          } else {
            numberOfTripsWithNoCalculableSpeed++;
          }
        }
      } else {
        System.err.println("Trip is not complete!");
        tripCounterIncomplete++;
        // Until now, the only case where incomplete trips happen is when agents are removed
        // according to "removeStuckVehicles = true"
        // Since a removed agent can at most have one incomplete trip (this incomplete trip is
        // exactly the event when he is removed)
        // the number of incomplete trips should be equal to the number of removed agents
      }
    }

    double averageTripDuration = aggregateTripDuration / tripCounter;
    double averageTripDistanceRouted = aggregateTripDistanceRouted / tripCounter;
    double averageTripDistanceBeeline = aggregateTripDistanceBeeline / tripCounter;
    double averageOfAverageTripSpeedsRouted = aggregateOfAverageTripSpeedsRouted / tripCounterSpeed;
    double averageOfAverageTripSpeedsBeeline =
        aggregateOfAverageTripSpeedsBeeline / tripCounterSpeed;

    otherInformationMap.put(
        "Number of trips that have no previous activity",
        handler.getNoPreviousEndOfActivityCounter());
    otherInformationMap.put(
        "Number of trips that have no calculable speed", numberOfTripsWithNoCalculableSpeed);
    otherInformationMap.put(
        "Number of incomplete trips (i.e. number of removed agents)", tripCounterIncomplete);
    otherInformationMap.put("Number of (complete) trips", tripCounter);

    // write results to files
    new File(outputDirectory).mkdir();
    AnalysisFileWriter writer = new AnalysisFileWriter();
    writer.writeToFileIntegerKey(
        tripDurationMap,
        outputDirectory + "/tripDuration.txt",
        binWidthDuration,
        tripCounter,
        averageTripDuration);
    writer.writeToFileIntegerKey(
        departureTimeMap,
        outputDirectory + "/departureTime.txt",
        binWidthTime,
        tripCounter,
        averageTripDuration);
    writer.writeToFileStringKey(
        activityTypeMap, outputDirectory + "/activityTypes.txt", tripCounter);
    writer.writeToFileIntegerKey(
        tripDistanceRoutedMap,
        outputDirectory + "/tripDistanceRouted.txt",
        binWidthDistance,
        tripCounter,
        averageTripDistanceRouted);
    writer.writeToFileIntegerKey(
        tripDistanceBeelineMap,
        outputDirectory + "/tripDistanceBeeline.txt",
        binWidthDistance,
        tripCounter,
        averageTripDistanceBeeline);
    writer.writeToFileIntegerKey(
        averageTripSpeedRoutedMap,
        outputDirectory + "/averageTripSpeedRouted.txt",
        binWidthSpeed,
        tripCounterSpeed,
        averageOfAverageTripSpeedsRouted);
    writer.writeToFileIntegerKey(
        averageTripSpeedBeelineMap,
        outputDirectory + "/averageTripSpeedBeeline.txt",
        binWidthSpeed,
        tripCounterSpeed,
        averageOfAverageTripSpeedsBeeline);
    writer.writeToFileIntegerKeyCumulative(
        tripDurationMap,
        outputDirectory + "/tripDurationCumulative.txt",
        binWidthDuration,
        tripCounter,
        averageTripDuration);
    writer.writeToFileIntegerKeyCumulative(
        tripDistanceBeelineMap,
        outputDirectory + "/tripDistanceBeelineCumulative.txt",
        binWidthDistance,
        tripCounter,
        averageTripDistanceBeeline);
    writer.writeToFileIntegerKeyCumulative(
        averageTripSpeedBeelineMap,
        outputDirectory + "/averageTripSpeedBeelineCumulative.txt",
        binWidthSpeed,
        tripCounterSpeed,
        averageOfAverageTripSpeedsBeeline);
    writer.writeToFileOther(otherInformationMap, outputDirectory + "/otherInformation.txt");

    // write a routed distance vs. beeline distance comparison file
    writer.writeRoutedBeelineDistanceComparisonFile(
        distanceRoutedMap, distanceBeelineMap, outputDirectory + "/beeline.txt", tripCounter);
  }
Esempio n. 28
0
 public void addTrip(Trip trip) {
   trip.setRoute(this);
   trips.add(trip);
 }