summaryrefslogtreecommitdiff
path: root/lib/Travel/Status/DE/IRIS/Stations.pm.PL
blob: b91d84af83fdf91738bb129b24bb12b1076379f8 (plain)
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
#!/usr/bin/env perl

use strict;
use warnings;
use 5.010;
use utf8;
use File::Slurp qw(read_file write_file);
use JSON;

my $json_str = read_file('share/stations.json');
my $stations = JSON->new->utf8->decode($json_str);

my $meta_str = read_file('share/meta.json');
my $meta     = JSON->new->utf8->decode($meta_str);

my $buf = <<'EOF';
package Travel::Status::DE::IRIS::Stations;

# vim:readonly
# This module has been automatically generated from share/stations.json
# by lib/Travel/Status/DE/IRIS/Stations.pm.PL.
# Do not edit, changes will be lost.

use strict;
use warnings;
use 5.014;
use utf8;

EOF

if ($ENV{DB_IRIS_DEB_BUILD}) {
	$buf .= "use Geo::Distance;\n"
}
else {
	$buf .= "use GIS::Distance;\n";
}

$buf .= <<'EOF';
use List::Util qw(min);
use List::UtilsBy qw(uniq_by);
use List::MoreUtils qw(firstval pairwise);
use Text::LevenshteinXS qw(distance);

# TODO switch to Text::Levenshtein::XS once AUR/Debian packages become available

our $VERSION = '1.77';

# Automatically generated, see share/stations.json
my @stations = (
EOF

for my $station ( @{$stations} ) {
	if ( $station->{latlong} ) {
		$buf .= sprintf(
			"['%s','%s',%s,%s,%s],\n",
			$station->{ds100}, $station->{name},
			$station->{eva},   $station->{latlong}[1],
			$station->{latlong}[0],
		);
	}
	else {
		$buf .= sprintf( "['%s','%s',%s],\n",
			$station->{ds100}, $station->{name}, $station->{eva} );
	}
}

$buf .= <<'EOF';
);

# Automatically generated, see share/meta.json
my $meta = {
EOF

for my $eva (keys %{$meta}) {
	$buf .= sprintf("%s => [%s],\n",
		$eva,
		join(q{,}, @{$meta->{$eva}})
	);
}

$buf .= <<'EOF';
};

sub get_stations {
	return @stations;
}

sub get_meta {
	return $meta;
}

sub normalize {
	my ($val) = @_;

	$val =~ s{Ä}{Ae}g;
	$val =~ s{Ö}{Oe}g;
	$val =~ s{Ü}{Ue}g;
	$val =~ s{ä}{ae}g;
	$val =~ s{ö}{oe}g;
	$val =~ s{ß}{sz}g;
	$val =~ s{ü}{ue}g;

	return $val;
}

sub get_station {
	my ($name) = @_;

	if (not $name) {
		return;
	}

	my $ds100_match = firstval { $name eq $_->[0] } @stations;

	if ($ds100_match) {
		return ($ds100_match);
	}

	my $eva_match = firstval { defined $_->[2] and $name eq $_->[2] } @stations;

	if ($eva_match) {
		return ($eva_match);
	}

	return get_station_by_name($name);
}

sub get_station_by_location {
	my ( $lon, $lat, $num_matches ) = @_;

	$num_matches //= 10;

EOF

if ($ENV{DB_IRIS_DEB_BUILD}) {
	$buf .= "\tmy \$dist = Geo::Distance->new();\n";
}
else {
	$buf .= "\tmy \$dist = GIS::Distance->new();\n";
}

$buf .= <<'EOF';

	# we only use geolocations inside germany.
	# For these, this fast preprocessing step will let through all
	# coordinates inside a 60km radius (and a bunch which are farther out)
	my @candidates = grep {
		      $#{$_} >= 4
		  and abs( $_->[3] - $lon ) < 1
		  and abs( $_->[4] - $lat )
		  < 1
	} @stations;
	my @distances
EOF

if ($ENV{DB_IRIS_DEB_BUILD}) {
	$buf .= '= map { $dist->distance( \'kilometer\', $lon, $lat, $_->[3], $_->[4] ) }';
}
else {
	$buf .= '= map { $dist->distance_metal( $lat, $lon, $_->[4], $_->[3] ) }';
}

$buf .= <<'EOF';
	  @candidates;
	my @station_map = pairwise { [ $a, $b ] } @candidates, @distances;

	@station_map = sort { $a->[1] <=> $b->[1] } @station_map;
	splice( @station_map, $num_matches );

	return @station_map;
}

