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
#include <kooling/component/classifier/interface.h>
#include <kooling/component/classifier/rail.h>
#include <kooling/component/osm/interface.h>
#include <kooling/datamodel/distance.h>
#include <kooling/datamodel/timestamp.h>
#include <kooling/datamodel/transport.h>
#include <kooling/datamodel/trip.h>
#include <kooling/datamodel/sensor.h>
#include <kooling/datamodel/motion-type.h>
#include <kooling/geo/algorithm.h>
#include <kooling/geo/geometry.h>
#include <kooling/geo/coordinate.h>
#include <kooling/system/random.h>

#include <plog/Log.h>
#include <plog/Severity.h>

#include <boost/format.hpp>
#include <boost/range/adaptor/filtered.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <boost/range/algorithm/copy.hpp>
#include <boost/range/algorithm/count_if.hpp>
#include <boost/range/algorithm/max_element.hpp>
#include <boost/range/numeric.hpp>

#include <cmath>
#include <initializer_list>
#include <optional>
#include <sstream>
#include <string>
#include <vector>

namespace kooling::component::classifier {

using coordinate_t        = kooling::geo::coordinate;
using fingerprint_t       = kooling::datamodel::fingerprint;
using distance_t          = kooling::datamodel::distance;
using motion_type_t       = kooling::datamodel::motion_type;
using segment_t           = kooling::datamodel::segment;
using segments_t          = kooling::datamodel::segments;
using sensor_data_point_t = kooling::datamodel::sensor_data_point;
using sensor_data_t       = kooling::datamodel::sensor_data;
using speed_t             = kooling::datamodel::speed;
using timestamp_t         = kooling::datamodel::timestamp;
using transport_t         = kooling::datamodel::transport;
using trip_t              = kooling::datamodel::trip;
using trips_t             = kooling::datamodel::trips;
using user_t              = kooling::datamodel::user;

class v1 : public interface
{
    struct ctor_tag {};

public:
    explicit v1(ctor_tag, const json_t&);

    ~v1() override = default;

    static interface::pointer_type create(const json_t& config)
    {
        return std::make_unique<v1>(ctor_tag{}, config);
    }

    static std::string name()
    {
        return "v1";
    }

    void run(user_t, fingerprint_t, segments_t, timestamp_t) override;

private:
    const struct airplane_params
    {
        explicit airplane_params(const json_t& config)
            : min_distance{ distance_t::from_km(config["min_distance_km"]) }
            , min_speed   { speed_t::from_kmh(config["min_speed_kmh"]) }
        {}

        const distance_t min_distance;
        const speed_t    min_speed;
    } d_airplane_params;

    const rail d_rail;

    const struct bus_params
    {
        explicit bus_params(const json_t& config)
            : max_speed{ speed_t::from_kmh(config["max_speed_kmh"]) }
            , stop     { config["stop"]  }
            , route    { config["route"] }
        {}

        const speed_t max_speed;

        const struct stop
        {
            explicit stop(const json_t& config)
                : max_speed{ speed_t::from_kmh(config["max_speed_kmh"]) }
                , vicinity { distance_t::from_m(config["max_distance_m"]) }
                , percent  { config["max_distance_percent"] }
            {}

            const speed_t    max_speed;
            const distance_t vicinity;
            const double     percent;
        } stop;

        const struct route_t
        {
            explicit route_t(const json_t& config)
                : vicinity{ distance_t::from_m(config["max_distance_m"]) }
                , percent { config["max_distance_percent"] }
            {}
            const distance_t vicinity;
            const double     percent;
        } route;

    } d_bus_params;

