repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
ruipgil/TrackToTrip | tracktotrip/segment.py | Segment.slice | def slice(self, start, end):
""" Creates a copy of the current segment between indexes. If end > start,
points are reverted
Args:
start (int): Start index
end (int): End index
Returns:
:obj:`Segment`
"""
reverse = False
if... | python | def slice(self, start, end):
""" Creates a copy of the current segment between indexes. If end > start,
points are reverted
Args:
start (int): Start index
end (int): End index
Returns:
:obj:`Segment`
"""
reverse = False
if... | [
"def",
"slice",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"reverse",
"=",
"False",
"if",
"start",
">",
"end",
":",
"temp",
"=",
"start",
"start",
"=",
"end",
"end",
"=",
"temp",
"reverse",
"=",
"True",
"seg",
"=",
"self",
".",
"copy",
"(",... | Creates a copy of the current segment between indexes. If end > start,
points are reverted
Args:
start (int): Start index
end (int): End index
Returns:
:obj:`Segment` | [
"Creates",
"a",
"copy",
"of",
"the",
"current",
"segment",
"between",
"indexes",
".",
"If",
"end",
">",
"start",
"points",
"are",
"reverted"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L257-L280 |
ruipgil/TrackToTrip | tracktotrip/segment.py | Segment.to_json | def to_json(self):
""" Converts segment to a JSON serializable format
Returns:
:obj:`dict`
"""
points = [point.to_json() for point in self.points]
return {
'points': points,
'transportationModes': self.transportation_modes,
'locati... | python | def to_json(self):
""" Converts segment to a JSON serializable format
Returns:
:obj:`dict`
"""
points = [point.to_json() for point in self.points]
return {
'points': points,
'transportationModes': self.transportation_modes,
'locati... | [
"def",
"to_json",
"(",
"self",
")",
":",
"points",
"=",
"[",
"point",
".",
"to_json",
"(",
")",
"for",
"point",
"in",
"self",
".",
"points",
"]",
"return",
"{",
"'points'",
":",
"points",
",",
"'transportationModes'",
":",
"self",
".",
"transportation_mo... | Converts segment to a JSON serializable format
Returns:
:obj:`dict` | [
"Converts",
"segment",
"to",
"a",
"JSON",
"serializable",
"format"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L290-L302 |
ruipgil/TrackToTrip | tracktotrip/segment.py | Segment.from_gpx | def from_gpx(gpx_segment):
""" Creates a segment from a GPX format.
No preprocessing is done.
Arguments:
gpx_segment (:obj:`gpxpy.GPXTrackSegment`)
Return:
:obj:`Segment`
"""
points = []
for point in gpx_segment.points:
points... | python | def from_gpx(gpx_segment):
""" Creates a segment from a GPX format.
No preprocessing is done.
Arguments:
gpx_segment (:obj:`gpxpy.GPXTrackSegment`)
Return:
:obj:`Segment`
"""
points = []
for point in gpx_segment.points:
points... | [
"def",
"from_gpx",
"(",
"gpx_segment",
")",
":",
"points",
"=",
"[",
"]",
"for",
"point",
"in",
"gpx_segment",
".",
"points",
":",
"points",
".",
"append",
"(",
"Point",
".",
"from_gpx",
"(",
"point",
")",
")",
"return",
"Segment",
"(",
"points",
")"
] | Creates a segment from a GPX format.
No preprocessing is done.
Arguments:
gpx_segment (:obj:`gpxpy.GPXTrackSegment`)
Return:
:obj:`Segment` | [
"Creates",
"a",
"segment",
"from",
"a",
"GPX",
"format",
"."
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L305-L318 |
ruipgil/TrackToTrip | tracktotrip/segment.py | Segment.from_json | def from_json(json):
""" Creates a segment from a JSON file.
No preprocessing is done.
Arguments:
json (:obj:`dict`): JSON representation. See to_json.
Return:
:obj:`Segment`
"""
points = []
for point in json['points']:
points... | python | def from_json(json):
""" Creates a segment from a JSON file.
No preprocessing is done.
Arguments:
json (:obj:`dict`): JSON representation. See to_json.
Return:
:obj:`Segment`
"""
points = []
for point in json['points']:
points... | [
"def",
"from_json",
"(",
"json",
")",
":",
"points",
"=",
"[",
"]",
"for",
"point",
"in",
"json",
"[",
"'points'",
"]",
":",
"points",
".",
"append",
"(",
"Point",
".",
"from_json",
"(",
"point",
")",
")",
"return",
"Segment",
"(",
"points",
")"
] | Creates a segment from a JSON file.
No preprocessing is done.
Arguments:
json (:obj:`dict`): JSON representation. See to_json.
Return:
:obj:`Segment` | [
"Creates",
"a",
"segment",
"from",
"a",
"JSON",
"file",
"."
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L321-L334 |
ruipgil/TrackToTrip | tracktotrip/smooth.py | extrapolate_points | def extrapolate_points(points, n_points):
""" Extrapolate a number of points, based on the first ones
Args:
points (:obj:`list` of :obj:`Point`)
n_points (int): number of points to extrapolate
Returns:
:obj:`list` of :obj:`Point`
"""
points = points[:n_points]
lat = []
... | python | def extrapolate_points(points, n_points):
""" Extrapolate a number of points, based on the first ones
Args:
points (:obj:`list` of :obj:`Point`)
n_points (int): number of points to extrapolate
Returns:
:obj:`list` of :obj:`Point`
"""
points = points[:n_points]
lat = []
... | [
"def",
"extrapolate_points",
"(",
"points",
",",
"n_points",
")",
":",
"points",
"=",
"points",
"[",
":",
"n_points",
"]",
"lat",
"=",
"[",
"]",
"lon",
"=",
"[",
"]",
"last",
"=",
"None",
"for",
"point",
"in",
"points",
":",
"if",
"last",
"is",
"no... | Extrapolate a number of points, based on the first ones
Args:
points (:obj:`list` of :obj:`Point`)
n_points (int): number of points to extrapolate
Returns:
:obj:`list` of :obj:`Point` | [
"Extrapolate",
"a",
"number",
"of",
"points",
"based",
"on",
"the",
"first",
"ones"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/smooth.py#L13-L45 |
ruipgil/TrackToTrip | tracktotrip/smooth.py | with_extrapolation | def with_extrapolation(points, noise, n_points):
""" Smooths a set of points, but it extrapolates some points at the beginning
Args:
points (:obj:`list` of :obj:`Point`)
noise (float): Expected noise, the higher it is the more the path will
be smoothed.
Returns:
:obj:`li... | python | def with_extrapolation(points, noise, n_points):
""" Smooths a set of points, but it extrapolates some points at the beginning
Args:
points (:obj:`list` of :obj:`Point`)
noise (float): Expected noise, the higher it is the more the path will
be smoothed.
Returns:
:obj:`li... | [
"def",
"with_extrapolation",
"(",
"points",
",",
"noise",
",",
"n_points",
")",
":",
"n_points",
"=",
"10",
"return",
"kalman_filter",
"(",
"extrapolate_points",
"(",
"points",
",",
"n_points",
")",
"+",
"points",
",",
"noise",
")",
"[",
"n_points",
":",
"... | Smooths a set of points, but it extrapolates some points at the beginning
Args:
points (:obj:`list` of :obj:`Point`)
noise (float): Expected noise, the higher it is the more the path will
be smoothed.
Returns:
:obj:`list` of :obj:`Point` | [
"Smooths",
"a",
"set",
"of",
"points",
"but",
"it",
"extrapolates",
"some",
"points",
"at",
"the",
"beginning"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/smooth.py#L47-L58 |
ruipgil/TrackToTrip | tracktotrip/smooth.py | with_inverse | def with_inverse(points, noise):
""" Smooths a set of points
It smooths them twice, once in given order, another one in the reverse order.
The the first half of the results will be taken from the reverse order and
the second half from the normal order.
Args:
points (:obj:`list` of :obj... | python | def with_inverse(points, noise):
""" Smooths a set of points
It smooths them twice, once in given order, another one in the reverse order.
The the first half of the results will be taken from the reverse order and
the second half from the normal order.
Args:
points (:obj:`list` of :obj... | [
"def",
"with_inverse",
"(",
"points",
",",
"noise",
")",
":",
"# noise_sample = 20",
"n_points",
"=",
"len",
"(",
"points",
")",
"/",
"2",
"break_point",
"=",
"n_points",
"points_part",
"=",
"copy",
".",
"deepcopy",
"(",
"points",
")",
"points_part",
"=",
... | Smooths a set of points
It smooths them twice, once in given order, another one in the reverse order.
The the first half of the results will be taken from the reverse order and
the second half from the normal order.
Args:
points (:obj:`list` of :obj:`Point`)
noise (float): Expected... | [
"Smooths",
"a",
"set",
"of",
"points"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/smooth.py#L76-L102 |
ruipgil/TrackToTrip | tracktotrip/spatiotemporal_segmentation.py | temporal_segmentation | def temporal_segmentation(segments, min_time):
""" Segments based on time distant points
Args:
segments (:obj:`list` of :obj:`list` of :obj:`Point`): segment points
min_time (int): minimum required time for segmentation
"""
final_segments = []
for segment in segments:
final_... | python | def temporal_segmentation(segments, min_time):
""" Segments based on time distant points
Args:
segments (:obj:`list` of :obj:`list` of :obj:`Point`): segment points
min_time (int): minimum required time for segmentation
"""
final_segments = []
for segment in segments:
final_... | [
"def",
"temporal_segmentation",
"(",
"segments",
",",
"min_time",
")",
":",
"final_segments",
"=",
"[",
"]",
"for",
"segment",
"in",
"segments",
":",
"final_segments",
".",
"append",
"(",
"[",
"]",
")",
"for",
"point",
"in",
"segment",
":",
"if",
"point",
... | Segments based on time distant points
Args:
segments (:obj:`list` of :obj:`list` of :obj:`Point`): segment points
min_time (int): minimum required time for segmentation | [
"Segments",
"based",
"on",
"time",
"distant",
"points"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/spatiotemporal_segmentation.py#L8-L23 |
ruipgil/TrackToTrip | tracktotrip/spatiotemporal_segmentation.py | correct_segmentation | def correct_segmentation(segments, clusters, min_time):
""" Corrects the predicted segmentation
This process prevents over segmentation
Args:
segments (:obj:`list` of :obj:`list` of :obj:`Point`):
segments to correct
min_time (int): minimum required time for segmentation
""... | python | def correct_segmentation(segments, clusters, min_time):
""" Corrects the predicted segmentation
This process prevents over segmentation
Args:
segments (:obj:`list` of :obj:`list` of :obj:`Point`):
segments to correct
min_time (int): minimum required time for segmentation
""... | [
"def",
"correct_segmentation",
"(",
"segments",
",",
"clusters",
",",
"min_time",
")",
":",
"# segments = [points for points in segments if len(points) > 1]",
"result_segments",
"=",
"[",
"]",
"prev_segment",
"=",
"None",
"for",
"i",
",",
"segment",
"in",
"enumerate",
... | Corrects the predicted segmentation
This process prevents over segmentation
Args:
segments (:obj:`list` of :obj:`list` of :obj:`Point`):
segments to correct
min_time (int): minimum required time for segmentation | [
"Corrects",
"the",
"predicted",
"segmentation"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/spatiotemporal_segmentation.py#L25-L59 |
ruipgil/TrackToTrip | tracktotrip/spatiotemporal_segmentation.py | spatiotemporal_segmentation | def spatiotemporal_segmentation(points, eps, min_time):
""" Splits a set of points into multiple sets of points based on
spatio-temporal stays
DBSCAN is used to predict possible segmentations,
furthermore we check to see if each clusters is big enough in
time (>=min_time). If that's the... | python | def spatiotemporal_segmentation(points, eps, min_time):
""" Splits a set of points into multiple sets of points based on
spatio-temporal stays
DBSCAN is used to predict possible segmentations,
furthermore we check to see if each clusters is big enough in
time (>=min_time). If that's the... | [
"def",
"spatiotemporal_segmentation",
"(",
"points",
",",
"eps",
",",
"min_time",
")",
":",
"# min time / sample rate",
"dt_average",
"=",
"np",
".",
"median",
"(",
"[",
"point",
".",
"dt",
"for",
"point",
"in",
"points",
"]",
")",
"min_samples",
"=",
"min_t... | Splits a set of points into multiple sets of points based on
spatio-temporal stays
DBSCAN is used to predict possible segmentations,
furthermore we check to see if each clusters is big enough in
time (>=min_time). If that's the case than the segmentation is
considered valid.
Wh... | [
"Splits",
"a",
"set",
"of",
"points",
"into",
"multiple",
"sets",
"of",
"points",
"based",
"on",
"spatio",
"-",
"temporal",
"stays"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/spatiotemporal_segmentation.py#L61-L124 |
ruipgil/TrackToTrip | tracktotrip/kalman.py | kalman_filter | def kalman_filter(points, noise):
""" Smooths points with kalman filter
See https://github.com/open-city/ikalman
Args:
points (:obj:`list` of :obj:`Point`): points to smooth
noise (float): expected noise
"""
kalman = ikalman.filter(noise)
for point in points:
kalman.upd... | python | def kalman_filter(points, noise):
""" Smooths points with kalman filter
See https://github.com/open-city/ikalman
Args:
points (:obj:`list` of :obj:`Point`): points to smooth
noise (float): expected noise
"""
kalman = ikalman.filter(noise)
for point in points:
kalman.upd... | [
"def",
"kalman_filter",
"(",
"points",
",",
"noise",
")",
":",
"kalman",
"=",
"ikalman",
".",
"filter",
"(",
"noise",
")",
"for",
"point",
"in",
"points",
":",
"kalman",
".",
"update_velocity2d",
"(",
"point",
".",
"lat",
",",
"point",
".",
"lon",
",",... | Smooths points with kalman filter
See https://github.com/open-city/ikalman
Args:
points (:obj:`list` of :obj:`Point`): points to smooth
noise (float): expected noise | [
"Smooths",
"points",
"with",
"kalman",
"filter"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/kalman.py#L7-L22 |
ruipgil/TrackToTrip | tracktotrip/transportation_mode.py | learn_transportation_mode | def learn_transportation_mode(track, clf):
""" Inserts transportation modes of a track into a classifier
Args:
track (:obj:`Track`)
clf (:obj:`Classifier`)
"""
for segment in track.segments:
tmodes = segment.transportation_modes
points = segment.points
features =... | python | def learn_transportation_mode(track, clf):
""" Inserts transportation modes of a track into a classifier
Args:
track (:obj:`Track`)
clf (:obj:`Classifier`)
"""
for segment in track.segments:
tmodes = segment.transportation_modes
points = segment.points
features =... | [
"def",
"learn_transportation_mode",
"(",
"track",
",",
"clf",
")",
":",
"for",
"segment",
"in",
"track",
".",
"segments",
":",
"tmodes",
"=",
"segment",
".",
"transportation_modes",
"points",
"=",
"segment",
".",
"points",
"features",
"=",
"[",
"]",
"labels"... | Inserts transportation modes of a track into a classifier
Args:
track (:obj:`Track`)
clf (:obj:`Classifier`) | [
"Inserts",
"transportation",
"modes",
"of",
"a",
"track",
"into",
"a",
"classifier"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/transportation_mode.py#L57-L76 |
ruipgil/TrackToTrip | tracktotrip/transportation_mode.py | extract_features | def extract_features(points, n_tops):
""" Feature extractor
Args:
points (:obj:`list` of :obj:`Point`)
n_tops (int): Number of top speeds to extract
Returns:
:obj:`list` of float: with length (n_tops*2). Where the ith even element
is the ith top speed and the i+1 element... | python | def extract_features(points, n_tops):
""" Feature extractor
Args:
points (:obj:`list` of :obj:`Point`)
n_tops (int): Number of top speeds to extract
Returns:
:obj:`list` of float: with length (n_tops*2). Where the ith even element
is the ith top speed and the i+1 element... | [
"def",
"extract_features",
"(",
"points",
",",
"n_tops",
")",
":",
"max_bin",
"=",
"-",
"1",
"for",
"point",
"in",
"points",
":",
"max_bin",
"=",
"max",
"(",
"max_bin",
",",
"point",
".",
"vel",
")",
"max_bin",
"=",
"int",
"(",
"round",
"(",
"max_bin... | Feature extractor
Args:
points (:obj:`list` of :obj:`Point`)
n_tops (int): Number of top speeds to extract
Returns:
:obj:`list` of float: with length (n_tops*2). Where the ith even element
is the ith top speed and the i+1 element is the percentage of time
spent o... | [
"Feature",
"extractor"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/transportation_mode.py#L78-L114 |
ruipgil/TrackToTrip | tracktotrip/transportation_mode.py | speed_difference | def speed_difference(points):
""" Computes the speed difference between each adjacent point
Args:
points (:obj:`Point`)
Returns:
:obj:`list` of int: Indexes of changepoints
"""
data = [0]
for before, after in pairwise(points):
data.append(before.vel - after.vel)
retu... | python | def speed_difference(points):
""" Computes the speed difference between each adjacent point
Args:
points (:obj:`Point`)
Returns:
:obj:`list` of int: Indexes of changepoints
"""
data = [0]
for before, after in pairwise(points):
data.append(before.vel - after.vel)
retu... | [
"def",
"speed_difference",
"(",
"points",
")",
":",
"data",
"=",
"[",
"0",
"]",
"for",
"before",
",",
"after",
"in",
"pairwise",
"(",
"points",
")",
":",
"data",
".",
"append",
"(",
"before",
".",
"vel",
"-",
"after",
".",
"vel",
")",
"return",
"da... | Computes the speed difference between each adjacent point
Args:
points (:obj:`Point`)
Returns:
:obj:`list` of int: Indexes of changepoints | [
"Computes",
"the",
"speed",
"difference",
"between",
"each",
"adjacent",
"point"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/transportation_mode.py#L116-L127 |
ruipgil/TrackToTrip | tracktotrip/transportation_mode.py | acc_difference | def acc_difference(points):
""" Computes the accelaration difference between each adjacent point
Args:
points (:obj:`Point`)
Returns:
:obj:`list` of int: Indexes of changepoints
"""
data = [0]
for before, after in pairwise(points):
data.append(before.acc - after.acc)
... | python | def acc_difference(points):
""" Computes the accelaration difference between each adjacent point
Args:
points (:obj:`Point`)
Returns:
:obj:`list` of int: Indexes of changepoints
"""
data = [0]
for before, after in pairwise(points):
data.append(before.acc - after.acc)
... | [
"def",
"acc_difference",
"(",
"points",
")",
":",
"data",
"=",
"[",
"0",
"]",
"for",
"before",
",",
"after",
"in",
"pairwise",
"(",
"points",
")",
":",
"data",
".",
"append",
"(",
"before",
".",
"acc",
"-",
"after",
".",
"acc",
")",
"return",
"data... | Computes the accelaration difference between each adjacent point
Args:
points (:obj:`Point`)
Returns:
:obj:`list` of int: Indexes of changepoints | [
"Computes",
"the",
"accelaration",
"difference",
"between",
"each",
"adjacent",
"point"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/transportation_mode.py#L129-L140 |
ruipgil/TrackToTrip | tracktotrip/transportation_mode.py | detect_changepoints | def detect_changepoints(points, min_time, data_processor=acc_difference):
""" Detects changepoints on points that have at least a specific duration
Args:
points (:obj:`Point`)
min_time (float): Min time that a sub-segmented, bounded by two changepoints, must have
data_processor (functio... | python | def detect_changepoints(points, min_time, data_processor=acc_difference):
""" Detects changepoints on points that have at least a specific duration
Args:
points (:obj:`Point`)
min_time (float): Min time that a sub-segmented, bounded by two changepoints, must have
data_processor (functio... | [
"def",
"detect_changepoints",
"(",
"points",
",",
"min_time",
",",
"data_processor",
"=",
"acc_difference",
")",
":",
"data",
"=",
"data_processor",
"(",
"points",
")",
"changepoints",
"=",
"pelt",
"(",
"normal_mean",
"(",
"data",
",",
"np",
".",
"std",
"(",... | Detects changepoints on points that have at least a specific duration
Args:
points (:obj:`Point`)
min_time (float): Min time that a sub-segmented, bounded by two changepoints, must have
data_processor (function): Function to extract data to feed to the changepoint algorithm.
Def... | [
"Detects",
"changepoints",
"on",
"points",
"that",
"have",
"at",
"least",
"a",
"specific",
"duration"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/transportation_mode.py#L142-L167 |
ruipgil/TrackToTrip | tracktotrip/transportation_mode.py | group_modes | def group_modes(modes):
""" Groups consecutive transportation modes with same label, into one
Args:
modes (:obj:`list` of :obj:`dict`)
Returns:
:obj:`list` of :obj:`dict`
"""
if len(modes) > 0:
previous = modes[0]
grouped = []
for changep in modes[1:]:
... | python | def group_modes(modes):
""" Groups consecutive transportation modes with same label, into one
Args:
modes (:obj:`list` of :obj:`dict`)
Returns:
:obj:`list` of :obj:`dict`
"""
if len(modes) > 0:
previous = modes[0]
grouped = []
for changep in modes[1:]:
... | [
"def",
"group_modes",
"(",
"modes",
")",
":",
"if",
"len",
"(",
"modes",
")",
">",
"0",
":",
"previous",
"=",
"modes",
"[",
"0",
"]",
"grouped",
"=",
"[",
"]",
"for",
"changep",
"in",
"modes",
"[",
"1",
":",
"]",
":",
"if",
"changep",
"[",
"'la... | Groups consecutive transportation modes with same label, into one
Args:
modes (:obj:`list` of :obj:`dict`)
Returns:
:obj:`list` of :obj:`dict` | [
"Groups",
"consecutive",
"transportation",
"modes",
"with",
"same",
"label",
"into",
"one"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/transportation_mode.py#L169-L191 |
ruipgil/TrackToTrip | tracktotrip/transportation_mode.py | speed_clustering | def speed_clustering(clf, points, min_time):
""" Transportation mode infering, based on changepoint segmentation
Args:
clf (:obj:`Classifier`): Classifier to use
points (:obj:`list` of :obj:`Point`)
min_time (float): Min time, in seconds, before do another segmentation
Returns:
... | python | def speed_clustering(clf, points, min_time):
""" Transportation mode infering, based on changepoint segmentation
Args:
clf (:obj:`Classifier`): Classifier to use
points (:obj:`list` of :obj:`Point`)
min_time (float): Min time, in seconds, before do another segmentation
Returns:
... | [
"def",
"speed_clustering",
"(",
"clf",
",",
"points",
",",
"min_time",
")",
":",
"# get changepoint indexes",
"changepoints",
"=",
"detect_changepoints",
"(",
"points",
",",
"min_time",
")",
"# info for each changepoint",
"cp_info",
"=",
"[",
"]",
"for",
"i",
"in"... | Transportation mode infering, based on changepoint segmentation
Args:
clf (:obj:`Classifier`): Classifier to use
points (:obj:`list` of :obj:`Point`)
min_time (float): Min time, in seconds, before do another segmentation
Returns:
:obj:`list` of :obj:`dict` | [
"Transportation",
"mode",
"infering",
"based",
"on",
"changepoint",
"segmentation"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/transportation_mode.py#L208-L231 |
ruipgil/TrackToTrip | tracktotrip/compression.py | distance | def distance(p_a, p_b):
""" Euclidean distance, between two points
Args:
p_a (:obj:`Point`)
p_b (:obj:`Point`)
Returns:
float: distance, in degrees
"""
return sqrt((p_a.lat - p_b.lat) ** 2 + (p_a.lon - p_b.lon) ** 2) | python | def distance(p_a, p_b):
""" Euclidean distance, between two points
Args:
p_a (:obj:`Point`)
p_b (:obj:`Point`)
Returns:
float: distance, in degrees
"""
return sqrt((p_a.lat - p_b.lat) ** 2 + (p_a.lon - p_b.lon) ** 2) | [
"def",
"distance",
"(",
"p_a",
",",
"p_b",
")",
":",
"return",
"sqrt",
"(",
"(",
"p_a",
".",
"lat",
"-",
"p_b",
".",
"lat",
")",
"**",
"2",
"+",
"(",
"p_a",
".",
"lon",
"-",
"p_b",
".",
"lon",
")",
"**",
"2",
")"
] | Euclidean distance, between two points
Args:
p_a (:obj:`Point`)
p_b (:obj:`Point`)
Returns:
float: distance, in degrees | [
"Euclidean",
"distance",
"between",
"two",
"points"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/compression.py#L40-L49 |
ruipgil/TrackToTrip | tracktotrip/compression.py | point_line_distance | def point_line_distance(point, start, end):
""" Distance from a point to a line, formed by two points
Args:
point (:obj:`Point`)
start (:obj:`Point`): line point
end (:obj:`Point`): line point
Returns:
float: distance to line, in degrees
"""
if start == end:
... | python | def point_line_distance(point, start, end):
""" Distance from a point to a line, formed by two points
Args:
point (:obj:`Point`)
start (:obj:`Point`): line point
end (:obj:`Point`): line point
Returns:
float: distance to line, in degrees
"""
if start == end:
... | [
"def",
"point_line_distance",
"(",
"point",
",",
"start",
",",
"end",
")",
":",
"if",
"start",
"==",
"end",
":",
"return",
"distance",
"(",
"point",
",",
"start",
")",
"else",
":",
"un_dist",
"=",
"abs",
"(",
"(",
"end",
".",
"lat",
"-",
"start",
"... | Distance from a point to a line, formed by two points
Args:
point (:obj:`Point`)
start (:obj:`Point`): line point
end (:obj:`Point`): line point
Returns:
float: distance to line, in degrees | [
"Distance",
"from",
"a",
"point",
"to",
"a",
"line",
"formed",
"by",
"two",
"points"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/compression.py#L51-L73 |
ruipgil/TrackToTrip | tracktotrip/compression.py | drp | def drp(points, epsilon):
""" Douglas ramer peucker
Based on https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm
Args:
points (:obj:`list` of :obj:`Point`)
epsilon (float): drp threshold
Returns:
:obj:`list` of :obj:`Point`
"""
dmax = 0.0
i... | python | def drp(points, epsilon):
""" Douglas ramer peucker
Based on https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm
Args:
points (:obj:`list` of :obj:`Point`)
epsilon (float): drp threshold
Returns:
:obj:`list` of :obj:`Point`
"""
dmax = 0.0
i... | [
"def",
"drp",
"(",
"points",
",",
"epsilon",
")",
":",
"dmax",
"=",
"0.0",
"index",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"points",
")",
"-",
"1",
")",
":",
"dist",
"=",
"point_line_distance",
"(",
"points",
"[",
"i",
... | Douglas ramer peucker
Based on https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm
Args:
points (:obj:`list` of :obj:`Point`)
epsilon (float): drp threshold
Returns:
:obj:`list` of :obj:`Point` | [
"Douglas",
"ramer",
"peucker"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/compression.py#L75-L98 |
ruipgil/TrackToTrip | tracktotrip/compression.py | td_sp | def td_sp(points, speed_threshold):
""" Top-Down Speed-Based Trajectory Compression Algorithm
Detailed in https://www.itc.nl/library/Papers_2003/peer_ref_conf/meratnia_new.pdf
Args:
points (:obj:`list` of :obj:`Point`): trajectory or part of it
speed_threshold (float): max speed error, in ... | python | def td_sp(points, speed_threshold):
""" Top-Down Speed-Based Trajectory Compression Algorithm
Detailed in https://www.itc.nl/library/Papers_2003/peer_ref_conf/meratnia_new.pdf
Args:
points (:obj:`list` of :obj:`Point`): trajectory or part of it
speed_threshold (float): max speed error, in ... | [
"def",
"td_sp",
"(",
"points",
",",
"speed_threshold",
")",
":",
"if",
"len",
"(",
"points",
")",
"<=",
"2",
":",
"return",
"points",
"else",
":",
"max_speed_threshold",
"=",
"0",
"found_index",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"le... | Top-Down Speed-Based Trajectory Compression Algorithm
Detailed in https://www.itc.nl/library/Papers_2003/peer_ref_conf/meratnia_new.pdf
Args:
points (:obj:`list` of :obj:`Point`): trajectory or part of it
speed_threshold (float): max speed error, in km/h
Returns:
:obj:`list` of :ob... | [
"Top",
"-",
"Down",
"Speed",
"-",
"Based",
"Trajectory",
"Compression",
"Algorithm"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/compression.py#L100-L134 |
ruipgil/TrackToTrip | tracktotrip/compression.py | td_tr | def td_tr(points, dist_threshold):
""" Top-Down Time-Ratio Trajectory Compression Algorithm
Detailed in https://www.itc.nl/library/Papers_2003/peer_ref_conf/meratnia_new.pdf
Args:
points (:obj:`list` of :obj:`Point`): trajectory or part of it
dist_threshold (float): max distance error, in ... | python | def td_tr(points, dist_threshold):
""" Top-Down Time-Ratio Trajectory Compression Algorithm
Detailed in https://www.itc.nl/library/Papers_2003/peer_ref_conf/meratnia_new.pdf
Args:
points (:obj:`list` of :obj:`Point`): trajectory or part of it
dist_threshold (float): max distance error, in ... | [
"def",
"td_tr",
"(",
"points",
",",
"dist_threshold",
")",
":",
"if",
"len",
"(",
"points",
")",
"<=",
"2",
":",
"return",
"points",
"else",
":",
"max_dist_threshold",
"=",
"0",
"found_index",
"=",
"0",
"delta_e",
"=",
"time_dist",
"(",
"points",
"[",
... | Top-Down Time-Ratio Trajectory Compression Algorithm
Detailed in https://www.itc.nl/library/Papers_2003/peer_ref_conf/meratnia_new.pdf
Args:
points (:obj:`list` of :obj:`Point`): trajectory or part of it
dist_threshold (float): max distance error, in meters
Returns:
:obj:`list` of ... | [
"Top",
"-",
"Down",
"Time",
"-",
"Ratio",
"Trajectory",
"Compression",
"Algorithm"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/compression.py#L136-L177 |
ruipgil/TrackToTrip | tracktotrip/compression.py | spt | def spt(points, max_dist_error, max_speed_error):
""" A combination of both `td_sp` and `td_tr`
Detailed in,
Spatiotemporal Compression Techniques for Moving Point Objects,
Nirvana Meratnia and Rolf A. de By, 2004,
in Advances in Database Technology - EDBT 2004: 9th
Internationa... | python | def spt(points, max_dist_error, max_speed_error):
""" A combination of both `td_sp` and `td_tr`
Detailed in,
Spatiotemporal Compression Techniques for Moving Point Objects,
Nirvana Meratnia and Rolf A. de By, 2004,
in Advances in Database Technology - EDBT 2004: 9th
Internationa... | [
"def",
"spt",
"(",
"points",
",",
"max_dist_error",
",",
"max_speed_error",
")",
":",
"if",
"len",
"(",
"points",
")",
"<=",
"2",
":",
"return",
"points",
"else",
":",
"is_error",
"=",
"False",
"e",
"=",
"1",
"while",
"e",
"<",
"len",
"(",
"points",
... | A combination of both `td_sp` and `td_tr`
Detailed in,
Spatiotemporal Compression Techniques for Moving Point Objects,
Nirvana Meratnia and Rolf A. de By, 2004,
in Advances in Database Technology - EDBT 2004: 9th
International Conference on Extending Database Technology,
Her... | [
"A",
"combination",
"of",
"both",
"td_sp",
"and",
"td_tr"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/compression.py#L179-L236 |
ruipgil/TrackToTrip | tracktotrip/track.py | Track.generate_name | def generate_name(self, name_format=DEFAULT_FILE_NAME_FORMAT):
""" Generates a name for the track
The name is generated based on the date of the first point of the
track, or in case it doesn't exist, "EmptyTrack"
Args:
name_format (str, optional): Name formar to give to the... | python | def generate_name(self, name_format=DEFAULT_FILE_NAME_FORMAT):
""" Generates a name for the track
The name is generated based on the date of the first point of the
track, or in case it doesn't exist, "EmptyTrack"
Args:
name_format (str, optional): Name formar to give to the... | [
"def",
"generate_name",
"(",
"self",
",",
"name_format",
"=",
"DEFAULT_FILE_NAME_FORMAT",
")",
":",
"if",
"len",
"(",
"self",
".",
"segments",
")",
">",
"0",
":",
"return",
"self",
".",
"segments",
"[",
"0",
"]",
".",
"points",
"[",
"0",
"]",
".",
"t... | Generates a name for the track
The name is generated based on the date of the first point of the
track, or in case it doesn't exist, "EmptyTrack"
Args:
name_format (str, optional): Name formar to give to the track, based on
its start time. Defaults to DEFAULT_FILE_N... | [
"Generates",
"a",
"name",
"for",
"the",
"track"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/track.py#L44-L59 |
ruipgil/TrackToTrip | tracktotrip/track.py | Track.smooth | def smooth(self, strategy, noise):
""" In-place smoothing of segments
Returns:
:obj:`Track`: self
"""
print noise
for segment in self.segments:
segment.smooth(noise, strategy)
return self | python | def smooth(self, strategy, noise):
""" In-place smoothing of segments
Returns:
:obj:`Track`: self
"""
print noise
for segment in self.segments:
segment.smooth(noise, strategy)
return self | [
"def",
"smooth",
"(",
"self",
",",
"strategy",
",",
"noise",
")",
":",
"print",
"noise",
"for",
"segment",
"in",
"self",
".",
"segments",
":",
"segment",
".",
"smooth",
"(",
"noise",
",",
"strategy",
")",
"return",
"self"
] | In-place smoothing of segments
Returns:
:obj:`Track`: self | [
"In",
"-",
"place",
"smoothing",
"of",
"segments"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/track.py#L71-L80 |
ruipgil/TrackToTrip | tracktotrip/track.py | Track.segment | def segment(self, eps, min_time):
"""In-place segmentation of segments
Spatio-temporal segmentation of each segment
The number of segments may increse after this step
Returns:
This track
"""
new_segments = []
for segment in self.segments:
... | python | def segment(self, eps, min_time):
"""In-place segmentation of segments
Spatio-temporal segmentation of each segment
The number of segments may increse after this step
Returns:
This track
"""
new_segments = []
for segment in self.segments:
... | [
"def",
"segment",
"(",
"self",
",",
"eps",
",",
"min_time",
")",
":",
"new_segments",
"=",
"[",
"]",
"for",
"segment",
"in",
"self",
".",
"segments",
":",
"segmented",
"=",
"segment",
".",
"segment",
"(",
"eps",
",",
"min_time",
")",
"for",
"seg",
"i... | In-place segmentation of segments
Spatio-temporal segmentation of each segment
The number of segments may increse after this step
Returns:
This track | [
"In",
"-",
"place",
"segmentation",
"of",
"segments"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/track.py#L82-L97 |
ruipgil/TrackToTrip | tracktotrip/track.py | Track.simplify | def simplify(self, eps, max_dist_error, max_speed_error, topology_only=False):
""" In-place simplification of segments
Args:
max_dist_error (float): Min distance error, in meters
max_speed_error (float): Min speed error, in km/h
topology_only: Boolean, optional. True... | python | def simplify(self, eps, max_dist_error, max_speed_error, topology_only=False):
""" In-place simplification of segments
Args:
max_dist_error (float): Min distance error, in meters
max_speed_error (float): Min speed error, in km/h
topology_only: Boolean, optional. True... | [
"def",
"simplify",
"(",
"self",
",",
"eps",
",",
"max_dist_error",
",",
"max_speed_error",
",",
"topology_only",
"=",
"False",
")",
":",
"for",
"segment",
"in",
"self",
".",
"segments",
":",
"segment",
".",
"simplify",
"(",
"eps",
",",
"max_dist_error",
",... | In-place simplification of segments
Args:
max_dist_error (float): Min distance error, in meters
max_speed_error (float): Min speed error, in km/h
topology_only: Boolean, optional. True to keep
the topology, neglecting velocity and time
accurac... | [
"In",
"-",
"place",
"simplification",
"of",
"segments"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/track.py#L99-L115 |
ruipgil/TrackToTrip | tracktotrip/track.py | Track.infer_transportation_mode | def infer_transportation_mode(self, clf, min_time):
"""In-place transportation mode inferring of segments
Returns:
This track
"""
for segment in self.segments:
segment.infer_transportation_mode(clf, min_time)
return self | python | def infer_transportation_mode(self, clf, min_time):
"""In-place transportation mode inferring of segments
Returns:
This track
"""
for segment in self.segments:
segment.infer_transportation_mode(clf, min_time)
return self | [
"def",
"infer_transportation_mode",
"(",
"self",
",",
"clf",
",",
"min_time",
")",
":",
"for",
"segment",
"in",
"self",
".",
"segments",
":",
"segment",
".",
"infer_transportation_mode",
"(",
"clf",
",",
"min_time",
")",
"return",
"self"
] | In-place transportation mode inferring of segments
Returns:
This track | [
"In",
"-",
"place",
"transportation",
"mode",
"inferring",
"of",
"segments"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/track.py#L117-L125 |
ruipgil/TrackToTrip | tracktotrip/track.py | Track.to_trip | def to_trip(
self,
smooth,
smooth_strategy,
smooth_noise,
seg,
seg_eps,
seg_min_time,
simplify,
simplify_max_dist_error,
simplify_max_speed_error
):
"""In-place, transformation of a tr... | python | def to_trip(
self,
smooth,
smooth_strategy,
smooth_noise,
seg,
seg_eps,
seg_min_time,
simplify,
simplify_max_dist_error,
simplify_max_speed_error
):
"""In-place, transformation of a tr... | [
"def",
"to_trip",
"(",
"self",
",",
"smooth",
",",
"smooth_strategy",
",",
"smooth_noise",
",",
"seg",
",",
"seg_eps",
",",
"seg_min_time",
",",
"simplify",
",",
"simplify_max_dist_error",
",",
"simplify_max_speed_error",
")",
":",
"self",
".",
"compute_metrics",
... | In-place, transformation of a track into a trip
A trip is a more accurate depiction of reality than a
track.
For a track to become a trip it need to go through the
following steps:
+ noise removal
+ smoothing
+ spatio-temporal segmentation
... | [
"In",
"-",
"place",
"transformation",
"of",
"a",
"track",
"into",
"a",
"trip"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/track.py#L137-L189 |
ruipgil/TrackToTrip | tracktotrip/track.py | Track.infer_transportation_modes | def infer_transportation_modes(self, dt_threshold=10):
"""In-place transportation inferring of segments
Returns:
This track
"""
self.segments = [
segment.infer_transportation_mode(dt_threshold=dt_threshold)
for segment in self.segments
]
... | python | def infer_transportation_modes(self, dt_threshold=10):
"""In-place transportation inferring of segments
Returns:
This track
"""
self.segments = [
segment.infer_transportation_mode(dt_threshold=dt_threshold)
for segment in self.segments
]
... | [
"def",
"infer_transportation_modes",
"(",
"self",
",",
"dt_threshold",
"=",
"10",
")",
":",
"self",
".",
"segments",
"=",
"[",
"segment",
".",
"infer_transportation_mode",
"(",
"dt_threshold",
"=",
"dt_threshold",
")",
"for",
"segment",
"in",
"self",
".",
"seg... | In-place transportation inferring of segments
Returns:
This track | [
"In",
"-",
"place",
"transportation",
"inferring",
"of",
"segments"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/track.py#L191-L201 |
ruipgil/TrackToTrip | tracktotrip/track.py | Track.infer_location | def infer_location(
self,
location_query,
max_distance,
google_key,
foursquare_client_id,
foursquare_client_secret,
limit
):
"""In-place location inferring of segments
Returns:
This track
"""... | python | def infer_location(
self,
location_query,
max_distance,
google_key,
foursquare_client_id,
foursquare_client_secret,
limit
):
"""In-place location inferring of segments
Returns:
This track
"""... | [
"def",
"infer_location",
"(",
"self",
",",
"location_query",
",",
"max_distance",
",",
"google_key",
",",
"foursquare_client_id",
",",
"foursquare_client_secret",
",",
"limit",
")",
":",
"self",
".",
"segments",
"=",
"[",
"segment",
".",
"infer_location",
"(",
"... | In-place location inferring of segments
Returns:
This track | [
"In",
"-",
"place",
"location",
"inferring",
"of",
"segments"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/track.py#L204-L229 |
ruipgil/TrackToTrip | tracktotrip/track.py | Track.to_json | def to_json(self):
"""Converts track to a JSON serializable format
Returns:
Map with the name, and segments of the track.
"""
return {
'name': self.name,
'segments': [segment.to_json() for segment in self.segments],
'meta': self.meta
... | python | def to_json(self):
"""Converts track to a JSON serializable format
Returns:
Map with the name, and segments of the track.
"""
return {
'name': self.name,
'segments': [segment.to_json() for segment in self.segments],
'meta': self.meta
... | [
"def",
"to_json",
"(",
"self",
")",
":",
"return",
"{",
"'name'",
":",
"self",
".",
"name",
",",
"'segments'",
":",
"[",
"segment",
".",
"to_json",
"(",
")",
"for",
"segment",
"in",
"self",
".",
"segments",
"]",
",",
"'meta'",
":",
"self",
".",
"me... | Converts track to a JSON serializable format
Returns:
Map with the name, and segments of the track. | [
"Converts",
"track",
"to",
"a",
"JSON",
"serializable",
"format"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/track.py#L231-L241 |
ruipgil/TrackToTrip | tracktotrip/track.py | Track.merge_and_fit | def merge_and_fit(self, track, pairings):
""" Merges another track with this one, ordering the points based on a
distance heuristic
Args:
track (:obj:`Track`): Track to merge with
pairings
Returns:
:obj:`Segment`: self
"""
for (se... | python | def merge_and_fit(self, track, pairings):
""" Merges another track with this one, ordering the points based on a
distance heuristic
Args:
track (:obj:`Track`): Track to merge with
pairings
Returns:
:obj:`Segment`: self
"""
for (se... | [
"def",
"merge_and_fit",
"(",
"self",
",",
"track",
",",
"pairings",
")",
":",
"for",
"(",
"self_seg_index",
",",
"track_seg_index",
",",
"_",
")",
"in",
"pairings",
":",
"self_s",
"=",
"self",
".",
"segments",
"[",
"self_seg_index",
"]",
"ss_start",
"=",
... | Merges another track with this one, ordering the points based on a
distance heuristic
Args:
track (:obj:`Track`): Track to merge with
pairings
Returns:
:obj:`Segment`: self | [
"Merges",
"another",
"track",
"with",
"this",
"one",
"ordering",
"the",
"points",
"based",
"on",
"a",
"distance",
"heuristic"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/track.py#L244-L270 |
ruipgil/TrackToTrip | tracktotrip/track.py | Track.get_point_index | def get_point_index(self, point):
""" Gets of the closest first point
Args:
point (:obj:`Point`)
Returns:
(int, int): Segment id and point index in that segment
"""
for i, segment in enumerate(self.segments):
idx = segment.getPointIndex(point)... | python | def get_point_index(self, point):
""" Gets of the closest first point
Args:
point (:obj:`Point`)
Returns:
(int, int): Segment id and point index in that segment
"""
for i, segment in enumerate(self.segments):
idx = segment.getPointIndex(point)... | [
"def",
"get_point_index",
"(",
"self",
",",
"point",
")",
":",
"for",
"i",
",",
"segment",
"in",
"enumerate",
"(",
"self",
".",
"segments",
")",
":",
"idx",
"=",
"segment",
".",
"getPointIndex",
"(",
"point",
")",
"if",
"idx",
"!=",
"-",
"1",
":",
... | Gets of the closest first point
Args:
point (:obj:`Point`)
Returns:
(int, int): Segment id and point index in that segment | [
"Gets",
"of",
"the",
"closest",
"first",
"point"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/track.py#L272-L284 |
ruipgil/TrackToTrip | tracktotrip/track.py | Track.bounds | def bounds(self, thr=0):
""" Gets the bounds of this segment
Returns:
(float, float, float, float): Bounds, with min latitude, min longitude,
max latitude and max longitude
"""
min_lat = float("inf")
min_lon = float("inf")
max_lat = -float("in... | python | def bounds(self, thr=0):
""" Gets the bounds of this segment
Returns:
(float, float, float, float): Bounds, with min latitude, min longitude,
max latitude and max longitude
"""
min_lat = float("inf")
min_lon = float("inf")
max_lat = -float("in... | [
"def",
"bounds",
"(",
"self",
",",
"thr",
"=",
"0",
")",
":",
"min_lat",
"=",
"float",
"(",
"\"inf\"",
")",
"min_lon",
"=",
"float",
"(",
"\"inf\"",
")",
"max_lat",
"=",
"-",
"float",
"(",
"\"inf\"",
")",
"max_lon",
"=",
"-",
"float",
"(",
"\"inf\"... | Gets the bounds of this segment
Returns:
(float, float, float, float): Bounds, with min latitude, min longitude,
max latitude and max longitude | [
"Gets",
"the",
"bounds",
"of",
"this",
"segment"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/track.py#L286-L303 |
ruipgil/TrackToTrip | tracktotrip/track.py | Track.similarity | def similarity(self, track):
""" Compares two tracks based on their topology
This method compares the given track against this
instance. It only verifies if given track is close
to this one, not the other way arround
Args:
track (:obj:`Track`)
Returns:
... | python | def similarity(self, track):
""" Compares two tracks based on their topology
This method compares the given track against this
instance. It only verifies if given track is close
to this one, not the other way arround
Args:
track (:obj:`Track`)
Returns:
... | [
"def",
"similarity",
"(",
"self",
",",
"track",
")",
":",
"idx",
"=",
"index",
".",
"Index",
"(",
")",
"i",
"=",
"0",
"for",
"i",
",",
"segment",
"in",
"enumerate",
"(",
"self",
".",
"segments",
")",
":",
"idx",
".",
"insert",
"(",
"i",
",",
"s... | Compares two tracks based on their topology
This method compares the given track against this
instance. It only verifies if given track is close
to this one, not the other way arround
Args:
track (:obj:`Track`)
Returns:
Two-tuple with global similarity b... | [
"Compares",
"two",
"tracks",
"based",
"on",
"their",
"topology"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/track.py#L316-L353 |
ruipgil/TrackToTrip | tracktotrip/track.py | Track.to_gpx | def to_gpx(self):
"""Converts track to a GPX format
Uses GPXPY library as an intermediate format
Returns:
A string with the GPX/XML track
"""
gpx_segments = []
for segment in self.segments:
gpx_points = []
for point in segment.points:... | python | def to_gpx(self):
"""Converts track to a GPX format
Uses GPXPY library as an intermediate format
Returns:
A string with the GPX/XML track
"""
gpx_segments = []
for segment in self.segments:
gpx_points = []
for point in segment.points:... | [
"def",
"to_gpx",
"(",
"self",
")",
":",
"gpx_segments",
"=",
"[",
"]",
"for",
"segment",
"in",
"self",
".",
"segments",
":",
"gpx_points",
"=",
"[",
"]",
"for",
"point",
"in",
"segment",
".",
"points",
":",
"time",
"=",
"''",
"if",
"point",
".",
"t... | Converts track to a GPX format
Uses GPXPY library as an intermediate format
Returns:
A string with the GPX/XML track | [
"Converts",
"track",
"to",
"a",
"GPX",
"format"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/track.py#L367-L398 |
ruipgil/TrackToTrip | tracktotrip/track.py | Track.timezone | def timezone(self, timezone=0):
""" Sets the timezone of the entire track
Args:
timezone (int): Timezone hour delta
"""
tz_dt = timedelta(hours=timezone)
for segment in self.segments:
for point in segment.points:
point.time = point.time +... | python | def timezone(self, timezone=0):
""" Sets the timezone of the entire track
Args:
timezone (int): Timezone hour delta
"""
tz_dt = timedelta(hours=timezone)
for segment in self.segments:
for point in segment.points:
point.time = point.time +... | [
"def",
"timezone",
"(",
"self",
",",
"timezone",
"=",
"0",
")",
":",
"tz_dt",
"=",
"timedelta",
"(",
"hours",
"=",
"timezone",
")",
"for",
"segment",
"in",
"self",
".",
"segments",
":",
"for",
"point",
"in",
"segment",
".",
"points",
":",
"point",
".... | Sets the timezone of the entire track
Args:
timezone (int): Timezone hour delta | [
"Sets",
"the",
"timezone",
"of",
"the",
"entire",
"track"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/track.py#L400-L411 |
ruipgil/TrackToTrip | tracktotrip/track.py | Track.to_life | def to_life(self):
"""Converts track to LIFE format
"""
buff = "--%s\n" % self.segments[0].points[0].time.strftime("%Y_%m_%d")
# buff += "--" + day
# buff += "UTC+s" # if needed
def military_time(time):
""" Converts time to military time
Args:
... | python | def to_life(self):
"""Converts track to LIFE format
"""
buff = "--%s\n" % self.segments[0].points[0].time.strftime("%Y_%m_%d")
# buff += "--" + day
# buff += "UTC+s" # if needed
def military_time(time):
""" Converts time to military time
Args:
... | [
"def",
"to_life",
"(",
"self",
")",
":",
"buff",
"=",
"\"--%s\\n\"",
"%",
"self",
".",
"segments",
"[",
"0",
"]",
".",
"points",
"[",
"0",
"]",
".",
"time",
".",
"strftime",
"(",
"\"%Y_%m_%d\"",
")",
"# buff += \"--\" + day",
"# buff += \"UTC+s\" # if needed... | Converts track to LIFE format | [
"Converts",
"track",
"to",
"LIFE",
"format"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/track.py#L413-L502 |
ruipgil/TrackToTrip | tracktotrip/track.py | Track.from_gpx | def from_gpx(file_path):
""" Creates a Track from a GPX file.
No preprocessing is done.
Arguments:
file_path (str): file path and name to the GPX file
Return:
:obj:`list` of :obj:`Track`
"""
gpx = gpxpy.parse(open(file_path, 'r'))
file_na... | python | def from_gpx(file_path):
""" Creates a Track from a GPX file.
No preprocessing is done.
Arguments:
file_path (str): file path and name to the GPX file
Return:
:obj:`list` of :obj:`Track`
"""
gpx = gpxpy.parse(open(file_path, 'r'))
file_na... | [
"def",
"from_gpx",
"(",
"file_path",
")",
":",
"gpx",
"=",
"gpxpy",
".",
"parse",
"(",
"open",
"(",
"file_path",
",",
"'r'",
")",
")",
"file_name",
"=",
"basename",
"(",
"file_path",
")",
"tracks",
"=",
"[",
"]",
"for",
"i",
",",
"track",
"in",
"en... | Creates a Track from a GPX file.
No preprocessing is done.
Arguments:
file_path (str): file path and name to the GPX file
Return:
:obj:`list` of :obj:`Track` | [
"Creates",
"a",
"Track",
"from",
"a",
"GPX",
"file",
"."
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/track.py#L505-L530 |
ruipgil/TrackToTrip | tracktotrip/track.py | Track.from_json | def from_json(json):
"""Creates a Track from a JSON file.
No preprocessing is done.
Arguments:
json: map with the keys: name (optional) and segments.
Return:
A track instance
"""
segments = [Segment.from_json(s) for s in json['segments']]
... | python | def from_json(json):
"""Creates a Track from a JSON file.
No preprocessing is done.
Arguments:
json: map with the keys: name (optional) and segments.
Return:
A track instance
"""
segments = [Segment.from_json(s) for s in json['segments']]
... | [
"def",
"from_json",
"(",
"json",
")",
":",
"segments",
"=",
"[",
"Segment",
".",
"from_json",
"(",
"s",
")",
"for",
"s",
"in",
"json",
"[",
"'segments'",
"]",
"]",
"return",
"Track",
"(",
"json",
"[",
"'name'",
"]",
",",
"segments",
")",
".",
"comp... | Creates a Track from a JSON file.
No preprocessing is done.
Arguments:
json: map with the keys: name (optional) and segments.
Return:
A track instance | [
"Creates",
"a",
"Track",
"from",
"a",
"JSON",
"file",
"."
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/track.py#L533-L544 |
ruipgil/TrackToTrip | tracktotrip/similarity.py | normalize | def normalize(p):
"""Normalizes a point/vector
Args:
p ([float, float]): x and y coordinates
Returns:
float
"""
l = math.sqrt(p[0]**2 + p[1]**2)
return [0.0, 0.0] if l == 0 else [p[0]/l, p[1]/l] | python | def normalize(p):
"""Normalizes a point/vector
Args:
p ([float, float]): x and y coordinates
Returns:
float
"""
l = math.sqrt(p[0]**2 + p[1]**2)
return [0.0, 0.0] if l == 0 else [p[0]/l, p[1]/l] | [
"def",
"normalize",
"(",
"p",
")",
":",
"l",
"=",
"math",
".",
"sqrt",
"(",
"p",
"[",
"0",
"]",
"**",
"2",
"+",
"p",
"[",
"1",
"]",
"**",
"2",
")",
"return",
"[",
"0.0",
",",
"0.0",
"]",
"if",
"l",
"==",
"0",
"else",
"[",
"p",
"[",
"0",... | Normalizes a point/vector
Args:
p ([float, float]): x and y coordinates
Returns:
float | [
"Normalizes",
"a",
"point",
"/",
"vector"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/similarity.py#L21-L30 |
ruipgil/TrackToTrip | tracktotrip/similarity.py | line | def line(p1, p2):
"""Creates a line from two points
From http://stackoverflow.com/a/20679579
Args:
p1 ([float, float]): x and y coordinates
p2 ([float, float]): x and y coordinates
Returns:
(float, float, float): x, y and _
"""
A = (p1[1] - p2[1])
B = (p2[0] - p1[0]... | python | def line(p1, p2):
"""Creates a line from two points
From http://stackoverflow.com/a/20679579
Args:
p1 ([float, float]): x and y coordinates
p2 ([float, float]): x and y coordinates
Returns:
(float, float, float): x, y and _
"""
A = (p1[1] - p2[1])
B = (p2[0] - p1[0]... | [
"def",
"line",
"(",
"p1",
",",
"p2",
")",
":",
"A",
"=",
"(",
"p1",
"[",
"1",
"]",
"-",
"p2",
"[",
"1",
"]",
")",
"B",
"=",
"(",
"p2",
"[",
"0",
"]",
"-",
"p1",
"[",
"0",
"]",
")",
"C",
"=",
"(",
"p1",
"[",
"0",
"]",
"*",
"p2",
"[... | Creates a line from two points
From http://stackoverflow.com/a/20679579
Args:
p1 ([float, float]): x and y coordinates
p2 ([float, float]): x and y coordinates
Returns:
(float, float, float): x, y and _ | [
"Creates",
"a",
"line",
"from",
"two",
"points"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/similarity.py#L55-L69 |
ruipgil/TrackToTrip | tracktotrip/similarity.py | intersection | def intersection(L1, L2):
"""Intersects two line segments
Args:
L1 ([float, float]): x and y coordinates
L2 ([float, float]): x and y coordinates
Returns:
bool: if they intersect
(float, float): x and y of intersection, if they do
"""
D = L1[0] * L2[1] - L1[1] * L2[0... | python | def intersection(L1, L2):
"""Intersects two line segments
Args:
L1 ([float, float]): x and y coordinates
L2 ([float, float]): x and y coordinates
Returns:
bool: if they intersect
(float, float): x and y of intersection, if they do
"""
D = L1[0] * L2[1] - L1[1] * L2[0... | [
"def",
"intersection",
"(",
"L1",
",",
"L2",
")",
":",
"D",
"=",
"L1",
"[",
"0",
"]",
"*",
"L2",
"[",
"1",
"]",
"-",
"L1",
"[",
"1",
"]",
"*",
"L2",
"[",
"0",
"]",
"Dx",
"=",
"L1",
"[",
"2",
"]",
"*",
"L2",
"[",
"1",
"]",
"-",
"L1",
... | Intersects two line segments
Args:
L1 ([float, float]): x and y coordinates
L2 ([float, float]): x and y coordinates
Returns:
bool: if they intersect
(float, float): x and y of intersection, if they do | [
"Intersects",
"two",
"line",
"segments"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/similarity.py#L71-L89 |
ruipgil/TrackToTrip | tracktotrip/similarity.py | distance_tt_point | def distance_tt_point(a, b):
""" Euclidean distance between two (tracktotrip) points
Args:
a (:obj:`Point`)
b (:obj:`Point`)
Returns:
float
"""
return math.sqrt((b.lat-a.lat)**2 + (b.lon-a.lon)**2) | python | def distance_tt_point(a, b):
""" Euclidean distance between two (tracktotrip) points
Args:
a (:obj:`Point`)
b (:obj:`Point`)
Returns:
float
"""
return math.sqrt((b.lat-a.lat)**2 + (b.lon-a.lon)**2) | [
"def",
"distance_tt_point",
"(",
"a",
",",
"b",
")",
":",
"return",
"math",
".",
"sqrt",
"(",
"(",
"b",
".",
"lat",
"-",
"a",
".",
"lat",
")",
"**",
"2",
"+",
"(",
"b",
".",
"lon",
"-",
"a",
".",
"lon",
")",
"**",
"2",
")"
] | Euclidean distance between two (tracktotrip) points
Args:
a (:obj:`Point`)
b (:obj:`Point`)
Returns:
float | [
"Euclidean",
"distance",
"between",
"two",
"(",
"tracktotrip",
")",
"points"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/similarity.py#L102-L111 |
ruipgil/TrackToTrip | tracktotrip/similarity.py | closest_point | def closest_point(a, b, p):
"""Finds closest point in a line segment
Args:
a ([float, float]): x and y coordinates. Line start
b ([float, float]): x and y coordinates. Line end
p ([float, float]): x and y coordinates. Point to find in the segment
Returns:
(float, float): x a... | python | def closest_point(a, b, p):
"""Finds closest point in a line segment
Args:
a ([float, float]): x and y coordinates. Line start
b ([float, float]): x and y coordinates. Line end
p ([float, float]): x and y coordinates. Point to find in the segment
Returns:
(float, float): x a... | [
"def",
"closest_point",
"(",
"a",
",",
"b",
",",
"p",
")",
":",
"ap",
"=",
"[",
"p",
"[",
"0",
"]",
"-",
"a",
"[",
"0",
"]",
",",
"p",
"[",
"1",
"]",
"-",
"a",
"[",
"1",
"]",
"]",
"ab",
"=",
"[",
"b",
"[",
"0",
"]",
"-",
"a",
"[",
... | Finds closest point in a line segment
Args:
a ([float, float]): x and y coordinates. Line start
b ([float, float]): x and y coordinates. Line end
p ([float, float]): x and y coordinates. Point to find in the segment
Returns:
(float, float): x and y coordinates of the closest poi... | [
"Finds",
"closest",
"point",
"in",
"a",
"line",
"segment"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/similarity.py#L113-L136 |
ruipgil/TrackToTrip | tracktotrip/similarity.py | distance_to_line | def distance_to_line(a, b, p):
"""Closest distance between a line segment and a point
Args:
a ([float, float]): x and y coordinates. Line start
b ([float, float]): x and y coordinates. Line end
p ([float, float]): x and y coordinates. Point to compute the distance
Returns:
f... | python | def distance_to_line(a, b, p):
"""Closest distance between a line segment and a point
Args:
a ([float, float]): x and y coordinates. Line start
b ([float, float]): x and y coordinates. Line end
p ([float, float]): x and y coordinates. Point to compute the distance
Returns:
f... | [
"def",
"distance_to_line",
"(",
"a",
",",
"b",
",",
"p",
")",
":",
"return",
"distance",
"(",
"closest_point",
"(",
"a",
",",
"b",
",",
"p",
")",
",",
"p",
")"
] | Closest distance between a line segment and a point
Args:
a ([float, float]): x and y coordinates. Line start
b ([float, float]): x and y coordinates. Line end
p ([float, float]): x and y coordinates. Point to compute the distance
Returns:
float | [
"Closest",
"distance",
"between",
"a",
"line",
"segment",
"and",
"a",
"point"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/similarity.py#L138-L148 |
ruipgil/TrackToTrip | tracktotrip/similarity.py | distance_similarity | def distance_similarity(a, b, p, T=CLOSE_DISTANCE_THRESHOLD):
"""Computes the distance similarity between a line segment
and a point
Args:
a ([float, float]): x and y coordinates. Line start
b ([float, float]): x and y coordinates. Line end
p ([float, float]): x and y coordinates. P... | python | def distance_similarity(a, b, p, T=CLOSE_DISTANCE_THRESHOLD):
"""Computes the distance similarity between a line segment
and a point
Args:
a ([float, float]): x and y coordinates. Line start
b ([float, float]): x and y coordinates. Line end
p ([float, float]): x and y coordinates. P... | [
"def",
"distance_similarity",
"(",
"a",
",",
"b",
",",
"p",
",",
"T",
"=",
"CLOSE_DISTANCE_THRESHOLD",
")",
":",
"d",
"=",
"distance_to_line",
"(",
"a",
",",
"b",
",",
"p",
")",
"r",
"=",
"(",
"-",
"1",
"/",
"float",
"(",
"T",
")",
")",
"*",
"a... | Computes the distance similarity between a line segment
and a point
Args:
a ([float, float]): x and y coordinates. Line start
b ([float, float]): x and y coordinates. Line end
p ([float, float]): x and y coordinates. Point to compute the distance
Returns:
float: between 0 an... | [
"Computes",
"the",
"distance",
"similarity",
"between",
"a",
"line",
"segment",
"and",
"a",
"point"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/similarity.py#L151-L165 |
ruipgil/TrackToTrip | tracktotrip/similarity.py | line_distance_similarity | def line_distance_similarity(p1a, p1b, p2a, p2b, T=CLOSE_DISTANCE_THRESHOLD):
"""Line distance similarity between two line segments
Args:
p1a ([float, float]): x and y coordinates. Line A start
p1b ([float, float]): x and y coordinates. Line A end
p2a ([float, float]): x and y coordinat... | python | def line_distance_similarity(p1a, p1b, p2a, p2b, T=CLOSE_DISTANCE_THRESHOLD):
"""Line distance similarity between two line segments
Args:
p1a ([float, float]): x and y coordinates. Line A start
p1b ([float, float]): x and y coordinates. Line A end
p2a ([float, float]): x and y coordinat... | [
"def",
"line_distance_similarity",
"(",
"p1a",
",",
"p1b",
",",
"p2a",
",",
"p2b",
",",
"T",
"=",
"CLOSE_DISTANCE_THRESHOLD",
")",
":",
"d1",
"=",
"distance_similarity",
"(",
"p1a",
",",
"p1b",
",",
"p2a",
",",
"T",
"=",
"T",
")",
"d2",
"=",
"distance_... | Line distance similarity between two line segments
Args:
p1a ([float, float]): x and y coordinates. Line A start
p1b ([float, float]): x and y coordinates. Line A end
p2a ([float, float]): x and y coordinates. Line B start
p2b ([float, float]): x and y coordinates. Line B end
Re... | [
"Line",
"distance",
"similarity",
"between",
"two",
"line",
"segments"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/similarity.py#L167-L180 |
ruipgil/TrackToTrip | tracktotrip/similarity.py | line_similarity | def line_similarity(p1a, p1b, p2a, p2b, T=CLOSE_DISTANCE_THRESHOLD):
"""Similarity between two lines
Args:
p1a ([float, float]): x and y coordinates. Line A start
p1b ([float, float]): x and y coordinates. Line A end
p2a ([float, float]): x and y coordinates. Line B start
p2b ([... | python | def line_similarity(p1a, p1b, p2a, p2b, T=CLOSE_DISTANCE_THRESHOLD):
"""Similarity between two lines
Args:
p1a ([float, float]): x and y coordinates. Line A start
p1b ([float, float]): x and y coordinates. Line A end
p2a ([float, float]): x and y coordinates. Line B start
p2b ([... | [
"def",
"line_similarity",
"(",
"p1a",
",",
"p1b",
",",
"p2a",
",",
"p2b",
",",
"T",
"=",
"CLOSE_DISTANCE_THRESHOLD",
")",
":",
"d",
"=",
"line_distance_similarity",
"(",
"p1a",
",",
"p1b",
",",
"p2a",
",",
"p2b",
",",
"T",
"=",
"T",
")",
"a",
"=",
... | Similarity between two lines
Args:
p1a ([float, float]): x and y coordinates. Line A start
p1b ([float, float]): x and y coordinates. Line A end
p2a ([float, float]): x and y coordinates. Line B start
p2b ([float, float]): x and y coordinates. Line B end
Returns:
float: ... | [
"Similarity",
"between",
"two",
"lines"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/similarity.py#L182-L195 |
ruipgil/TrackToTrip | tracktotrip/similarity.py | bounding_box_from | def bounding_box_from(points, i, i1, thr):
"""Creates bounding box for a line segment
Args:
points (:obj:`list` of :obj:`Point`)
i (int): Line segment start, index in points array
i1 (int): Line segment end, index in points array
Returns:
(float, float, float, float): with b... | python | def bounding_box_from(points, i, i1, thr):
"""Creates bounding box for a line segment
Args:
points (:obj:`list` of :obj:`Point`)
i (int): Line segment start, index in points array
i1 (int): Line segment end, index in points array
Returns:
(float, float, float, float): with b... | [
"def",
"bounding_box_from",
"(",
"points",
",",
"i",
",",
"i1",
",",
"thr",
")",
":",
"pi",
"=",
"points",
"[",
"i",
"]",
"pi1",
"=",
"points",
"[",
"i1",
"]",
"min_lat",
"=",
"min",
"(",
"pi",
".",
"lat",
",",
"pi1",
".",
"lat",
")",
"min_lon"... | Creates bounding box for a line segment
Args:
points (:obj:`list` of :obj:`Point`)
i (int): Line segment start, index in points array
i1 (int): Line segment end, index in points array
Returns:
(float, float, float, float): with bounding box min x, min y, max x and max y | [
"Creates",
"bounding",
"box",
"for",
"a",
"line",
"segment"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/similarity.py#L197-L215 |
ruipgil/TrackToTrip | tracktotrip/similarity.py | segment_similarity | def segment_similarity(A, B, T=CLOSE_DISTANCE_THRESHOLD):
"""Computes the similarity between two segments
Args:
A (:obj:`Segment`)
B (:obj:`Segment`)
Returns:
float: between 0 and 1. Where 1 is very similar and 0 is completely different
"""
l_a = len(A.points)
l_b = len(... | python | def segment_similarity(A, B, T=CLOSE_DISTANCE_THRESHOLD):
"""Computes the similarity between two segments
Args:
A (:obj:`Segment`)
B (:obj:`Segment`)
Returns:
float: between 0 and 1. Where 1 is very similar and 0 is completely different
"""
l_a = len(A.points)
l_b = len(... | [
"def",
"segment_similarity",
"(",
"A",
",",
"B",
",",
"T",
"=",
"CLOSE_DISTANCE_THRESHOLD",
")",
":",
"l_a",
"=",
"len",
"(",
"A",
".",
"points",
")",
"l_b",
"=",
"len",
"(",
"B",
".",
"points",
")",
"idx",
"=",
"index",
".",
"Index",
"(",
")",
"... | Computes the similarity between two segments
Args:
A (:obj:`Segment`)
B (:obj:`Segment`)
Returns:
float: between 0 and 1. Where 1 is very similar and 0 is completely different | [
"Computes",
"the",
"similarity",
"between",
"two",
"segments"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/similarity.py#L217-L259 |
ruipgil/TrackToTrip | tracktotrip/similarity.py | sort_segment_points | def sort_segment_points(Aps, Bps):
"""Takes two line segments and sorts all their points,
so that they form a continuous path
Args:
Aps: Array of tracktotrip.Point
Bps: Array of tracktotrip.Point
Returns:
Array with points ordered
"""
mid = []
j = 0
mid.append(Ap... | python | def sort_segment_points(Aps, Bps):
"""Takes two line segments and sorts all their points,
so that they form a continuous path
Args:
Aps: Array of tracktotrip.Point
Bps: Array of tracktotrip.Point
Returns:
Array with points ordered
"""
mid = []
j = 0
mid.append(Ap... | [
"def",
"sort_segment_points",
"(",
"Aps",
",",
"Bps",
")",
":",
"mid",
"=",
"[",
"]",
"j",
"=",
"0",
"mid",
".",
"append",
"(",
"Aps",
"[",
"0",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"Aps",
")",
"-",
"1",
")",
":",
"dist",
"... | Takes two line segments and sorts all their points,
so that they form a continuous path
Args:
Aps: Array of tracktotrip.Point
Bps: Array of tracktotrip.Point
Returns:
Array with points ordered | [
"Takes",
"two",
"line",
"segments",
"and",
"sorts",
"all",
"their",
"points",
"so",
"that",
"they",
"form",
"a",
"continuous",
"path"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/similarity.py#L261-L288 |
ruipgil/TrackToTrip | tracktotrip/point.py | haversine_distance | def haversine_distance(latitude_1, longitude_1, latitude_2, longitude_2):
"""
Haversine distance between two points, expressed in meters.
Implemented from http://www.movable-type.co.uk/scripts/latlong.html
"""
d_lat = to_rad(latitude_1 - latitude_2)
d_lon = to_rad(longitude_1 - longitude_2)
... | python | def haversine_distance(latitude_1, longitude_1, latitude_2, longitude_2):
"""
Haversine distance between two points, expressed in meters.
Implemented from http://www.movable-type.co.uk/scripts/latlong.html
"""
d_lat = to_rad(latitude_1 - latitude_2)
d_lon = to_rad(longitude_1 - longitude_2)
... | [
"def",
"haversine_distance",
"(",
"latitude_1",
",",
"longitude_1",
",",
"latitude_2",
",",
"longitude_2",
")",
":",
"d_lat",
"=",
"to_rad",
"(",
"latitude_1",
"-",
"latitude_2",
")",
"d_lon",
"=",
"to_rad",
"(",
"longitude_1",
"-",
"longitude_2",
")",
"lat1",... | Haversine distance between two points, expressed in meters.
Implemented from http://www.movable-type.co.uk/scripts/latlong.html | [
"Haversine",
"distance",
"between",
"two",
"points",
"expressed",
"in",
"meters",
".",
"Implemented",
"from",
"http",
":",
"//",
"www",
".",
"movable",
"-",
"type",
".",
"co",
".",
"uk",
"/",
"scripts",
"/",
"latlong",
".",
"html"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/point.py#L165-L181 |
ruipgil/TrackToTrip | tracktotrip/point.py | distance | def distance(latitude_1, longitude_1, elevation_1, latitude_2, longitude_2, elevation_2,
haversine=None):
""" Distance between two points """
# If points too distant -- compute haversine distance:
if haversine or (abs(latitude_1 - latitude_2) > .2 or abs(longitude_1 - longitude_2) > .2):
... | python | def distance(latitude_1, longitude_1, elevation_1, latitude_2, longitude_2, elevation_2,
haversine=None):
""" Distance between two points """
# If points too distant -- compute haversine distance:
if haversine or (abs(latitude_1 - latitude_2) > .2 or abs(longitude_1 - longitude_2) > .2):
... | [
"def",
"distance",
"(",
"latitude_1",
",",
"longitude_1",
",",
"elevation_1",
",",
"latitude_2",
",",
"longitude_2",
",",
"elevation_2",
",",
"haversine",
"=",
"None",
")",
":",
"# If points too distant -- compute haversine distance:",
"if",
"haversine",
"or",
"(",
... | Distance between two points | [
"Distance",
"between",
"two",
"points"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/point.py#L184-L202 |
ruipgil/TrackToTrip | tracktotrip/point.py | Point.distance | def distance(self, other):
""" Distance between points
Args:
other (:obj:`Point`)
Returns:
float: Distance in km
"""
return distance(self.lat, self.lon, None, other.lat, other.lon, None) | python | def distance(self, other):
""" Distance between points
Args:
other (:obj:`Point`)
Returns:
float: Distance in km
"""
return distance(self.lat, self.lon, None, other.lat, other.lon, None) | [
"def",
"distance",
"(",
"self",
",",
"other",
")",
":",
"return",
"distance",
"(",
"self",
".",
"lat",
",",
"self",
".",
"lon",
",",
"None",
",",
"other",
".",
"lat",
",",
"other",
".",
"lon",
",",
"None",
")"
] | Distance between points
Args:
other (:obj:`Point`)
Returns:
float: Distance in km | [
"Distance",
"between",
"points"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/point.py#L57-L65 |
ruipgil/TrackToTrip | tracktotrip/point.py | Point.compute_metrics | def compute_metrics(self, previous):
""" Computes the metrics of this point
Computes and updates the dt, vel and acc attributes.
Args:
previous (:obj:`Point`): Point before
Returns:
:obj:`Point`: Self
"""
delta_t = self.time_difference(previous)
... | python | def compute_metrics(self, previous):
""" Computes the metrics of this point
Computes and updates the dt, vel and acc attributes.
Args:
previous (:obj:`Point`): Point before
Returns:
:obj:`Point`: Self
"""
delta_t = self.time_difference(previous)
... | [
"def",
"compute_metrics",
"(",
"self",
",",
"previous",
")",
":",
"delta_t",
"=",
"self",
".",
"time_difference",
"(",
"previous",
")",
"delta_x",
"=",
"self",
".",
"distance",
"(",
"previous",
")",
"vel",
"=",
"0",
"delta_v",
"=",
"0",
"acc",
"=",
"0"... | Computes the metrics of this point
Computes and updates the dt, vel and acc attributes.
Args:
previous (:obj:`Point`): Point before
Returns:
:obj:`Point`: Self | [
"Computes",
"the",
"metrics",
"of",
"this",
"point"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/point.py#L77-L101 |
ruipgil/TrackToTrip | tracktotrip/point.py | Point.from_gpx | def from_gpx(gpx_track_point):
""" Creates a point from GPX representation
Arguments:
gpx_track_point (:obj:`gpxpy.GPXTrackPoint`)
Returns:
:obj:`Point`
"""
return Point(
lat=gpx_track_point.latitude,
lon=gpx_track_point.longitude,... | python | def from_gpx(gpx_track_point):
""" Creates a point from GPX representation
Arguments:
gpx_track_point (:obj:`gpxpy.GPXTrackPoint`)
Returns:
:obj:`Point`
"""
return Point(
lat=gpx_track_point.latitude,
lon=gpx_track_point.longitude,... | [
"def",
"from_gpx",
"(",
"gpx_track_point",
")",
":",
"return",
"Point",
"(",
"lat",
"=",
"gpx_track_point",
".",
"latitude",
",",
"lon",
"=",
"gpx_track_point",
".",
"longitude",
",",
"time",
"=",
"gpx_track_point",
".",
"time",
")"
] | Creates a point from GPX representation
Arguments:
gpx_track_point (:obj:`gpxpy.GPXTrackPoint`)
Returns:
:obj:`Point` | [
"Creates",
"a",
"point",
"from",
"GPX",
"representation"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/point.py#L104-L116 |
ruipgil/TrackToTrip | tracktotrip/point.py | Point.to_json | def to_json(self):
""" Creates a JSON serializable representation of this instance
Returns:
:obj:`dict`: For example,
{
"lat": 9.3470298,
"lon": 3.79274,
"time": "2016-07-15T15:27:53.574110"
}
... | python | def to_json(self):
""" Creates a JSON serializable representation of this instance
Returns:
:obj:`dict`: For example,
{
"lat": 9.3470298,
"lon": 3.79274,
"time": "2016-07-15T15:27:53.574110"
}
... | [
"def",
"to_json",
"(",
"self",
")",
":",
"return",
"{",
"'lat'",
":",
"self",
".",
"lat",
",",
"'lon'",
":",
"self",
".",
"lon",
",",
"'time'",
":",
"self",
".",
"time",
".",
"isoformat",
"(",
")",
"if",
"self",
".",
"time",
"is",
"not",
"None",
... | Creates a JSON serializable representation of this instance
Returns:
:obj:`dict`: For example,
{
"lat": 9.3470298,
"lon": 3.79274,
"time": "2016-07-15T15:27:53.574110"
} | [
"Creates",
"a",
"JSON",
"serializable",
"representation",
"of",
"this",
"instance"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/point.py#L118-L133 |
ruipgil/TrackToTrip | tracktotrip/point.py | Point.from_json | def from_json(json):
""" Creates Point instance from JSON representation
Args:
json (:obj:`dict`): Must have at least the following keys: lat (float), lon (float),
time (string in iso format). Example,
{
"lat": 9.3470298,
... | python | def from_json(json):
""" Creates Point instance from JSON representation
Args:
json (:obj:`dict`): Must have at least the following keys: lat (float), lon (float),
time (string in iso format). Example,
{
"lat": 9.3470298,
... | [
"def",
"from_json",
"(",
"json",
")",
":",
"return",
"Point",
"(",
"lat",
"=",
"json",
"[",
"'lat'",
"]",
",",
"lon",
"=",
"json",
"[",
"'lon'",
"]",
",",
"time",
"=",
"isostr_to_datetime",
"(",
"json",
"[",
"'time'",
"]",
")",
")"
] | Creates Point instance from JSON representation
Args:
json (:obj:`dict`): Must have at least the following keys: lat (float), lon (float),
time (string in iso format). Example,
{
"lat": 9.3470298,
"lon": 3.79274,
... | [
"Creates",
"Point",
"instance",
"from",
"JSON",
"representation"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/point.py#L136-L155 |
ruipgil/TrackToTrip | tracktotrip/location.py | compute_centroid | def compute_centroid(points):
""" Computes the centroid of set of points
Args:
points (:obj:`list` of :obj:`Point`)
Returns:
:obj:`Point`
"""
lats = [p[1] for p in points]
lons = [p[0] for p in points]
return Point(np.mean(lats), np.mean(lons), None) | python | def compute_centroid(points):
""" Computes the centroid of set of points
Args:
points (:obj:`list` of :obj:`Point`)
Returns:
:obj:`Point`
"""
lats = [p[1] for p in points]
lons = [p[0] for p in points]
return Point(np.mean(lats), np.mean(lons), None) | [
"def",
"compute_centroid",
"(",
"points",
")",
":",
"lats",
"=",
"[",
"p",
"[",
"1",
"]",
"for",
"p",
"in",
"points",
"]",
"lons",
"=",
"[",
"p",
"[",
"0",
"]",
"for",
"p",
"in",
"points",
"]",
"return",
"Point",
"(",
"np",
".",
"mean",
"(",
... | Computes the centroid of set of points
Args:
points (:obj:`list` of :obj:`Point`)
Returns:
:obj:`Point` | [
"Computes",
"the",
"centroid",
"of",
"set",
"of",
"points"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/location.py#L37-L47 |
ruipgil/TrackToTrip | tracktotrip/location.py | update_location_centroid | def update_location_centroid(point, cluster, max_distance, min_samples):
""" Updates the centroid of a location cluster with another point
Args:
point (:obj:`Point`): Point to add to the cluster
cluster (:obj:`list` of :obj:`Point`): Location cluster
max_distance (float): Max neighbour ... | python | def update_location_centroid(point, cluster, max_distance, min_samples):
""" Updates the centroid of a location cluster with another point
Args:
point (:obj:`Point`): Point to add to the cluster
cluster (:obj:`list` of :obj:`Point`): Location cluster
max_distance (float): Max neighbour ... | [
"def",
"update_location_centroid",
"(",
"point",
",",
"cluster",
",",
"max_distance",
",",
"min_samples",
")",
":",
"cluster",
".",
"append",
"(",
"point",
")",
"points",
"=",
"[",
"p",
".",
"gen2arr",
"(",
")",
"for",
"p",
"in",
"cluster",
"]",
"# Estim... | Updates the centroid of a location cluster with another point
Args:
point (:obj:`Point`): Point to add to the cluster
cluster (:obj:`list` of :obj:`Point`): Location cluster
max_distance (float): Max neighbour distance
min_samples (int): Minimum number of samples
Returns:
... | [
"Updates",
"the",
"centroid",
"of",
"a",
"location",
"cluster",
"with",
"another",
"point"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/location.py#L49-L92 |
ruipgil/TrackToTrip | tracktotrip/location.py | query_foursquare | def query_foursquare(point, max_distance, client_id, client_secret):
""" Queries Squarespace API for a location
Args:
point (:obj:`Point`): Point location to query
max_distance (float): Search radius, in meters
client_id (str): Valid Foursquare client id
client_secret (str): Val... | python | def query_foursquare(point, max_distance, client_id, client_secret):
""" Queries Squarespace API for a location
Args:
point (:obj:`Point`): Point location to query
max_distance (float): Search radius, in meters
client_id (str): Valid Foursquare client id
client_secret (str): Val... | [
"def",
"query_foursquare",
"(",
"point",
",",
"max_distance",
",",
"client_id",
",",
"client_secret",
")",
":",
"if",
"not",
"client_id",
":",
"return",
"[",
"]",
"if",
"not",
"client_secret",
":",
"return",
"[",
"]",
"if",
"from_cache",
"(",
"FS_CACHE",
"... | Queries Squarespace API for a location
Args:
point (:obj:`Point`): Point location to query
max_distance (float): Search radius, in meters
client_id (str): Valid Foursquare client id
client_secret (str): Valid Foursquare client secret
Returns:
:obj:`list` of :obj:`dict`: ... | [
"Queries",
"Squarespace",
"API",
"for",
"a",
"location"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/location.py#L94-L142 |
ruipgil/TrackToTrip | tracktotrip/location.py | query_google | def query_google(point, max_distance, key):
""" Queries google maps API for a location
Args:
point (:obj:`Point`): Point location to query
max_distance (float): Search radius, in meters
key (str): Valid google maps api key
Returns:
:obj:`list` of :obj:`dict`: List of locatio... | python | def query_google(point, max_distance, key):
""" Queries google maps API for a location
Args:
point (:obj:`Point`): Point location to query
max_distance (float): Search radius, in meters
key (str): Valid google maps api key
Returns:
:obj:`list` of :obj:`dict`: List of locatio... | [
"def",
"query_google",
"(",
"point",
",",
"max_distance",
",",
"key",
")",
":",
"if",
"not",
"key",
":",
"return",
"[",
"]",
"if",
"from_cache",
"(",
"GG_CACHE",
",",
"point",
",",
"max_distance",
")",
":",
"return",
"from_cache",
"(",
"GG_CACHE",
",",
... | Queries google maps API for a location
Args:
point (:obj:`Point`): Point location to query
max_distance (float): Search radius, in meters
key (str): Valid google maps api key
Returns:
:obj:`list` of :obj:`dict`: List of locations with the following format:
{
... | [
"Queries",
"google",
"maps",
"API",
"for",
"a",
"location"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/location.py#L145-L189 |
ruipgil/TrackToTrip | tracktotrip/location.py | infer_location | def infer_location(
point,
location_query,
max_distance,
google_key,
foursquare_client_id,
foursquare_client_secret,
limit
):
""" Infers the semantic location of a (point) place.
Args:
points (:obj:`Point`): Point location to infer
loc... | python | def infer_location(
point,
location_query,
max_distance,
google_key,
foursquare_client_id,
foursquare_client_secret,
limit
):
""" Infers the semantic location of a (point) place.
Args:
points (:obj:`Point`): Point location to infer
loc... | [
"def",
"infer_location",
"(",
"point",
",",
"location_query",
",",
"max_distance",
",",
"google_key",
",",
"foursquare_client_id",
",",
"foursquare_client_secret",
",",
"limit",
")",
":",
"locations",
"=",
"[",
"]",
"if",
"location_query",
"is",
"not",
"None",
"... | Infers the semantic location of a (point) place.
Args:
points (:obj:`Point`): Point location to infer
location_query: Function with signature, (:obj:`Point`, int) -> (str, :obj:`Point`, ...)
max_distance (float): Max distance to a position, in meters
google_key (str): Valid google m... | [
"Infers",
"the",
"semantic",
"location",
"of",
"a",
"(",
"point",
")",
"place",
"."
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/location.py#L191-L245 |
ruipgil/TrackToTrip | tracktotrip/utils.py | estimate_meters_to_deg | def estimate_meters_to_deg(meters, precision=PRECISION_PERSON):
""" Meters to degrees estimation
See https://en.wikipedia.org/wiki/Decimal_degrees
Args:
meters (float)
precision (float)
Returns:
float: meters in degrees approximation
"""
line = PRECISION_TABLE[precision... | python | def estimate_meters_to_deg(meters, precision=PRECISION_PERSON):
""" Meters to degrees estimation
See https://en.wikipedia.org/wiki/Decimal_degrees
Args:
meters (float)
precision (float)
Returns:
float: meters in degrees approximation
"""
line = PRECISION_TABLE[precision... | [
"def",
"estimate_meters_to_deg",
"(",
"meters",
",",
"precision",
"=",
"PRECISION_PERSON",
")",
":",
"line",
"=",
"PRECISION_TABLE",
"[",
"precision",
"]",
"dec",
"=",
"1",
"/",
"float",
"(",
"10",
"**",
"precision",
")",
"return",
"meters",
"/",
"line",
"... | Meters to degrees estimation
See https://en.wikipedia.org/wiki/Decimal_degrees
Args:
meters (float)
precision (float)
Returns:
float: meters in degrees approximation | [
"Meters",
"to",
"degrees",
"estimation"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/utils.py#L21-L34 |
ruipgil/TrackToTrip | tracktotrip/utils.py | isostr_to_datetime | def isostr_to_datetime(dt_str):
""" Converts iso formated text string into a datetime object
Args:
dt_str (str): ISO formated text string
Returns:
:obj:`datetime.datetime`
"""
if len(dt_str) <= 20:
return datetime.datetime.strptime(dt_str, "%Y-%m-%dT%H:%M:%SZ")
else:
... | python | def isostr_to_datetime(dt_str):
""" Converts iso formated text string into a datetime object
Args:
dt_str (str): ISO formated text string
Returns:
:obj:`datetime.datetime`
"""
if len(dt_str) <= 20:
return datetime.datetime.strptime(dt_str, "%Y-%m-%dT%H:%M:%SZ")
else:
... | [
"def",
"isostr_to_datetime",
"(",
"dt_str",
")",
":",
"if",
"len",
"(",
"dt_str",
")",
"<=",
"20",
":",
"return",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"dt_str",
",",
"\"%Y-%m-%dT%H:%M:%SZ\"",
")",
"else",
":",
"dt_str",
"=",
"dt_str",
".",
... | Converts iso formated text string into a datetime object
Args:
dt_str (str): ISO formated text string
Returns:
:obj:`datetime.datetime` | [
"Converts",
"iso",
"formated",
"text",
"string",
"into",
"a",
"datetime",
"object"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/utils.py#L36-L48 |
ruipgil/TrackToTrip | tracktotrip/utils.py | pairwise | def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
now, nxt = tee(iterable)
next(nxt, None)
return izip(now, nxt) | python | def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
now, nxt = tee(iterable)
next(nxt, None)
return izip(now, nxt) | [
"def",
"pairwise",
"(",
"iterable",
")",
":",
"now",
",",
"nxt",
"=",
"tee",
"(",
"iterable",
")",
"next",
"(",
"nxt",
",",
"None",
")",
"return",
"izip",
"(",
"now",
",",
"nxt",
")"
] | s -> (s0,s1), (s1,s2), (s2, s3), ... | [
"s",
"-",
">",
"(",
"s0",
"s1",
")",
"(",
"s1",
"s2",
")",
"(",
"s2",
"s3",
")",
"..."
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/utils.py#L50-L54 |
ruipgil/TrackToTrip | tracktotrip/classifier.py | Classifier.__learn_labels | def __learn_labels(self, labels):
""" Learns new labels, this method is intended for internal use
Args:
labels (:obj:`list` of :obj:`str`): Labels to learn
"""
if self.feature_length > 0:
result = list(self.labels.classes_)
else:
result = []
... | python | def __learn_labels(self, labels):
""" Learns new labels, this method is intended for internal use
Args:
labels (:obj:`list` of :obj:`str`): Labels to learn
"""
if self.feature_length > 0:
result = list(self.labels.classes_)
else:
result = []
... | [
"def",
"__learn_labels",
"(",
"self",
",",
"labels",
")",
":",
"if",
"self",
".",
"feature_length",
">",
"0",
":",
"result",
"=",
"list",
"(",
"self",
".",
"labels",
".",
"classes_",
")",
"else",
":",
"result",
"=",
"[",
"]",
"for",
"label",
"in",
... | Learns new labels, this method is intended for internal use
Args:
labels (:obj:`list` of :obj:`str`): Labels to learn | [
"Learns",
"new",
"labels",
"this",
"method",
"is",
"intended",
"for",
"internal",
"use"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/classifier.py#L28-L41 |
ruipgil/TrackToTrip | tracktotrip/classifier.py | Classifier.learn | def learn(self, features, labels):
""" Fits the classifier
If it's state is empty, the classifier is fitted, if not
the classifier is partially fitted.
See sklearn's SGDClassifier fit and partial_fit methods.
Args:
features (:obj:`list` of :obj:`list` of :obj:`float... | python | def learn(self, features, labels):
""" Fits the classifier
If it's state is empty, the classifier is fitted, if not
the classifier is partially fitted.
See sklearn's SGDClassifier fit and partial_fit methods.
Args:
features (:obj:`list` of :obj:`list` of :obj:`float... | [
"def",
"learn",
"(",
"self",
",",
"features",
",",
"labels",
")",
":",
"labels",
"=",
"np",
".",
"ravel",
"(",
"labels",
")",
"self",
".",
"__learn_labels",
"(",
"labels",
")",
"if",
"len",
"(",
"labels",
")",
"==",
"0",
":",
"return",
"labels",
"=... | Fits the classifier
If it's state is empty, the classifier is fitted, if not
the classifier is partially fitted.
See sklearn's SGDClassifier fit and partial_fit methods.
Args:
features (:obj:`list` of :obj:`list` of :obj:`float`)
labels (:obj:`list` of :obj:`str... | [
"Fits",
"the",
"classifier"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/classifier.py#L43-L66 |
ruipgil/TrackToTrip | tracktotrip/classifier.py | Classifier.predict | def predict(self, features, verbose=False):
""" Probability estimates of each feature
See sklearn's SGDClassifier predict and predict_proba methods.
Args:
features (:obj:`list` of :obj:`list` of :obj:`float`)
verbose: Boolean, optional. If true returns an array where ea... | python | def predict(self, features, verbose=False):
""" Probability estimates of each feature
See sklearn's SGDClassifier predict and predict_proba methods.
Args:
features (:obj:`list` of :obj:`list` of :obj:`float`)
verbose: Boolean, optional. If true returns an array where ea... | [
"def",
"predict",
"(",
"self",
",",
"features",
",",
"verbose",
"=",
"False",
")",
":",
"probs",
"=",
"self",
".",
"clf",
".",
"predict_proba",
"(",
"features",
")",
"if",
"verbose",
":",
"labels",
"=",
"self",
".",
"labels",
".",
"classes_",
"res",
... | Probability estimates of each feature
See sklearn's SGDClassifier predict and predict_proba methods.
Args:
features (:obj:`list` of :obj:`list` of :obj:`float`)
verbose: Boolean, optional. If true returns an array where each
element is a dictionary, where keys a... | [
"Probability",
"estimates",
"of",
"each",
"feature"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/classifier.py#L72-L98 |
the-tale/pynames | pynames/utils.py | is_file | def is_file(obj):
"""Retrun True is object has 'next', '__enter__' and '__exit__' methods.
Suitable to check both builtin ``file`` and ``django.core.file.File`` instances.
"""
return all(
[callable(getattr(obj, method_name, None)) for method_name in ('__enter__', '__exit__')]
+
... | python | def is_file(obj):
"""Retrun True is object has 'next', '__enter__' and '__exit__' methods.
Suitable to check both builtin ``file`` and ``django.core.file.File`` instances.
"""
return all(
[callable(getattr(obj, method_name, None)) for method_name in ('__enter__', '__exit__')]
+
... | [
"def",
"is_file",
"(",
"obj",
")",
":",
"return",
"all",
"(",
"[",
"callable",
"(",
"getattr",
"(",
"obj",
",",
"method_name",
",",
"None",
")",
")",
"for",
"method_name",
"in",
"(",
"'__enter__'",
",",
"'__exit__'",
")",
"]",
"+",
"[",
"any",
"(",
... | Retrun True is object has 'next', '__enter__' and '__exit__' methods.
Suitable to check both builtin ``file`` and ``django.core.file.File`` instances. | [
"Retrun",
"True",
"is",
"object",
"has",
"next",
"__enter__",
"and",
"__exit__",
"methods",
"."
] | train | https://github.com/the-tale/pynames/blob/da45eaaac3166847bcb2c48cab4571a462660ace/pynames/utils.py#L40-L50 |
the-tale/pynames | pynames/utils.py | file_adapter | def file_adapter(file_or_path):
"""Context manager that works similar to ``open(file_path)``but also accepts already openned file-like objects."""
if is_file(file_or_path):
file_obj = file_or_path
else:
file_obj = open(file_or_path, 'rb')
yield file_obj
file_obj.close() | python | def file_adapter(file_or_path):
"""Context manager that works similar to ``open(file_path)``but also accepts already openned file-like objects."""
if is_file(file_or_path):
file_obj = file_or_path
else:
file_obj = open(file_or_path, 'rb')
yield file_obj
file_obj.close() | [
"def",
"file_adapter",
"(",
"file_or_path",
")",
":",
"if",
"is_file",
"(",
"file_or_path",
")",
":",
"file_obj",
"=",
"file_or_path",
"else",
":",
"file_obj",
"=",
"open",
"(",
"file_or_path",
",",
"'rb'",
")",
"yield",
"file_obj",
"file_obj",
".",
"close",... | Context manager that works similar to ``open(file_path)``but also accepts already openned file-like objects. | [
"Context",
"manager",
"that",
"works",
"similar",
"to",
"open",
"(",
"file_path",
")",
"but",
"also",
"accepts",
"already",
"openned",
"file",
"-",
"like",
"objects",
"."
] | train | https://github.com/the-tale/pynames/blob/da45eaaac3166847bcb2c48cab4571a462660ace/pynames/utils.py#L54-L61 |
the-tale/pynames | pynames/from_tables_generator.py | FromCSVTablesGenerator.source_loader | def source_loader(self, source_paths, create_missing_tables=True):
"""Load source from 3 csv files.
First file should contain global settings:
* ``native_lagnauge,languages`` header on first row
* appropriate values on following rows
Example::
native_lagnauge,lang... | python | def source_loader(self, source_paths, create_missing_tables=True):
"""Load source from 3 csv files.
First file should contain global settings:
* ``native_lagnauge,languages`` header on first row
* appropriate values on following rows
Example::
native_lagnauge,lang... | [
"def",
"source_loader",
"(",
"self",
",",
"source_paths",
",",
"create_missing_tables",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"source_paths",
",",
"Iterable",
")",
"or",
"len",
"(",
"source_paths",
")",
"<",
"3",
":",
"raise",
"TypeError",
... | Load source from 3 csv files.
First file should contain global settings:
* ``native_lagnauge,languages`` header on first row
* appropriate values on following rows
Example::
native_lagnauge,languages
ru,ru
,en
Second file should contain ... | [
"Load",
"source",
"from",
"3",
"csv",
"files",
"."
] | train | https://github.com/the-tale/pynames/blob/da45eaaac3166847bcb2c48cab4571a462660ace/pynames/from_tables_generator.py#L179-L238 |
rtlee9/serveit | examples/pytorch_imagenet_resnet50.py | loader | def loader():
"""Load image from URL, and preprocess for Resnet."""
url = request.args.get('url') # read image URL as a request URL param
response = requests.get(url) # make request to static image file
return response.content | python | def loader():
"""Load image from URL, and preprocess for Resnet."""
url = request.args.get('url') # read image URL as a request URL param
response = requests.get(url) # make request to static image file
return response.content | [
"def",
"loader",
"(",
")",
":",
"url",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'url'",
")",
"# read image URL as a request URL param",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"# make request to static image file",
"return",
"response",
"... | Load image from URL, and preprocess for Resnet. | [
"Load",
"image",
"from",
"URL",
"and",
"preprocess",
"for",
"Resnet",
"."
] | train | https://github.com/rtlee9/serveit/blob/d97b5fbe56bec78d6c0193d6fd2ea2a0c1cbafdc/examples/pytorch_imagenet_resnet50.py#L32-L36 |
rtlee9/serveit | examples/pytorch_imagenet_resnet50.py | postprocessor | def postprocessor(prediction):
"""Map prediction tensor to labels."""
prediction = prediction.data.numpy()[0]
top_predictions = prediction.argsort()[-3:][::-1]
return [labels[prediction] for prediction in top_predictions] | python | def postprocessor(prediction):
"""Map prediction tensor to labels."""
prediction = prediction.data.numpy()[0]
top_predictions = prediction.argsort()[-3:][::-1]
return [labels[prediction] for prediction in top_predictions] | [
"def",
"postprocessor",
"(",
"prediction",
")",
":",
"prediction",
"=",
"prediction",
".",
"data",
".",
"numpy",
"(",
")",
"[",
"0",
"]",
"top_predictions",
"=",
"prediction",
".",
"argsort",
"(",
")",
"[",
"-",
"3",
":",
"]",
"[",
":",
":",
"-",
"... | Map prediction tensor to labels. | [
"Map",
"prediction",
"tensor",
"to",
"labels",
"."
] | train | https://github.com/rtlee9/serveit/blob/d97b5fbe56bec78d6c0193d6fd2ea2a0c1cbafdc/examples/pytorch_imagenet_resnet50.py#L48-L52 |
rtlee9/serveit | serveit/log_utils.py | get_logger | def get_logger(name):
"""Get a logger with the specified name."""
logger = logging.getLogger(name)
logger.setLevel(getenv('LOGLEVEL', 'INFO'))
return logger | python | def get_logger(name):
"""Get a logger with the specified name."""
logger = logging.getLogger(name)
logger.setLevel(getenv('LOGLEVEL', 'INFO'))
return logger | [
"def",
"get_logger",
"(",
"name",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"name",
")",
"logger",
".",
"setLevel",
"(",
"getenv",
"(",
"'LOGLEVEL'",
",",
"'INFO'",
")",
")",
"return",
"logger"
] | Get a logger with the specified name. | [
"Get",
"a",
"logger",
"with",
"the",
"specified",
"name",
"."
] | train | https://github.com/rtlee9/serveit/blob/d97b5fbe56bec78d6c0193d6fd2ea2a0c1cbafdc/serveit/log_utils.py#L8-L12 |
rtlee9/serveit | serveit/utils.py | make_serializable | def make_serializable(data):
"""Ensure data is serializable."""
if is_serializable(data):
return data
# if numpy array convert to list
try:
return data.tolist()
except AttributeError:
pass
except Exception as e:
logger.debug('{} exception ({}): {}'.format(type(e)... | python | def make_serializable(data):
"""Ensure data is serializable."""
if is_serializable(data):
return data
# if numpy array convert to list
try:
return data.tolist()
except AttributeError:
pass
except Exception as e:
logger.debug('{} exception ({}): {}'.format(type(e)... | [
"def",
"make_serializable",
"(",
"data",
")",
":",
"if",
"is_serializable",
"(",
"data",
")",
":",
"return",
"data",
"# if numpy array convert to list",
"try",
":",
"return",
"data",
".",
"tolist",
"(",
")",
"except",
"AttributeError",
":",
"pass",
"except",
"... | Ensure data is serializable. | [
"Ensure",
"data",
"is",
"serializable",
"."
] | train | https://github.com/rtlee9/serveit/blob/d97b5fbe56bec78d6c0193d6fd2ea2a0c1cbafdc/serveit/utils.py#L10-L34 |
rtlee9/serveit | serveit/utils.py | json_numpy_loader | def json_numpy_loader():
"""Load data from JSON request and convert to numpy array."""
data = request.get_json()
logger.debug('Received JSON data of length {:,}'.format(len(data)))
return data | python | def json_numpy_loader():
"""Load data from JSON request and convert to numpy array."""
data = request.get_json()
logger.debug('Received JSON data of length {:,}'.format(len(data)))
return data | [
"def",
"json_numpy_loader",
"(",
")",
":",
"data",
"=",
"request",
".",
"get_json",
"(",
")",
"logger",
".",
"debug",
"(",
"'Received JSON data of length {:,}'",
".",
"format",
"(",
"len",
"(",
"data",
")",
")",
")",
"return",
"data"
] | Load data from JSON request and convert to numpy array. | [
"Load",
"data",
"from",
"JSON",
"request",
"and",
"convert",
"to",
"numpy",
"array",
"."
] | train | https://github.com/rtlee9/serveit/blob/d97b5fbe56bec78d6c0193d6fd2ea2a0c1cbafdc/serveit/utils.py#L46-L50 |
rtlee9/serveit | serveit/utils.py | get_bytes_to_image_callback | def get_bytes_to_image_callback(image_dims=(224, 224)):
"""Return a callback to process image bytes for ImageNet."""
from keras.preprocessing import image
import numpy as np
from PIL import Image
from io import BytesIO
def preprocess_image_bytes(data_bytes):
"""Process image bytes for I... | python | def get_bytes_to_image_callback(image_dims=(224, 224)):
"""Return a callback to process image bytes for ImageNet."""
from keras.preprocessing import image
import numpy as np
from PIL import Image
from io import BytesIO
def preprocess_image_bytes(data_bytes):
"""Process image bytes for I... | [
"def",
"get_bytes_to_image_callback",
"(",
"image_dims",
"=",
"(",
"224",
",",
"224",
")",
")",
":",
"from",
"keras",
".",
"preprocessing",
"import",
"image",
"import",
"numpy",
"as",
"np",
"from",
"PIL",
"import",
"Image",
"from",
"io",
"import",
"BytesIO",... | Return a callback to process image bytes for ImageNet. | [
"Return",
"a",
"callback",
"to",
"process",
"image",
"bytes",
"for",
"ImageNet",
"."
] | train | https://github.com/rtlee9/serveit/blob/d97b5fbe56bec78d6c0193d6fd2ea2a0c1cbafdc/serveit/utils.py#L53-L70 |
rtlee9/serveit | serveit/server.py | exception_log_and_respond | def exception_log_and_respond(exception, logger, message, status_code):
"""Log an error and send jsonified respond."""
logger.error(message, exc_info=True)
return make_response(
message,
status_code,
dict(exception_type=type(exception).__name__, exception_message=str(exception)),
... | python | def exception_log_and_respond(exception, logger, message, status_code):
"""Log an error and send jsonified respond."""
logger.error(message, exc_info=True)
return make_response(
message,
status_code,
dict(exception_type=type(exception).__name__, exception_message=str(exception)),
... | [
"def",
"exception_log_and_respond",
"(",
"exception",
",",
"logger",
",",
"message",
",",
"status_code",
")",
":",
"logger",
".",
"error",
"(",
"message",
",",
"exc_info",
"=",
"True",
")",
"return",
"make_response",
"(",
"message",
",",
"status_code",
",",
... | Log an error and send jsonified respond. | [
"Log",
"an",
"error",
"and",
"send",
"jsonified",
"respond",
"."
] | train | https://github.com/rtlee9/serveit/blob/d97b5fbe56bec78d6c0193d6fd2ea2a0c1cbafdc/serveit/server.py#L12-L19 |
rtlee9/serveit | serveit/server.py | make_response | def make_response(message, status_code, details=None):
"""Make a jsonified response with specified message and status code."""
response_body = dict(message=message)
if details:
response_body['details'] = details
response = jsonify(response_body)
response.status_code = status_code
return ... | python | def make_response(message, status_code, details=None):
"""Make a jsonified response with specified message and status code."""
response_body = dict(message=message)
if details:
response_body['details'] = details
response = jsonify(response_body)
response.status_code = status_code
return ... | [
"def",
"make_response",
"(",
"message",
",",
"status_code",
",",
"details",
"=",
"None",
")",
":",
"response_body",
"=",
"dict",
"(",
"message",
"=",
"message",
")",
"if",
"details",
":",
"response_body",
"[",
"'details'",
"]",
"=",
"details",
"response",
... | Make a jsonified response with specified message and status code. | [
"Make",
"a",
"jsonified",
"response",
"with",
"specified",
"message",
"and",
"status",
"code",
"."
] | train | https://github.com/rtlee9/serveit/blob/d97b5fbe56bec78d6c0193d6fd2ea2a0c1cbafdc/serveit/server.py#L22-L29 |
rtlee9/serveit | serveit/server.py | ModelServer._create_prediction_endpoint | def _create_prediction_endpoint(
self,
to_numpy=True,
data_loader=json_numpy_loader,
preprocessor=lambda x: x,
input_validation=lambda data: (True, None),
postprocessor=lambda x: x,
make_serializable_post=True):
"""Create an end... | python | def _create_prediction_endpoint(
self,
to_numpy=True,
data_loader=json_numpy_loader,
preprocessor=lambda x: x,
input_validation=lambda data: (True, None),
postprocessor=lambda x: x,
make_serializable_post=True):
"""Create an end... | [
"def",
"_create_prediction_endpoint",
"(",
"self",
",",
"to_numpy",
"=",
"True",
",",
"data_loader",
"=",
"json_numpy_loader",
",",
"preprocessor",
"=",
"lambda",
"x",
":",
"x",
",",
"input_validation",
"=",
"lambda",
"data",
":",
"(",
"True",
",",
"None",
"... | Create an endpoint to serve predictions.
Arguments:
- input_validation (fn): takes a numpy array as input;
returns True if validation passes and False otherwise
- data_loader (fn): reads flask request and returns data preprocessed to be
used in the `predi... | [
"Create",
"an",
"endpoint",
"to",
"serve",
"predictions",
"."
] | train | https://github.com/rtlee9/serveit/blob/d97b5fbe56bec78d6c0193d6fd2ea2a0c1cbafdc/serveit/server.py#L77-L152 |
rtlee9/serveit | serveit/server.py | ModelServer.create_info_endpoint | def create_info_endpoint(self, name, data):
"""Create an endpoint to serve info GET requests."""
# make sure data is serializable
data = make_serializable(data)
# create generic restful resource to serve static JSON data
class InfoBase(Resource):
@staticmethod
... | python | def create_info_endpoint(self, name, data):
"""Create an endpoint to serve info GET requests."""
# make sure data is serializable
data = make_serializable(data)
# create generic restful resource to serve static JSON data
class InfoBase(Resource):
@staticmethod
... | [
"def",
"create_info_endpoint",
"(",
"self",
",",
"name",
",",
"data",
")",
":",
"# make sure data is serializable",
"data",
"=",
"make_serializable",
"(",
"data",
")",
"# create generic restful resource to serve static JSON data",
"class",
"InfoBase",
"(",
"Resource",
")"... | Create an endpoint to serve info GET requests. | [
"Create",
"an",
"endpoint",
"to",
"serve",
"info",
"GET",
"requests",
"."
] | train | https://github.com/rtlee9/serveit/blob/d97b5fbe56bec78d6c0193d6fd2ea2a0c1cbafdc/serveit/server.py#L154-L175 |
rtlee9/serveit | serveit/server.py | ModelServer._create_model_info_endpoint | def _create_model_info_endpoint(self, path='/info/model'):
"""Create an endpoint to serve info GET requests."""
model = self.model
# parse model details
model_details = {}
for key, value in model.__dict__.items():
model_details[key] = make_serializable(value)
... | python | def _create_model_info_endpoint(self, path='/info/model'):
"""Create an endpoint to serve info GET requests."""
model = self.model
# parse model details
model_details = {}
for key, value in model.__dict__.items():
model_details[key] = make_serializable(value)
... | [
"def",
"_create_model_info_endpoint",
"(",
"self",
",",
"path",
"=",
"'/info/model'",
")",
":",
"model",
"=",
"self",
".",
"model",
"# parse model details",
"model_details",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"model",
".",
"__dict__",
".",
"ite... | Create an endpoint to serve info GET requests. | [
"Create",
"an",
"endpoint",
"to",
"serve",
"info",
"GET",
"requests",
"."
] | train | https://github.com/rtlee9/serveit/blob/d97b5fbe56bec78d6c0193d6fd2ea2a0c1cbafdc/serveit/server.py#L177-L194 |
rtlee9/serveit | serveit/server.py | ModelServer.serve | def serve(self, host='127.0.0.1', port=5000):
"""Serve predictions as an API endpoint."""
from meinheld import server, middleware
# self.app.run(host=host, port=port)
server.listen((host, port))
server.run(middleware.WebSocketMiddleware(self.app)) | python | def serve(self, host='127.0.0.1', port=5000):
"""Serve predictions as an API endpoint."""
from meinheld import server, middleware
# self.app.run(host=host, port=port)
server.listen((host, port))
server.run(middleware.WebSocketMiddleware(self.app)) | [
"def",
"serve",
"(",
"self",
",",
"host",
"=",
"'127.0.0.1'",
",",
"port",
"=",
"5000",
")",
":",
"from",
"meinheld",
"import",
"server",
",",
"middleware",
"# self.app.run(host=host, port=port)",
"server",
".",
"listen",
"(",
"(",
"host",
",",
"port",
")",
... | Serve predictions as an API endpoint. | [
"Serve",
"predictions",
"as",
"an",
"API",
"endpoint",
"."
] | train | https://github.com/rtlee9/serveit/blob/d97b5fbe56bec78d6c0193d6fd2ea2a0c1cbafdc/serveit/server.py#L196-L201 |
rtlee9/serveit | examples/keras_boston_neural_net.py | get_model | def get_model(input_dim):
"""Create and compile simple model."""
model = Sequential()
model.add(Dense(100, input_dim=input_dim, activation='sigmoid'))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='SGD')
return model | python | def get_model(input_dim):
"""Create and compile simple model."""
model = Sequential()
model.add(Dense(100, input_dim=input_dim, activation='sigmoid'))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='SGD')
return model | [
"def",
"get_model",
"(",
"input_dim",
")",
":",
"model",
"=",
"Sequential",
"(",
")",
"model",
".",
"add",
"(",
"Dense",
"(",
"100",
",",
"input_dim",
"=",
"input_dim",
",",
"activation",
"=",
"'sigmoid'",
")",
")",
"model",
".",
"add",
"(",
"Dense",
... | Create and compile simple model. | [
"Create",
"and",
"compile",
"simple",
"model",
"."
] | train | https://github.com/rtlee9/serveit/blob/d97b5fbe56bec78d6c0193d6fd2ea2a0c1cbafdc/examples/keras_boston_neural_net.py#L8-L14 |
rtlee9/serveit | examples/keras_boston_neural_net.py | validator | def validator(input_data):
"""Simple model input validator.
Validator ensures the input data array is
- two dimensional
- has the correct number of features.
"""
global data
# check num dims
if input_data.ndim != 2:
return False, 'Data should have two dimensions.'
# ... | python | def validator(input_data):
"""Simple model input validator.
Validator ensures the input data array is
- two dimensional
- has the correct number of features.
"""
global data
# check num dims
if input_data.ndim != 2:
return False, 'Data should have two dimensions.'
# ... | [
"def",
"validator",
"(",
"input_data",
")",
":",
"global",
"data",
"# check num dims",
"if",
"input_data",
".",
"ndim",
"!=",
"2",
":",
"return",
"False",
",",
"'Data should have two dimensions.'",
"# check number of columns",
"if",
"input_data",
".",
"shape",
"[",
... | Simple model input validator.
Validator ensures the input data array is
- two dimensional
- has the correct number of features. | [
"Simple",
"model",
"input",
"validator",
"."
] | train | https://github.com/rtlee9/serveit/blob/d97b5fbe56bec78d6c0193d6fd2ea2a0c1cbafdc/examples/keras_boston_neural_net.py#L22-L39 |
OTTOMATIC-IO/pycine | pycine/file.py | read_chd_header | def read_chd_header(chd_file):
"""
read the .chd header file created when Vision Research software saves the images in a file format other than .cine
"""
with open(chd_file, "rb") as f:
header = {
"cinefileheader": cine.CINEFILEHEADER(),
"bitmapinfoheader": cine.BITMAPIN... | python | def read_chd_header(chd_file):
"""
read the .chd header file created when Vision Research software saves the images in a file format other than .cine
"""
with open(chd_file, "rb") as f:
header = {
"cinefileheader": cine.CINEFILEHEADER(),
"bitmapinfoheader": cine.BITMAPIN... | [
"def",
"read_chd_header",
"(",
"chd_file",
")",
":",
"with",
"open",
"(",
"chd_file",
",",
"\"rb\"",
")",
"as",
"f",
":",
"header",
"=",
"{",
"\"cinefileheader\"",
":",
"cine",
".",
"CINEFILEHEADER",
"(",
")",
",",
"\"bitmapinfoheader\"",
":",
"cine",
".",... | read the .chd header file created when Vision Research software saves the images in a file format other than .cine | [
"read",
"the",
".",
"chd",
"header",
"file",
"created",
"when",
"Vision",
"Research",
"software",
"saves",
"the",
"images",
"in",
"a",
"file",
"format",
"other",
"than",
".",
"cine"
] | train | https://github.com/OTTOMATIC-IO/pycine/blob/8cc27b762796456e36fffe42df940f232e402974/pycine/file.py#L31-L46 |
jackmaney/python-stdlib-list | stdlib_list/fetch.py | fetch_list | def fetch_list(version=None):
"""
For the given version of Python (or all versions if no version is set), this function:
- Uses the `fetch_inventory` function of :py:mod`sphinx.ext.intersphinx` to
grab and parse the Sphinx object inventory
(ie ``http://docs.python.org/<version>/objects.inv``) for t... | python | def fetch_list(version=None):
"""
For the given version of Python (or all versions if no version is set), this function:
- Uses the `fetch_inventory` function of :py:mod`sphinx.ext.intersphinx` to
grab and parse the Sphinx object inventory
(ie ``http://docs.python.org/<version>/objects.inv``) for t... | [
"def",
"fetch_list",
"(",
"version",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"versions",
"=",
"short_versions",
"else",
":",
"versions",
"=",
"[",
"get_canonical_version",
"(",
"version",
")",
"]",
"for",
"version",
"in",
"versions",
":"... | For the given version of Python (or all versions if no version is set), this function:
- Uses the `fetch_inventory` function of :py:mod`sphinx.ext.intersphinx` to
grab and parse the Sphinx object inventory
(ie ``http://docs.python.org/<version>/objects.inv``) for the given version.
- Grabs the names o... | [
"For",
"the",
"given",
"version",
"of",
"Python",
"(",
"or",
"all",
"versions",
"if",
"no",
"version",
"is",
"set",
")",
"this",
"function",
":"
] | train | https://github.com/jackmaney/python-stdlib-list/blob/f343504405435fcc4bc49bc064f70006813f6845/stdlib_list/fetch.py#L34-L71 |
jackmaney/python-stdlib-list | stdlib_list/base.py | stdlib_list | def stdlib_list(version=None):
"""
Given a ``version``, return a ``list`` of names of the Python Standard
Libraries for that version. These names are obtained from the Sphinx inventory
file (used in :py:mod:`sphinx.ext.intersphinx`).
:param str|None version: The version (as a string) whose list of ... | python | def stdlib_list(version=None):
"""
Given a ``version``, return a ``list`` of names of the Python Standard
Libraries for that version. These names are obtained from the Sphinx inventory
file (used in :py:mod:`sphinx.ext.intersphinx`).
:param str|None version: The version (as a string) whose list of ... | [
"def",
"stdlib_list",
"(",
"version",
"=",
"None",
")",
":",
"version",
"=",
"get_canonical_version",
"(",
"version",
")",
"if",
"version",
"is",
"not",
"None",
"else",
"'.'",
".",
"join",
"(",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"sys",
".",
"ver... | Given a ``version``, return a ``list`` of names of the Python Standard
Libraries for that version. These names are obtained from the Sphinx inventory
file (used in :py:mod:`sphinx.ext.intersphinx`).
:param str|None version: The version (as a string) whose list of libraries you want
(one of ``"2.6"``, `... | [
"Given",
"a",
"version",
"return",
"a",
"list",
"of",
"names",
"of",
"the",
"Python",
"Standard",
"Libraries",
"for",
"that",
"version",
".",
"These",
"names",
"are",
"obtained",
"from",
"the",
"Sphinx",
"inventory",
"file",
"(",
"used",
"in",
":",
"py",
... | train | https://github.com/jackmaney/python-stdlib-list/blob/f343504405435fcc4bc49bc064f70006813f6845/stdlib_list/base.py#L25-L47 |
OTTOMATIC-IO/pycine | pycine/color.py | color_pipeline | def color_pipeline(raw, setup, bpp=12):
"""Order from:
http://www.visionresearch.com/phantomzone/viewtopic.php?f=20&t=572#p3884
"""
# 1. Offset the raw image by the amount in flare
print("fFlare: ", setup.fFlare)
# 2. White balance the raw picture using the white balance component of cmatrix
... | python | def color_pipeline(raw, setup, bpp=12):
"""Order from:
http://www.visionresearch.com/phantomzone/viewtopic.php?f=20&t=572#p3884
"""
# 1. Offset the raw image by the amount in flare
print("fFlare: ", setup.fFlare)
# 2. White balance the raw picture using the white balance component of cmatrix
... | [
"def",
"color_pipeline",
"(",
"raw",
",",
"setup",
",",
"bpp",
"=",
"12",
")",
":",
"# 1. Offset the raw image by the amount in flare",
"print",
"(",
"\"fFlare: \"",
",",
"setup",
".",
"fFlare",
")",
"# 2. White balance the raw picture using the white balance component of c... | Order from:
http://www.visionresearch.com/phantomzone/viewtopic.php?f=20&t=572#p3884 | [
"Order",
"from",
":",
"http",
":",
"//",
"www",
".",
"visionresearch",
".",
"com",
"/",
"phantomzone",
"/",
"viewtopic",
".",
"php?f",
"=",
"20&t",
"=",
"572#p3884"
] | train | https://github.com/OTTOMATIC-IO/pycine/blob/8cc27b762796456e36fffe42df940f232e402974/pycine/color.py#L5-L99 |
smarie/python-autoclass | autoclass/autohash_.py | autohash | def autohash(include=None, # type: Union[str, Tuple[str]]
exclude=None, # type: Union[str, Tuple[str]]
only_constructor_args=False, # type: bool
only_public_fields=False, # type: bool
cls=DECORATED
):
"""
A decor... | python | def autohash(include=None, # type: Union[str, Tuple[str]]
exclude=None, # type: Union[str, Tuple[str]]
only_constructor_args=False, # type: bool
only_public_fields=False, # type: bool
cls=DECORATED
):
"""
A decor... | [
"def",
"autohash",
"(",
"include",
"=",
"None",
",",
"# type: Union[str, Tuple[str]]",
"exclude",
"=",
"None",
",",
"# type: Union[str, Tuple[str]]",
"only_constructor_args",
"=",
"False",
",",
"# type: bool",
"only_public_fields",
"=",
"False",
",",
"# type: bool",
"cl... | A decorator to makes objects of the class implement __hash__, so that they can be used correctly for example in
sets.
Parameters allow to customize the list of attributes that are taken into account in the hash.
:param include: a tuple of explicit attribute names to include (None means all)
:param... | [
"A",
"decorator",
"to",
"makes",
"objects",
"of",
"the",
"class",
"implement",
"__hash__",
"so",
"that",
"they",
"can",
"be",
"used",
"correctly",
"for",
"example",
"in",
"sets",
".",
"Parameters",
"allow",
"to",
"customize",
"the",
"list",
"of",
"attributes... | train | https://github.com/smarie/python-autoclass/blob/097098776c69ebc87bc1aeda6997431b29bd583a/autoclass/autohash_.py#L26-L51 |
smarie/python-autoclass | autoclass/autohash_.py | autohash_decorate | def autohash_decorate(cls, # type: Type[T]
include=None, # type: Union[str, Tuple[str]]
exclude=None, # type: Union[str, Tuple[str]]
only_constructor_args=False, # type: bool
... | python | def autohash_decorate(cls, # type: Type[T]
include=None, # type: Union[str, Tuple[str]]
exclude=None, # type: Union[str, Tuple[str]]
only_constructor_args=False, # type: bool
... | [
"def",
"autohash_decorate",
"(",
"cls",
",",
"# type: Type[T]",
"include",
"=",
"None",
",",
"# type: Union[str, Tuple[str]]",
"exclude",
"=",
"None",
",",
"# type: Union[str, Tuple[str]]",
"only_constructor_args",
"=",
"False",
",",
"# type: bool",
"only_public_fields",
... | To automatically generate the appropriate methods so that objects of this class are hashable,
manually, without using @autohash decorator.
:param cls: the class on which to execute. Note that it won't be wrapped.
:param include: a tuple of explicit attribute names to include (None means all)
:param exc... | [
"To",
"automatically",
"generate",
"the",
"appropriate",
"methods",
"so",
"that",
"objects",
"of",
"this",
"class",
"are",
"hashable",
"manually",
"without",
"using",
"@autohash",
"decorator",
"."
] | train | https://github.com/smarie/python-autoclass/blob/097098776c69ebc87bc1aeda6997431b29bd583a/autoclass/autohash_.py#L54-L85 |
smarie/python-autoclass | autoclass/autohash_.py | _execute_autohash_on_class | def _execute_autohash_on_class(object_type, # type: Type[T]
include=None, # type: Union[str, Tuple[str]]
exclude=None, # type: Union[str, Tuple[str]]
only_constructor_args=False,... | python | def _execute_autohash_on_class(object_type, # type: Type[T]
include=None, # type: Union[str, Tuple[str]]
exclude=None, # type: Union[str, Tuple[str]]
only_constructor_args=False,... | [
"def",
"_execute_autohash_on_class",
"(",
"object_type",
",",
"# type: Type[T]",
"include",
"=",
"None",
",",
"# type: Union[str, Tuple[str]]",
"exclude",
"=",
"None",
",",
"# type: Union[str, Tuple[str]]",
"only_constructor_args",
"=",
"False",
",",
"# type: bool",
"only_p... | A decorator to make objects of the class implement __hash__, so that they can be used correctly for example in
sets.
Parameters allow to customize the list of attributes that are taken into account in the hash.
:param object_type: the class on which to execute.
:param include: a tuple of explicit attr... | [
"A",
"decorator",
"to",
"make",
"objects",
"of",
"the",
"class",
"implement",
"__hash__",
"so",
"that",
"they",
"can",
"be",
"used",
"correctly",
"for",
"example",
"in",
"sets",
"."
] | train | https://github.com/smarie/python-autoclass/blob/097098776c69ebc87bc1aeda6997431b29bd583a/autoclass/autohash_.py#L88-L187 |
smarie/python-autoclass | autoclass/autoclass_.py | autoclass | def autoclass(include=None, # type: Union[str, Tuple[str]]
exclude=None, # type: Union[str, Tuple[str]]
autoargs=True, # type: bool
autoprops=True, # type: bool
autodict=True, # type: bool
autohash=True, # type: bool
cls=DE... | python | def autoclass(include=None, # type: Union[str, Tuple[str]]
exclude=None, # type: Union[str, Tuple[str]]
autoargs=True, # type: bool
autoprops=True, # type: bool
autodict=True, # type: bool
autohash=True, # type: bool
cls=DE... | [
"def",
"autoclass",
"(",
"include",
"=",
"None",
",",
"# type: Union[str, Tuple[str]]",
"exclude",
"=",
"None",
",",
"# type: Union[str, Tuple[str]]",
"autoargs",
"=",
"True",
",",
"# type: bool",
"autoprops",
"=",
"True",
",",
"# type: bool",
"autodict",
"=",
"True... | A decorator to perform @autoargs, @autoprops and @autodict all at once with the same include/exclude list.
:param include: a tuple of explicit attribute names to include (None means all)
:param exclude: a tuple of explicit attribute names to exclude. In such case, include should be None.
:param autoargs: a... | [
"A",
"decorator",
"to",
"perform",
"@autoargs",
"@autoprops",
"and",
"@autodict",
"all",
"at",
"once",
"with",
"the",
"same",
"include",
"/",
"exclude",
"list",
"."
] | train | https://github.com/smarie/python-autoclass/blob/097098776c69ebc87bc1aeda6997431b29bd583a/autoclass/autoclass_.py#L22-L42 |
smarie/python-autoclass | ci_tools/py_install.py | install | def install(cmd, packages):
"""
Installs all packages provided at once
:param packages:
:return:
"""
check_cmd(cmd)
all_pkgs_str = " ".join(all_pkgs)
print("INSTALLING: " + cmd + " install " + all_pkgs_str)
subprocess.check_call([cmd, 'install'] + packages) | python | def install(cmd, packages):
"""
Installs all packages provided at once
:param packages:
:return:
"""
check_cmd(cmd)
all_pkgs_str = " ".join(all_pkgs)
print("INSTALLING: " + cmd + " install " + all_pkgs_str)
subprocess.check_call([cmd, 'install'] + packages) | [
"def",
"install",
"(",
"cmd",
",",
"packages",
")",
":",
"check_cmd",
"(",
"cmd",
")",
"all_pkgs_str",
"=",
"\" \"",
".",
"join",
"(",
"all_pkgs",
")",
"print",
"(",
"\"INSTALLING: \"",
"+",
"cmd",
"+",
"\" install \"",
"+",
"all_pkgs_str",
")",
"subproces... | Installs all packages provided at once
:param packages:
:return: | [
"Installs",
"all",
"packages",
"provided",
"at",
"once",
":",
"param",
"packages",
":",
":",
"return",
":"
] | train | https://github.com/smarie/python-autoclass/blob/097098776c69ebc87bc1aeda6997431b29bd583a/ci_tools/py_install.py#L18-L28 |
smarie/python-autoclass | autoclass/autodict_.py | autodict | def autodict(include=None, # type: Union[str, Tuple[str]]
exclude=None, # type: Union[str, Tuple[str]]
only_constructor_args=True, # type: bool
only_public_fields=True, # type: bool
cls=DECORATED
):
"""
A decorat... | python | def autodict(include=None, # type: Union[str, Tuple[str]]
exclude=None, # type: Union[str, Tuple[str]]
only_constructor_args=True, # type: bool
only_public_fields=True, # type: bool
cls=DECORATED
):
"""
A decorat... | [
"def",
"autodict",
"(",
"include",
"=",
"None",
",",
"# type: Union[str, Tuple[str]]",
"exclude",
"=",
"None",
",",
"# type: Union[str, Tuple[str]]",
"only_constructor_args",
"=",
"True",
",",
"# type: bool",
"only_public_fields",
"=",
"True",
",",
"# type: bool",
"cls"... | A decorator to makes objects of the class behave like a read-only `dict`. It does several things:
* it adds collections.Mapping to the list of parent classes (i.e. to the class' `__bases__`)
* it generates `__len__`, `__iter__` and `__getitem__` in order for the appropriate fields to be exposed in the dict
... | [
"A",
"decorator",
"to",
"makes",
"objects",
"of",
"the",
"class",
"behave",
"like",
"a",
"read",
"-",
"only",
"dict",
".",
"It",
"does",
"several",
"things",
":",
"*",
"it",
"adds",
"collections",
".",
"Mapping",
"to",
"the",
"list",
"of",
"parent",
"c... | train | https://github.com/smarie/python-autoclass/blob/097098776c69ebc87bc1aeda6997431b29bd583a/autoclass/autodict_.py#L34-L62 |
smarie/python-autoclass | autoclass/autodict_.py | autodict_decorate | def autodict_decorate(cls, # type: Type[T]
include=None, # type: Union[str, Tuple[str]]
exclude=None, # type: Union[str, Tuple[str]]
only_constructor_args=True, # type: bool
onl... | python | def autodict_decorate(cls, # type: Type[T]
include=None, # type: Union[str, Tuple[str]]
exclude=None, # type: Union[str, Tuple[str]]
only_constructor_args=True, # type: bool
onl... | [
"def",
"autodict_decorate",
"(",
"cls",
",",
"# type: Type[T]",
"include",
"=",
"None",
",",
"# type: Union[str, Tuple[str]]",
"exclude",
"=",
"None",
",",
"# type: Union[str, Tuple[str]]",
"only_constructor_args",
"=",
"True",
",",
"# type: bool",
"only_public_fields",
"... | To automatically generate the appropriate methods so that objects of this class behave like a `dict`,
manually, without using @autodict decorator.
:param cls: the class on which to execute. Note that it won't be wrapped.
:param include: a tuple of explicit attribute names to include (None means all)
:p... | [
"To",
"automatically",
"generate",
"the",
"appropriate",
"methods",
"so",
"that",
"objects",
"of",
"this",
"class",
"behave",
"like",
"a",
"dict",
"manually",
"without",
"using",
"@autodict",
"decorator",
"."
] | train | https://github.com/smarie/python-autoclass/blob/097098776c69ebc87bc1aeda6997431b29bd583a/autoclass/autodict_.py#L65-L94 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.