sub get_station_by_name {
	my ($name) = @_;

	if (not $name) {
		return;
	}

	my $nname        = lc($name);
	my $actual_match = firstval { $nname eq lc( $_->[1] ) } @stations;

	if ($actual_match) {
		return ($actual_match);
	}

	$nname        = normalize($nname);
	$actual_match = firstval { $nname eq normalize( lc( $_->[1] ) ) } @stations;
	if ($actual_match) {
		return ($actual_match);
	}

	my @distances   = map { distance( $nname, $_->[1] ) } @stations;
	my $min_dist    = min(@distances);
	my @station_map = pairwise { [ $a, $b ] } @stations, @distances;

	my @substring_matches;

	# $name may be an invalid regular expression
	eval { push(@substring_matches, grep { $_->[1] =~ m{\Q$name\E}i } @stations) };
	eval { push(@substring_matches, grep { $_->[1] =~ m{$name}i } @stations) };

	my @levenshtein_matches
	  = map { $_->[0] } grep { $_->[1] == $min_dist } @station_map;

	return uniq_by { $_->[0] } ( @substring_matches, @levenshtein_matches );
}

1;

__END__

=head1 NAME

Travel::Status::DE::IRIS::Stations - Station name to station code mapping

=head1 SYNOPSIS

    use Travel::Status::DE::IRIS::Stations;

    my $name = 'Essen Hbf';
    my @stations = Travel::Status::DE::IRIS::Stations::get_station_by_name(
      $name);

    if (@stations < 1) {
      # no matching stations
    }
    elsif (@stations > 1) {
      # too many matches
    }
    else {
      printf("Input '%s' matched station code %s (as '%s')\n",
        $name, @{$stations[0]});
    }

=head1 VERSION

version 1.77

=head1 DESCRIPTION

This module contains a list of Deutsche Bahn stations, and also some stations
outside of Germany which are served by Deutsche Bahn trains. It offers
several accessors to look up stations based on names or geolocation data and
can also simply dump all known stations.

Each of the following methods returns a list of array references. Each
array reference describes a single station and contains either two or
five elements:

=over

=item * Station code (also known as DS100 / "Druckschrift 100" /
"Richtlinie 100"). A short string used exclusively by Deutsche Bahn APIs. Note
that it may contain space characters.

=item * Station name

=item * EVA station number (often, but not always, same as UIC station number)

=item * Station longitude, if available

=item * Station latitude, if available

=back

Note that station names are not unique.
A single station may be present multiple times with different EVA numbers and DS100 codes.
At the moment, EVA numbers and DS100 codes are unique.

=head1 METHODS

=over

=item Travel::Status::DE::IRIS::Stations::get_stations

Returns a list of all known stations, lexically sorted by station name.

=item Travel::Status::DE::IRIS::Stations::get_station(I<$in>)

Returns a list of stations matching I<$in>.

If a I<$in> is a valid station identifier (either DS100 code or EVA number),
a single array reference describing the station is returned. Otherwise,
I<$in> is passed to get_station_by_name(I<$in>) (see below).

Note that DS100 code matching is case sensitive.

=item Travel::Status::DE::IRIS::Stations::get_station_by_location(I<$lon>, I<$lat>, I<$num_matches>)

Looks for stations which are close to longitude/latitude I<$lon>/I<$lat> and
returns the closest I<$num_matches> (defaults to 10) matches. Note that
stations which are located more than 70 kilometers away from I<$lon>/I<$lat>
may be ignored when computing the closest matches.

=item Travel::Status::DE::IRIS::Stations::get_station_by_name(I<$name>)

Returns a list of stations where the station name matches I<$name>.

Matching happens in two steps: If a case-insensitive exact match exists, only
this one is returned. For station names that correspond to several EVA/DS100
codes, the match with the lowest EVA number is returned.

Otherwise, all stations whose name contains I<$name> as a substring (also
case-insensitive) and all stations whose name has a low Levenshtein distance to
I<$name> are returned.

This two-step behaviour makes sure that not-prefix-free stations can still be
matched directly. For instance, both "Essen-Steele" and "Essen-Steele Ost"
are valid station names, but "essen-steele" will only return "Essen-Steele".

=back

=head1 DIAGNOSTICS

None.

=head1 DEPENDENCIES

=over

=item * GIS::Distance(3pm)

=item * List::MoreUtils(3pm)

=item * List::Util(3pm)

=item * Text::LevenshteinXS(3pm)

=back

=head1 BUGS AND LIMITATIONS

There is no support for intelligent whitespaces (to also match "-" and similar)
yet.

=head1 SEE ALSO

Travel::Status::DE::IRIS(3pm).

=head1 AUTHOR

Station data: Copyright (C) 2016 by DB Station&Service AG, Europaplatz 1, 10557 Berlin, Germany

Lookup code: Copyright (C) 2014-2022 by Daniel Friesel E<lt>derf@finalrewind.orgE<gt>

=head1 LICENSE

This module is licensed under the same terms as Perl itself. Note that the
station data used by this module is also available under a CC-BY 4.0 license on
L<http://data.deutschebahn.com/dataset/data-haltestellen>.
EOF

write_file( $ARGV[0], { binmode => ':utf8' }, $buf );