    const struct bicycle_params
    {
        explicit bicycle_params(const json_t& config)
            : max_avg_speed{ speed_t::from_kmh(config["max_avg_speed_kmh"]) }
            , max_speed{ speed_t::from_kmh(config["max_speed_kmh"]) }
            , min_bike_percent{ config["min_bike_percent"] }
        {}

        const speed_t max_avg_speed;
        const speed_t max_speed;
        const double  min_bike_percent;
    } d_bicycle_params;

private:
    trip_t create_trip(const user_t&, const fingerprint_t& , segment_t) const;
    transport_t analyze(const segment_t&) const;
    std::optional<transport_t> is_airplane(const segment_t&) const;
    std::optional<transport_t> is_bicycle(const segment_t&) const;
    std::optional<transport_t> is_bus(const segment_t&) const;
    std::optional<transport_t> is_car(const segment_t&) const;
};

static bool registered{ factory().register_component<v1>() };

v1::v1(ctor_tag, const json_t& config)
    : d_airplane_params{ config["airplane"] }
    , d_rail           { config }
    , d_bus_params     { config["bus"]      }
    , d_bicycle_params { config["bicycle"]  }
{}

void v1::run(user_t user, fingerprint_t fingerprint, segments_t segments, timestamp_t last_timestamp)
{
    trips_t trips;
    trips.reserve(segments.size());

    for (auto segment : segments)
    {
        trips.push_back(create_trip(user, fingerprint, std::move(segment)));<--- Consider using std::transform algorithm instead of a raw loop.
    }

    d_trip->run(std::move(user), std::move(fingerprint), std::move(trips), std::move(last_timestamp));
}

static std::string create_itin_id()
{
    return str(
        boost::format("av-%1%-%2%")
        % kooling::system::random_string(40)
        % kooling::datamodel::timestamp::now().milliseconds());
}

static int percent(const size_t num, double percent)
{
    return std::ceil(num * percent / 100.);
}

std::optional<transport_t> v1::is_airplane(const segment_t& segment) const
{
    if (segment.integrated.max_distance >= d_airplane_params.min_distance &&
        segment.integrated.max_speed >= d_airplane_params.min_speed)
    {
            PLOG_DEBUG << segment.id << ": is_airplane - yes";
            return +transport_t::plane;
    }

    PLOG_DEBUG
        << segment.id << ": is_airplane - no, required "
        << d_airplane_params.min_distance.km() << " km and "
        << d_airplane_params.min_speed.kmh() << " km/h, found "
        << segment.integrated.max_distance.km() << " km and "
        << segment.integrated.max_speed.kmh() << " km/h";
    return {};
}

std::optional<transport_t> v1::is_bicycle(const segment_t& segment) const
{
    using namespace boost::adaptors;

    if (segment.integrated.speed > d_bicycle_params.max_avg_speed)
    {
        PLOG_DEBUG
            << segment.id << ": is_bicycle - no: "
            << "found avg speed: " << segment.integrated.speed << ", "
            << "max: " << d_bicycle_params.max_avg_speed;
        return {};
    }

    for (const auto& dp : segment.range)
    {
        if (dp.speed > d_bicycle_params.max_speed)
        {<--- Consider using std::find_if algorithm instead of a raw loop.
            PLOG_DEBUG
                << segment.id << ": is_bicycle - no: "
                << "found speed: " << dp.speed << ", "
                << "max: " << d_bicycle_params.max_speed;
            return {};
        }
    }

    const auto nof_bike{ boost::count_if(segment.range | transformed([](const auto& dp) { return dp.motion_type; }), kooling::datamodel::is_cycling) };
    const auto min_bike{ percent(segment.nof_dps, d_bicycle_params.min_bike_percent) };
    if (nof_bike < min_bike)
    {
        PLOG_DEBUG
            << segment.id << ": is_bicycle - no: "
            << "bikes found : " << nof_bike << ", "
            << "required : " << min_bike;
        return {};
    }

    PLOG_DEBUG << segment.id << ": is_bicycle - yes";
    return +transport_t::bicycle;
}

std::optional<transport_t> v1::is_bus(const segment_t& segment) const
{
    using namespace boost::adaptors;

    if (segment.integrated.speed > d_bus_params.max_speed)
    {
        PLOG_DEBUG
            << segment.id << ": is_bus - no: "
            << "found speed: " << segment.integrated.speed << ", "
            << "max speed: " << d_bus_params.max_speed;
        return {};
    }

    // Check for a bus stop near the first DP
    {
        if (d_osm->near_bus_stop({ segment.begin->coord }, d_bus_params.stop.vicinity, 1) == 0)
        {
            PLOG_DEBUG
                << segment.id << ": is_bus - no: "
                << "no stops at start";
            return {};
        }
    }

    // Check for bus stops near slow DPs
    {
        const auto slow_dps{ segment.range
            | filtered([&speed = d_bus_params.stop.max_speed](const sensor_data_point_t& dp) { return dp.speed <= speed; })
            | transformed([](const auto& dp) { return dp.coord; }) };

        // TODO - can we try not to copy these?
        std::vector<coordinate_t> slow_coords;
        slow_coords.reserve(segment.nof_dps / 10); // heuristics
        boost::copy(slow_dps, std::back_inserter(slow_coords));

        const auto min_near{ percent(slow_coords.size(), d_bus_params.stop.percent) };
        PLOG_DEBUG << segment.id << ": is_bus - stop osm query start";
        const auto nof_near{ d_osm->near_bus_stop(slow_coords, d_bus_params.stop.vicinity, min_near) };
        PLOG_DEBUG << segment.id << ": is_bus - stop osm query end";
        if (nof_near < min_near)
        {
            PLOG_DEBUG
                << segment.id << ": is_bus - no: "
                << "stops found: " << nof_near << ", required: " << min_near;
            return {};
        }
    }

    // Check for bus routes near all DPs
    {
        // TODO - can we try not to copy these?
        std::vector<coordinate_t> coords;
        coords.reserve(segment.nof_dps);
        boost::copy(segment.range | transformed([](const auto& dp) { return dp.coord; }), std::back_inserter(coords));
        PLOG_DEBUG << segment.id << ": is_bus - route osm query start";
        const double pct_found{ 100. * d_osm->near_bus_route(coords, segment.interpolated.points, d_bus_params.route.vicinity, d_bus_params.route.percent) };
        PLOG_DEBUG << segment.id << ": is_bus - route osm query end";
        if (pct_found < d_bus_params.route.percent)
        {
            PLOG_DEBUG
                << segment.id << ": is_bus - no: "
                << "routes found: " << pct_found << "%, "
                << "required: " << d_bus_params.route.percent << "%";
            return {};
        }
    }

    PLOG_DEBUG << segment.id << ": is_bus - yes";
    return +transport_t::bus;
}

std::optional<transport_t> v1::is_car(const segment_t& segment) const
{
    PLOG_DEBUG << segment.id << ": is_car - yes";
    return +transport_t::car;
}

transport_t v1::analyze(const segment_t& segment) const
{
    if (const auto mode{ is_airplane(segment) })
    {
        return *mode;
    }
    if (const auto mode{ is_bicycle(segment) })
    {
        return *mode;
    }
    if (const auto mode{ d_rail.detect(segment, d_osm) })
    {
        return *mode;
    }
    if (const auto mode{ is_bus(segment) })
    {
        return *mode;
    }
    if (const auto mode{ is_car(segment) })
    {
        return *mode;
    }
    return +transport_t::unknown;
}

static std::string create_gpx_trace(const segment_t& segment)
{
    std::stringstream gpx_trace;
    gpx_trace
        << R"(<?xml version="1.0" encoding="UTF-8"?>)"
        << R"(<gpx xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance")"
        << R"( xmlns="http://www.topografix.com/GPX/1/1")"
        << R"( xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd")"
        << R"( version="1.1")"
        << R"( creator="kooling-core-av">)";

    std::stringstream trk, wpt;
    trk << "<trk><trkseg>";

    int zero_speed_points{ 0 };
    for (auto it{ segment.begin }; it != segment.end; ++it)
    {
        const auto& dp{ *it };
        const auto& coord{ dp.coord };

        trk << boost::format(R"(<trkpt lat="%1%" lon="%2%"></trkpt>)")
               % coord.lat()
               % coord.lon();

        if (dp.speed.ms() == 0)
        {
            ++zero_speed_points;
        }
        else if (zero_speed_points != 0)
        {
            const auto& start{ std::prev(it, zero_speed_points) };
            wpt << boost::format(R"(<wpt lat="%1%" lon="%2%"><name>%3%</name></wpt>)")
                   % start->coord.lat()
                   % start->coord.lon()
                   % zero_speed_points;
            zero_speed_points = 0;
        }
    }

    trk << "</trkseg></trk>";

    gpx_trace << wpt.str() << trk.str() << "</gpx>";
    auto str{ gpx_trace.str() };

    PLOG_VERBOSE << segment.id << ": gpx trace - " << str;

    return str;
}

static json_t create_geojson(const user_t& user, const segment_t& segment, const transport_t& transport)
{
    using namespace boost::adaptors;

    std::vector<std::array<double, 2>> coords;
    coords.reserve(segment.nof_dps);

    std::vector<json_t> features;
    features.reserve(segment.nof_dps + 1 /* for the LineString */);

    const auto max_speed{ *boost::max_element(
        segment.range
        | transformed([](const sensor_data_point_t& dp) { return dp.speed.kmh(); })) };
    const auto trans{ transport._to_string() };

    // add these last so they aren't overlaid by other DPs with the same coords
    ordered_json_t first_dp, last_dp;

    int num{};
    for (const auto& dp : segment.range)
    {
        ++num;

        json_t coord = { dp.coord.lon(), dp.coord.lat() };
        coords.push_back(coord);

        const auto motion{ dp.motion_type };
        const std::string color{
            num == 1               ? "#800000" :
            num == segment.nof_dps ? "#006600" :
            is_none(motion)        ? "#ffffff" :
            is_walking(motion)     ? "#33ccff" :
            is_running(motion)     ? "#003399" :
            is_cycling(motion)     ? "#66ffff" :
            is_automotive(motion)  ? "#ff0000" :
            is_unknown(motion)     ? "#9c9c9c" :
                                     "#ffff00"
        };

        const std::string dp_number{ boost::str(boost::format("%1% / %2%") % num % segment.nof_dps) };

        if (num == 1)
        {
            ordered_json_t feature = {
                { "type", "Feature" },
                { "geometry", { { "type", "Point" }, { "coordinates", coord } } },
                { "properties",  { { "user", user.user_id },
                                   { "transport", trans },
                                   { "max speed (km/h)", max_speed },
                                   { "∫ speed (km/h)", segment.integrated.speed.kmh() },
                                   { "∫ distance (km)", segment.integrated.distance.km() },
                                   { "∫ duration (H:M:S)", std::string{ segment.integrated.duration } },
                                   { "DP number", dp_number },
                                   { "DP time", std::string{ dp.timestamp } },
                                   { "DP speed (km/h)", dp.speed.kmh() },
                                   { "DP motion type", motion._to_string() },
                                   { "marker-color", color } } } };
            first_dp = std::move(feature);
        }
        else
        {
            ordered_json_t feature = {
                { "type", "Feature" },
                { "geometry", { { "type", "Point" }, { "coordinates", coord } } },
                { "properties",  { { "DP number", dp_number },
                                   { "DP time", std::string{ dp.timestamp } },
                                   { "DP speed (km/h)", dp.speed.kmh() },
                                   { "DP motion type", motion._to_string() },
                                   { "marker-color", color } } } };
            if (num == segment.nof_dps)
            {
                last_dp = std::move(feature);
            }
            else
            {
                features.push_back(std::move(feature));
            }
        }
    }

    features.push_back(json_t{
        { "type", "Feature" },
        { "geometry", { { "type", "LineString" }, { "coordinates",  coords } } },
        { "properties", {} }
        });

    features.push_back(last_dp);
    features.push_back(first_dp);

    json_t geojson = { { "type", "FeatureCollection" }, { "features", features } };

    return geojson;
}

static double compute_eco_driving_score(transport_t transport, const segment_t& segment)
{
    if (transport != +transport_t::car && transport != +transport_t::heavydutyvehicle)
    {
        return 7;
    }

    double score{ 0. };

    for (const auto& dp : segment.range)
    {
        // TODO
        (void)dp;
    }

    return score;
}

static int sum_steps(const segment_t& segment)
{
    return boost::accumulate(
        segment.range,
        0,
        [](const int acc, const sensor_data_point_t& dp)
        {
            return acc + dp.steps;
        });
}

trip_t v1::create_trip(const user_t& user, const fingerprint_t&, segment_t segment) const
{
    const auto transport{ analyze(segment) };

    return trip_t{
        .itin_id   = create_itin_id(),
        .transport = transport,
        .gpx_trace = create_gpx_trace(segment),
        .geojson   = create_geojson(user, segment, transport),
        .eco_score = compute_eco_driving_score(transport, segment),
        .steps     = sum_steps(segment),
        .segment   = std::move(segment) };
}

} // namespace kooling::component::classifier