id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
239,000 | google/transitfeed | transitfeed/problems.py | ProblemReporter.InvalidLineEnd | def InvalidLineEnd(self, bad_line_end, context=None, type=TYPE_WARNING):
"""bad_line_end is a human readable string."""
e = InvalidLineEnd(bad_line_end=bad_line_end, context=context,
context2=self._context, type=type)
self.AddToAccumulator(e) | python | def InvalidLineEnd(self, bad_line_end, context=None, type=TYPE_WARNING):
e = InvalidLineEnd(bad_line_end=bad_line_end, context=context,
context2=self._context, type=type)
self.AddToAccumulator(e) | [
"def",
"InvalidLineEnd",
"(",
"self",
",",
"bad_line_end",
",",
"context",
"=",
"None",
",",
"type",
"=",
"TYPE_WARNING",
")",
":",
"e",
"=",
"InvalidLineEnd",
"(",
"bad_line_end",
"=",
"bad_line_end",
",",
"context",
"=",
"context",
",",
"context2",
"=",
... | bad_line_end is a human readable string. | [
"bad_line_end",
"is",
"a",
"human",
"readable",
"string",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/problems.py#L268-L272 |
239,001 | google/transitfeed | transitfeed/problems.py | ExceptionWithContext.GetDictToFormat | def GetDictToFormat(self):
"""Return a copy of self as a dict, suitable for passing to FormatProblem"""
d = {}
for k, v in self.__dict__.items():
# TODO: Better handling of unicode/utf-8 within Schedule objects.
# Concatinating a unicode and utf-8 str object causes an exception such
# as "UnicodeDecodeError: 'ascii' codec can't decode byte ..." as python
# tries to convert the str to a unicode. To avoid that happening within
# the problem reporter convert all unicode attributes to utf-8.
# Currently valid utf-8 fields are converted to unicode in _ReadCsvDict.
# Perhaps all fields should be left as utf-8.
d[k] = util.EncodeUnicode(v)
return d | python | def GetDictToFormat(self):
d = {}
for k, v in self.__dict__.items():
# TODO: Better handling of unicode/utf-8 within Schedule objects.
# Concatinating a unicode and utf-8 str object causes an exception such
# as "UnicodeDecodeError: 'ascii' codec can't decode byte ..." as python
# tries to convert the str to a unicode. To avoid that happening within
# the problem reporter convert all unicode attributes to utf-8.
# Currently valid utf-8 fields are converted to unicode in _ReadCsvDict.
# Perhaps all fields should be left as utf-8.
d[k] = util.EncodeUnicode(v)
return d | [
"def",
"GetDictToFormat",
"(",
"self",
")",
":",
"d",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"self",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"# TODO: Better handling of unicode/utf-8 within Schedule objects.",
"# Concatinating a unicode and utf-8 str object ... | Return a copy of self as a dict, suitable for passing to FormatProblem | [
"Return",
"a",
"copy",
"of",
"self",
"as",
"a",
"dict",
"suitable",
"for",
"passing",
"to",
"FormatProblem"
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/problems.py#L445-L457 |
239,002 | google/transitfeed | transitfeed/problems.py | ExceptionWithContext.FormatProblem | def FormatProblem(self, d=None):
"""Return a text string describing the problem.
Args:
d: map returned by GetDictToFormat with with formatting added
"""
if not d:
d = self.GetDictToFormat()
output_error_text = self.__class__.ERROR_TEXT % d
if ('reason' in d) and d['reason']:
return '%s\n%s' % (output_error_text, d['reason'])
else:
return output_error_text | python | def FormatProblem(self, d=None):
if not d:
d = self.GetDictToFormat()
output_error_text = self.__class__.ERROR_TEXT % d
if ('reason' in d) and d['reason']:
return '%s\n%s' % (output_error_text, d['reason'])
else:
return output_error_text | [
"def",
"FormatProblem",
"(",
"self",
",",
"d",
"=",
"None",
")",
":",
"if",
"not",
"d",
":",
"d",
"=",
"self",
".",
"GetDictToFormat",
"(",
")",
"output_error_text",
"=",
"self",
".",
"__class__",
".",
"ERROR_TEXT",
"%",
"d",
"if",
"(",
"'reason'",
"... | Return a text string describing the problem.
Args:
d: map returned by GetDictToFormat with with formatting added | [
"Return",
"a",
"text",
"string",
"describing",
"the",
"problem",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/problems.py#L459-L472 |
239,003 | google/transitfeed | transitfeed/problems.py | ExceptionWithContext.FormatContext | def FormatContext(self):
"""Return a text string describing the context"""
text = ''
if hasattr(self, 'feed_name'):
text += "In feed '%s': " % self.feed_name
if hasattr(self, 'file_name'):
text += self.file_name
if hasattr(self, 'row_num'):
text += ":%i" % self.row_num
if hasattr(self, 'column_name'):
text += " column %s" % self.column_name
return text | python | def FormatContext(self):
text = ''
if hasattr(self, 'feed_name'):
text += "In feed '%s': " % self.feed_name
if hasattr(self, 'file_name'):
text += self.file_name
if hasattr(self, 'row_num'):
text += ":%i" % self.row_num
if hasattr(self, 'column_name'):
text += " column %s" % self.column_name
return text | [
"def",
"FormatContext",
"(",
"self",
")",
":",
"text",
"=",
"''",
"if",
"hasattr",
"(",
"self",
",",
"'feed_name'",
")",
":",
"text",
"+=",
"\"In feed '%s': \"",
"%",
"self",
".",
"feed_name",
"if",
"hasattr",
"(",
"self",
",",
"'file_name'",
")",
":",
... | Return a text string describing the context | [
"Return",
"a",
"text",
"string",
"describing",
"the",
"context"
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/problems.py#L474-L485 |
239,004 | google/transitfeed | transitfeed/problems.py | ExceptionWithContext.GetOrderKey | def GetOrderKey(self):
"""Return a tuple that can be used to sort problems into a consistent order.
Returns:
A list of values.
"""
context_attributes = ['_type']
context_attributes.extend(ExceptionWithContext.CONTEXT_PARTS)
context_attributes.extend(self._GetExtraOrderAttributes())
tokens = []
for context_attribute in context_attributes:
tokens.append(getattr(self, context_attribute, None))
return tokens | python | def GetOrderKey(self):
context_attributes = ['_type']
context_attributes.extend(ExceptionWithContext.CONTEXT_PARTS)
context_attributes.extend(self._GetExtraOrderAttributes())
tokens = []
for context_attribute in context_attributes:
tokens.append(getattr(self, context_attribute, None))
return tokens | [
"def",
"GetOrderKey",
"(",
"self",
")",
":",
"context_attributes",
"=",
"[",
"'_type'",
"]",
"context_attributes",
".",
"extend",
"(",
"ExceptionWithContext",
".",
"CONTEXT_PARTS",
")",
"context_attributes",
".",
"extend",
"(",
"self",
".",
"_GetExtraOrderAttributes... | Return a tuple that can be used to sort problems into a consistent order.
Returns:
A list of values. | [
"Return",
"a",
"tuple",
"that",
"can",
"be",
"used",
"to",
"sort",
"problems",
"into",
"a",
"consistent",
"order",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/problems.py#L506-L519 |
239,005 | google/transitfeed | visualize_pathways.py | gtfs_to_graphviz | def gtfs_to_graphviz(gtfs, stop_ids=None):
"""Reads GTFS data and returns GraphViz DOT file content as string.
"""
graph = GraphViz()
location_ids = choose_location_ids(gtfs, stop_ids)
locations = [gtfs.get_location(i) for i in location_ids]
for location in locations:
if not location.parent_id:
graph.add_cluster(GraphCluster(
location.gtfs_id,
location_label(location, max_length=-1),
location_color(location.location_type)))
for location in locations:
if location.parent_id and requires_platform_cluster(location):
graph.get_cluster(location.parent_id).add_cluster(GraphCluster(
location.gtfs_id,
location_label(location),
location_color(location.location_type)))
for location in locations:
if not location.parent_id or requires_platform_cluster(location):
continue
node = GraphNode(
location.gtfs_id,
location_label(location, max_length=25),
location_color(location.location_type),
location_shape(location.location_type))
cluster = graph.get_cluster(location.station().gtfs_id)
if location.location_type == LocationType.boarding_area:
cluster = cluster.get_cluster(location.parent_id)
cluster.nodes.append(node)
for pathway in gtfs.pathways:
if pathway.from_id in location_ids and pathway.to_id in location_ids:
graph.edges.append(GraphEdge(
pathway.from_id, pathway.to_id,
'both' if pathway.is_bidirectional else 'forward',
pathway_label(pathway)))
return graph | python | def gtfs_to_graphviz(gtfs, stop_ids=None):
graph = GraphViz()
location_ids = choose_location_ids(gtfs, stop_ids)
locations = [gtfs.get_location(i) for i in location_ids]
for location in locations:
if not location.parent_id:
graph.add_cluster(GraphCluster(
location.gtfs_id,
location_label(location, max_length=-1),
location_color(location.location_type)))
for location in locations:
if location.parent_id and requires_platform_cluster(location):
graph.get_cluster(location.parent_id).add_cluster(GraphCluster(
location.gtfs_id,
location_label(location),
location_color(location.location_type)))
for location in locations:
if not location.parent_id or requires_platform_cluster(location):
continue
node = GraphNode(
location.gtfs_id,
location_label(location, max_length=25),
location_color(location.location_type),
location_shape(location.location_type))
cluster = graph.get_cluster(location.station().gtfs_id)
if location.location_type == LocationType.boarding_area:
cluster = cluster.get_cluster(location.parent_id)
cluster.nodes.append(node)
for pathway in gtfs.pathways:
if pathway.from_id in location_ids and pathway.to_id in location_ids:
graph.edges.append(GraphEdge(
pathway.from_id, pathway.to_id,
'both' if pathway.is_bidirectional else 'forward',
pathway_label(pathway)))
return graph | [
"def",
"gtfs_to_graphviz",
"(",
"gtfs",
",",
"stop_ids",
"=",
"None",
")",
":",
"graph",
"=",
"GraphViz",
"(",
")",
"location_ids",
"=",
"choose_location_ids",
"(",
"gtfs",
",",
"stop_ids",
")",
"locations",
"=",
"[",
"gtfs",
".",
"get_location",
"(",
"i",... | Reads GTFS data and returns GraphViz DOT file content as string. | [
"Reads",
"GTFS",
"data",
"and",
"returns",
"GraphViz",
"DOT",
"file",
"content",
"as",
"string",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/visualize_pathways.py#L424-L466 |
239,006 | google/transitfeed | transitfeed/gtfsfactoryuser.py | GtfsFactoryUser.GetGtfsFactory | def GetGtfsFactory(self):
"""Return the object's GTFS Factory.
Returns:
The GTFS Factory that was set for this object. If none was explicitly
set, it first sets the object's factory to transitfeed's GtfsFactory
and returns it"""
if self._gtfs_factory is None:
#TODO(anog): We really need to create a dependency graph and clean things
# up, as the comment in __init__.py says.
# Not having GenericGTFSObject as a leaf (with no other
# imports) creates all sorts of circular import problems.
# This is why the import is here and not at the top level.
# When this runs, gtfsfactory should have already been loaded
# by other modules, avoiding the circular imports.
from . import gtfsfactory
self._gtfs_factory = gtfsfactory.GetGtfsFactory()
return self._gtfs_factory | python | def GetGtfsFactory(self):
if self._gtfs_factory is None:
#TODO(anog): We really need to create a dependency graph and clean things
# up, as the comment in __init__.py says.
# Not having GenericGTFSObject as a leaf (with no other
# imports) creates all sorts of circular import problems.
# This is why the import is here and not at the top level.
# When this runs, gtfsfactory should have already been loaded
# by other modules, avoiding the circular imports.
from . import gtfsfactory
self._gtfs_factory = gtfsfactory.GetGtfsFactory()
return self._gtfs_factory | [
"def",
"GetGtfsFactory",
"(",
"self",
")",
":",
"if",
"self",
".",
"_gtfs_factory",
"is",
"None",
":",
"#TODO(anog): We really need to create a dependency graph and clean things",
"# up, as the comment in __init__.py says.",
"# Not having GenericGTFSObject as a le... | Return the object's GTFS Factory.
Returns:
The GTFS Factory that was set for this object. If none was explicitly
set, it first sets the object's factory to transitfeed's GtfsFactory
and returns it | [
"Return",
"the",
"object",
"s",
"GTFS",
"Factory",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/gtfsfactoryuser.py#L26-L44 |
239,007 | google/transitfeed | transitfeed/gtfsobjectbase.py | GtfsObjectBase.keys | def keys(self):
"""Return iterable of columns used by this object."""
columns = set()
for name in vars(self):
if (not name) or name[0] == "_":
continue
columns.add(name)
return columns | python | def keys(self):
columns = set()
for name in vars(self):
if (not name) or name[0] == "_":
continue
columns.add(name)
return columns | [
"def",
"keys",
"(",
"self",
")",
":",
"columns",
"=",
"set",
"(",
")",
"for",
"name",
"in",
"vars",
"(",
"self",
")",
":",
"if",
"(",
"not",
"name",
")",
"or",
"name",
"[",
"0",
"]",
"==",
"\"_\"",
":",
"continue",
"columns",
".",
"add",
"(",
... | Return iterable of columns used by this object. | [
"Return",
"iterable",
"of",
"columns",
"used",
"by",
"this",
"object",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/gtfsobjectbase.py#L108-L115 |
239,008 | google/transitfeed | transitfeed/shape.py | Shape.AddShapePointObjectUnsorted | def AddShapePointObjectUnsorted(self, shapepoint, problems):
"""Insert a point into a correct position by sequence. """
if (len(self.sequence) == 0 or
shapepoint.shape_pt_sequence >= self.sequence[-1]):
index = len(self.sequence)
elif shapepoint.shape_pt_sequence <= self.sequence[0]:
index = 0
else:
index = bisect.bisect(self.sequence, shapepoint.shape_pt_sequence)
if shapepoint.shape_pt_sequence in self.sequence:
problems.InvalidValue('shape_pt_sequence', shapepoint.shape_pt_sequence,
'The sequence number %d occurs more than once in '
'shape %s.' %
(shapepoint.shape_pt_sequence, self.shape_id))
if shapepoint.shape_dist_traveled is not None and len(self.sequence) > 0:
if (index != len(self.sequence) and
shapepoint.shape_dist_traveled > self.distance[index]):
problems.InvalidValue('shape_dist_traveled',
shapepoint.shape_dist_traveled,
'Each subsequent point in a shape should have '
'a distance value that shouldn\'t be larger '
'than the next ones. In this case, the next '
'distance was %f.' % self.distance[index])
if (index > 0 and
shapepoint.shape_dist_traveled < self.distance[index - 1]):
problems.InvalidValue('shape_dist_traveled',
shapepoint.shape_dist_traveled,
'Each subsequent point in a shape should have '
'a distance value that\'s at least as large as '
'the previous ones. In this case, the previous '
'distance was %f.' % self.distance[index - 1])
if shapepoint.shape_dist_traveled > self.max_distance:
self.max_distance = shapepoint.shape_dist_traveled
self.sequence.insert(index, shapepoint.shape_pt_sequence)
self.distance.insert(index, shapepoint.shape_dist_traveled)
self.points.insert(index, (shapepoint.shape_pt_lat,
shapepoint.shape_pt_lon,
shapepoint.shape_dist_traveled)) | python | def AddShapePointObjectUnsorted(self, shapepoint, problems):
if (len(self.sequence) == 0 or
shapepoint.shape_pt_sequence >= self.sequence[-1]):
index = len(self.sequence)
elif shapepoint.shape_pt_sequence <= self.sequence[0]:
index = 0
else:
index = bisect.bisect(self.sequence, shapepoint.shape_pt_sequence)
if shapepoint.shape_pt_sequence in self.sequence:
problems.InvalidValue('shape_pt_sequence', shapepoint.shape_pt_sequence,
'The sequence number %d occurs more than once in '
'shape %s.' %
(shapepoint.shape_pt_sequence, self.shape_id))
if shapepoint.shape_dist_traveled is not None and len(self.sequence) > 0:
if (index != len(self.sequence) and
shapepoint.shape_dist_traveled > self.distance[index]):
problems.InvalidValue('shape_dist_traveled',
shapepoint.shape_dist_traveled,
'Each subsequent point in a shape should have '
'a distance value that shouldn\'t be larger '
'than the next ones. In this case, the next '
'distance was %f.' % self.distance[index])
if (index > 0 and
shapepoint.shape_dist_traveled < self.distance[index - 1]):
problems.InvalidValue('shape_dist_traveled',
shapepoint.shape_dist_traveled,
'Each subsequent point in a shape should have '
'a distance value that\'s at least as large as '
'the previous ones. In this case, the previous '
'distance was %f.' % self.distance[index - 1])
if shapepoint.shape_dist_traveled > self.max_distance:
self.max_distance = shapepoint.shape_dist_traveled
self.sequence.insert(index, shapepoint.shape_pt_sequence)
self.distance.insert(index, shapepoint.shape_dist_traveled)
self.points.insert(index, (shapepoint.shape_pt_lat,
shapepoint.shape_pt_lon,
shapepoint.shape_dist_traveled)) | [
"def",
"AddShapePointObjectUnsorted",
"(",
"self",
",",
"shapepoint",
",",
"problems",
")",
":",
"if",
"(",
"len",
"(",
"self",
".",
"sequence",
")",
"==",
"0",
"or",
"shapepoint",
".",
"shape_pt_sequence",
">=",
"self",
".",
"sequence",
"[",
"-",
"1",
"... | Insert a point into a correct position by sequence. | [
"Insert",
"a",
"point",
"into",
"a",
"correct",
"position",
"by",
"sequence",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/shape.py#L54-L96 |
239,009 | google/transitfeed | transitfeed/shape.py | Shape.GetPointWithDistanceTraveled | def GetPointWithDistanceTraveled(self, shape_dist_traveled):
"""Returns a point on the shape polyline with the input shape_dist_traveled.
Args:
shape_dist_traveled: The input shape_dist_traveled.
Returns:
The shape point as a tuple (lat, lng, shape_dist_traveled), where lat and
lng is the location of the shape point, and shape_dist_traveled is an
increasing metric representing the distance traveled along the shape.
Returns None if there is data error in shape.
"""
if not self.distance:
return None
if shape_dist_traveled <= self.distance[0]:
return self.points[0]
if shape_dist_traveled >= self.distance[-1]:
return self.points[-1]
index = bisect.bisect(self.distance, shape_dist_traveled)
(lat0, lng0, dist0) = self.points[index - 1]
(lat1, lng1, dist1) = self.points[index]
# Interpolate if shape_dist_traveled does not equal to any of the point
# in shape segment.
# (lat0, lng0) (lat, lng) (lat1, lng1)
# -----|--------------------|---------------------|------
# dist0 shape_dist_traveled dist1
# \------- ca --------/ \-------- bc -------/
# \----------------- ba ------------------/
ca = shape_dist_traveled - dist0
bc = dist1 - shape_dist_traveled
ba = bc + ca
if ba == 0:
# This only happens when there's data error in shapes and should have been
# catched before. Check to avoid crash.
return None
# This won't work crossing longitude 180 and is only an approximation which
# works well for short distance.
lat = (lat1 * ca + lat0 * bc) / ba
lng = (lng1 * ca + lng0 * bc) / ba
return (lat, lng, shape_dist_traveled) | python | def GetPointWithDistanceTraveled(self, shape_dist_traveled):
if not self.distance:
return None
if shape_dist_traveled <= self.distance[0]:
return self.points[0]
if shape_dist_traveled >= self.distance[-1]:
return self.points[-1]
index = bisect.bisect(self.distance, shape_dist_traveled)
(lat0, lng0, dist0) = self.points[index - 1]
(lat1, lng1, dist1) = self.points[index]
# Interpolate if shape_dist_traveled does not equal to any of the point
# in shape segment.
# (lat0, lng0) (lat, lng) (lat1, lng1)
# -----|--------------------|---------------------|------
# dist0 shape_dist_traveled dist1
# \------- ca --------/ \-------- bc -------/
# \----------------- ba ------------------/
ca = shape_dist_traveled - dist0
bc = dist1 - shape_dist_traveled
ba = bc + ca
if ba == 0:
# This only happens when there's data error in shapes and should have been
# catched before. Check to avoid crash.
return None
# This won't work crossing longitude 180 and is only an approximation which
# works well for short distance.
lat = (lat1 * ca + lat0 * bc) / ba
lng = (lng1 * ca + lng0 * bc) / ba
return (lat, lng, shape_dist_traveled) | [
"def",
"GetPointWithDistanceTraveled",
"(",
"self",
",",
"shape_dist_traveled",
")",
":",
"if",
"not",
"self",
".",
"distance",
":",
"return",
"None",
"if",
"shape_dist_traveled",
"<=",
"self",
".",
"distance",
"[",
"0",
"]",
":",
"return",
"self",
".",
"poi... | Returns a point on the shape polyline with the input shape_dist_traveled.
Args:
shape_dist_traveled: The input shape_dist_traveled.
Returns:
The shape point as a tuple (lat, lng, shape_dist_traveled), where lat and
lng is the location of the shape point, and shape_dist_traveled is an
increasing metric representing the distance traveled along the shape.
Returns None if there is data error in shape. | [
"Returns",
"a",
"point",
"on",
"the",
"shape",
"polyline",
"with",
"the",
"input",
"shape_dist_traveled",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/shape.py#L129-L170 |
239,010 | google/transitfeed | transitfeed/trip.py | Trip.AddStopTime | def AddStopTime(self, stop, problems=None, schedule=None, **kwargs):
"""Add a stop to this trip. Stops must be added in the order visited.
Args:
stop: A Stop object
kwargs: remaining keyword args passed to StopTime.__init__
Returns:
None
"""
if problems is None:
# TODO: delete this branch when StopTime.__init__ doesn't need a
# ProblemReporter
problems = problems_module.default_problem_reporter
stoptime = self.GetGtfsFactory().StopTime(
problems=problems, stop=stop, **kwargs)
self.AddStopTimeObject(stoptime, schedule) | python | def AddStopTime(self, stop, problems=None, schedule=None, **kwargs):
if problems is None:
# TODO: delete this branch when StopTime.__init__ doesn't need a
# ProblemReporter
problems = problems_module.default_problem_reporter
stoptime = self.GetGtfsFactory().StopTime(
problems=problems, stop=stop, **kwargs)
self.AddStopTimeObject(stoptime, schedule) | [
"def",
"AddStopTime",
"(",
"self",
",",
"stop",
",",
"problems",
"=",
"None",
",",
"schedule",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"problems",
"is",
"None",
":",
"# TODO: delete this branch when StopTime.__init__ doesn't need a",
"# ProblemReport... | Add a stop to this trip. Stops must be added in the order visited.
Args:
stop: A Stop object
kwargs: remaining keyword args passed to StopTime.__init__
Returns:
None | [
"Add",
"a",
"stop",
"to",
"this",
"trip",
".",
"Stops",
"must",
"be",
"added",
"in",
"the",
"order",
"visited",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/trip.py#L59-L75 |
239,011 | google/transitfeed | transitfeed/trip.py | Trip._AddStopTimeObjectUnordered | def _AddStopTimeObjectUnordered(self, stoptime, schedule):
"""Add StopTime object to this trip.
The trip isn't checked for duplicate sequence numbers so it must be
validated later."""
stop_time_class = self.GetGtfsFactory().StopTime
cursor = schedule._connection.cursor()
insert_query = "INSERT INTO stop_times (%s) VALUES (%s);" % (
','.join(stop_time_class._SQL_FIELD_NAMES),
','.join(['?'] * len(stop_time_class._SQL_FIELD_NAMES)))
cursor = schedule._connection.cursor()
cursor.execute(
insert_query, stoptime.GetSqlValuesTuple(self.trip_id)) | python | def _AddStopTimeObjectUnordered(self, stoptime, schedule):
stop_time_class = self.GetGtfsFactory().StopTime
cursor = schedule._connection.cursor()
insert_query = "INSERT INTO stop_times (%s) VALUES (%s);" % (
','.join(stop_time_class._SQL_FIELD_NAMES),
','.join(['?'] * len(stop_time_class._SQL_FIELD_NAMES)))
cursor = schedule._connection.cursor()
cursor.execute(
insert_query, stoptime.GetSqlValuesTuple(self.trip_id)) | [
"def",
"_AddStopTimeObjectUnordered",
"(",
"self",
",",
"stoptime",
",",
"schedule",
")",
":",
"stop_time_class",
"=",
"self",
".",
"GetGtfsFactory",
"(",
")",
".",
"StopTime",
"cursor",
"=",
"schedule",
".",
"_connection",
".",
"cursor",
"(",
")",
"insert_que... | Add StopTime object to this trip.
The trip isn't checked for duplicate sequence numbers so it must be
validated later. | [
"Add",
"StopTime",
"object",
"to",
"this",
"trip",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/trip.py#L77-L89 |
239,012 | google/transitfeed | transitfeed/trip.py | Trip.ReplaceStopTimeObject | def ReplaceStopTimeObject(self, stoptime, schedule=None):
"""Replace a StopTime object from this trip with the given one.
Keys the StopTime object to be replaced by trip_id, stop_sequence
and stop_id as 'stoptime', with the object 'stoptime'.
"""
if schedule is None:
schedule = self._schedule
new_secs = stoptime.GetTimeSecs()
cursor = schedule._connection.cursor()
cursor.execute("DELETE FROM stop_times WHERE trip_id=? and "
"stop_sequence=? and stop_id=?",
(self.trip_id, stoptime.stop_sequence, stoptime.stop_id))
if cursor.rowcount == 0:
raise problems_module.Error('Attempted replacement of StopTime object which does not exist')
self._AddStopTimeObjectUnordered(stoptime, schedule) | python | def ReplaceStopTimeObject(self, stoptime, schedule=None):
if schedule is None:
schedule = self._schedule
new_secs = stoptime.GetTimeSecs()
cursor = schedule._connection.cursor()
cursor.execute("DELETE FROM stop_times WHERE trip_id=? and "
"stop_sequence=? and stop_id=?",
(self.trip_id, stoptime.stop_sequence, stoptime.stop_id))
if cursor.rowcount == 0:
raise problems_module.Error('Attempted replacement of StopTime object which does not exist')
self._AddStopTimeObjectUnordered(stoptime, schedule) | [
"def",
"ReplaceStopTimeObject",
"(",
"self",
",",
"stoptime",
",",
"schedule",
"=",
"None",
")",
":",
"if",
"schedule",
"is",
"None",
":",
"schedule",
"=",
"self",
".",
"_schedule",
"new_secs",
"=",
"stoptime",
".",
"GetTimeSecs",
"(",
")",
"cursor",
"=",
... | Replace a StopTime object from this trip with the given one.
Keys the StopTime object to be replaced by trip_id, stop_sequence
and stop_id as 'stoptime', with the object 'stoptime'. | [
"Replace",
"a",
"StopTime",
"object",
"from",
"this",
"trip",
"with",
"the",
"given",
"one",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/trip.py#L91-L108 |
239,013 | google/transitfeed | transitfeed/trip.py | Trip.AddStopTimeObject | def AddStopTimeObject(self, stoptime, schedule=None, problems=None):
"""Add a StopTime object to the end of this trip.
Args:
stoptime: A StopTime object. Should not be reused in multiple trips.
schedule: Schedule object containing this trip which must be
passed to Trip.__init__ or here
problems: ProblemReporter object for validating the StopTime in its new
home
Returns:
None
"""
if schedule is None:
schedule = self._schedule
if schedule is None:
warnings.warn("No longer supported. _schedule attribute is used to get "
"stop_times table", DeprecationWarning)
if problems is None:
problems = schedule.problem_reporter
new_secs = stoptime.GetTimeSecs()
cursor = schedule._connection.cursor()
cursor.execute("SELECT max(stop_sequence), max(arrival_secs), "
"max(departure_secs) FROM stop_times WHERE trip_id=?",
(self.trip_id,))
row = cursor.fetchone()
if row[0] is None:
# This is the first stop_time of the trip
stoptime.stop_sequence = 1
if new_secs == None:
problems.OtherProblem(
'No time for first StopTime of trip_id "%s"' % (self.trip_id,))
else:
stoptime.stop_sequence = row[0] + 1
prev_secs = max(row[1], row[2])
if new_secs != None and new_secs < prev_secs:
problems.OtherProblem(
'out of order stop time for stop_id=%s trip_id=%s %s < %s' %
(util.EncodeUnicode(stoptime.stop_id),
util.EncodeUnicode(self.trip_id),
util.FormatSecondsSinceMidnight(new_secs),
util.FormatSecondsSinceMidnight(prev_secs)))
self._AddStopTimeObjectUnordered(stoptime, schedule) | python | def AddStopTimeObject(self, stoptime, schedule=None, problems=None):
if schedule is None:
schedule = self._schedule
if schedule is None:
warnings.warn("No longer supported. _schedule attribute is used to get "
"stop_times table", DeprecationWarning)
if problems is None:
problems = schedule.problem_reporter
new_secs = stoptime.GetTimeSecs()
cursor = schedule._connection.cursor()
cursor.execute("SELECT max(stop_sequence), max(arrival_secs), "
"max(departure_secs) FROM stop_times WHERE trip_id=?",
(self.trip_id,))
row = cursor.fetchone()
if row[0] is None:
# This is the first stop_time of the trip
stoptime.stop_sequence = 1
if new_secs == None:
problems.OtherProblem(
'No time for first StopTime of trip_id "%s"' % (self.trip_id,))
else:
stoptime.stop_sequence = row[0] + 1
prev_secs = max(row[1], row[2])
if new_secs != None and new_secs < prev_secs:
problems.OtherProblem(
'out of order stop time for stop_id=%s trip_id=%s %s < %s' %
(util.EncodeUnicode(stoptime.stop_id),
util.EncodeUnicode(self.trip_id),
util.FormatSecondsSinceMidnight(new_secs),
util.FormatSecondsSinceMidnight(prev_secs)))
self._AddStopTimeObjectUnordered(stoptime, schedule) | [
"def",
"AddStopTimeObject",
"(",
"self",
",",
"stoptime",
",",
"schedule",
"=",
"None",
",",
"problems",
"=",
"None",
")",
":",
"if",
"schedule",
"is",
"None",
":",
"schedule",
"=",
"self",
".",
"_schedule",
"if",
"schedule",
"is",
"None",
":",
"warnings... | Add a StopTime object to the end of this trip.
Args:
stoptime: A StopTime object. Should not be reused in multiple trips.
schedule: Schedule object containing this trip which must be
passed to Trip.__init__ or here
problems: ProblemReporter object for validating the StopTime in its new
home
Returns:
None | [
"Add",
"a",
"StopTime",
"object",
"to",
"the",
"end",
"of",
"this",
"trip",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/trip.py#L110-L153 |
239,014 | google/transitfeed | transitfeed/trip.py | Trip.GetCountStopTimes | def GetCountStopTimes(self):
"""Return the number of stops made by this trip."""
cursor = self._schedule._connection.cursor()
cursor.execute(
'SELECT count(*) FROM stop_times WHERE trip_id=?', (self.trip_id,))
return cursor.fetchone()[0] | python | def GetCountStopTimes(self):
cursor = self._schedule._connection.cursor()
cursor.execute(
'SELECT count(*) FROM stop_times WHERE trip_id=?', (self.trip_id,))
return cursor.fetchone()[0] | [
"def",
"GetCountStopTimes",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"_schedule",
".",
"_connection",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"'SELECT count(*) FROM stop_times WHERE trip_id=?'",
",",
"(",
"self",
".",
"trip_id",
",",
... | Return the number of stops made by this trip. | [
"Return",
"the",
"number",
"of",
"stops",
"made",
"by",
"this",
"trip",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/trip.py#L163-L168 |
239,015 | google/transitfeed | transitfeed/trip.py | Trip.ClearStopTimes | def ClearStopTimes(self):
"""Remove all stop times from this trip.
StopTime objects previously returned by GetStopTimes are unchanged but are
no longer associated with this trip.
"""
cursor = self._schedule._connection.cursor()
cursor.execute('DELETE FROM stop_times WHERE trip_id=?', (self.trip_id,)) | python | def ClearStopTimes(self):
cursor = self._schedule._connection.cursor()
cursor.execute('DELETE FROM stop_times WHERE trip_id=?', (self.trip_id,)) | [
"def",
"ClearStopTimes",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"_schedule",
".",
"_connection",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"'DELETE FROM stop_times WHERE trip_id=?'",
",",
"(",
"self",
".",
"trip_id",
",",
")",
")"
] | Remove all stop times from this trip.
StopTime objects previously returned by GetStopTimes are unchanged but are
no longer associated with this trip. | [
"Remove",
"all",
"stop",
"times",
"from",
"this",
"trip",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/trip.py#L218-L225 |
239,016 | google/transitfeed | transitfeed/trip.py | Trip.GetStopTimes | def GetStopTimes(self, problems=None):
"""Return a sorted list of StopTime objects for this trip."""
# In theory problems=None should be safe because data from database has been
# validated. See comment in _LoadStopTimes for why this isn't always true.
cursor = self._schedule._connection.cursor()
cursor.execute(
'SELECT arrival_secs,departure_secs,stop_headsign,pickup_type,'
'drop_off_type,shape_dist_traveled,stop_id,stop_sequence,timepoint '
'FROM stop_times '
'WHERE trip_id=? '
'ORDER BY stop_sequence', (self.trip_id,))
stop_times = []
stoptime_class = self.GetGtfsFactory().StopTime
if problems is None:
# TODO: delete this branch when StopTime.__init__ doesn't need a
# ProblemReporter
problems = problems_module.default_problem_reporter
for row in cursor.fetchall():
stop = self._schedule.GetStop(row[6])
stop_times.append(stoptime_class(problems=problems,
stop=stop,
arrival_secs=row[0],
departure_secs=row[1],
stop_headsign=row[2],
pickup_type=row[3],
drop_off_type=row[4],
shape_dist_traveled=row[5],
stop_sequence=row[7],
timepoint=row[8]))
return stop_times | python | def GetStopTimes(self, problems=None):
# In theory problems=None should be safe because data from database has been
# validated. See comment in _LoadStopTimes for why this isn't always true.
cursor = self._schedule._connection.cursor()
cursor.execute(
'SELECT arrival_secs,departure_secs,stop_headsign,pickup_type,'
'drop_off_type,shape_dist_traveled,stop_id,stop_sequence,timepoint '
'FROM stop_times '
'WHERE trip_id=? '
'ORDER BY stop_sequence', (self.trip_id,))
stop_times = []
stoptime_class = self.GetGtfsFactory().StopTime
if problems is None:
# TODO: delete this branch when StopTime.__init__ doesn't need a
# ProblemReporter
problems = problems_module.default_problem_reporter
for row in cursor.fetchall():
stop = self._schedule.GetStop(row[6])
stop_times.append(stoptime_class(problems=problems,
stop=stop,
arrival_secs=row[0],
departure_secs=row[1],
stop_headsign=row[2],
pickup_type=row[3],
drop_off_type=row[4],
shape_dist_traveled=row[5],
stop_sequence=row[7],
timepoint=row[8]))
return stop_times | [
"def",
"GetStopTimes",
"(",
"self",
",",
"problems",
"=",
"None",
")",
":",
"# In theory problems=None should be safe because data from database has been",
"# validated. See comment in _LoadStopTimes for why this isn't always true.",
"cursor",
"=",
"self",
".",
"_schedule",
".",
... | Return a sorted list of StopTime objects for this trip. | [
"Return",
"a",
"sorted",
"list",
"of",
"StopTime",
"objects",
"for",
"this",
"trip",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/trip.py#L227-L256 |
239,017 | google/transitfeed | transitfeed/trip.py | Trip.GetFrequencyStopTimes | def GetFrequencyStopTimes(self, problems=None):
"""Return a list of StopTime objects for each headway-based run.
Returns:
a list of list of StopTime objects. Each list of StopTime objects
represents one run. If this trip doesn't have headways returns an empty
list.
"""
stoptimes_list = [] # list of stoptime lists to be returned
stoptime_pattern = self.GetStopTimes()
first_secs = stoptime_pattern[0].arrival_secs # first time of the trip
stoptime_class = self.GetGtfsFactory().StopTime
# for each start time of a headway run
for run_secs in self.GetFrequencyStartTimes():
# stop time list for a headway run
stoptimes = []
# go through the pattern and generate stoptimes
for st in stoptime_pattern:
arrival_secs, departure_secs = None, None # default value if the stoptime is not timepoint
if st.arrival_secs != None:
arrival_secs = st.arrival_secs - first_secs + run_secs
if st.departure_secs != None:
departure_secs = st.departure_secs - first_secs + run_secs
# append stoptime
stoptimes.append(stoptime_class(problems=problems, stop=st.stop,
arrival_secs=arrival_secs,
departure_secs=departure_secs,
stop_headsign=st.stop_headsign,
pickup_type=st.pickup_type,
drop_off_type=st.drop_off_type,
shape_dist_traveled= \
st.shape_dist_traveled,
stop_sequence=st.stop_sequence,
timepoint=st.timepoint))
# add stoptimes to the stoptimes_list
stoptimes_list.append ( stoptimes )
return stoptimes_list | python | def GetFrequencyStopTimes(self, problems=None):
stoptimes_list = [] # list of stoptime lists to be returned
stoptime_pattern = self.GetStopTimes()
first_secs = stoptime_pattern[0].arrival_secs # first time of the trip
stoptime_class = self.GetGtfsFactory().StopTime
# for each start time of a headway run
for run_secs in self.GetFrequencyStartTimes():
# stop time list for a headway run
stoptimes = []
# go through the pattern and generate stoptimes
for st in stoptime_pattern:
arrival_secs, departure_secs = None, None # default value if the stoptime is not timepoint
if st.arrival_secs != None:
arrival_secs = st.arrival_secs - first_secs + run_secs
if st.departure_secs != None:
departure_secs = st.departure_secs - first_secs + run_secs
# append stoptime
stoptimes.append(stoptime_class(problems=problems, stop=st.stop,
arrival_secs=arrival_secs,
departure_secs=departure_secs,
stop_headsign=st.stop_headsign,
pickup_type=st.pickup_type,
drop_off_type=st.drop_off_type,
shape_dist_traveled= \
st.shape_dist_traveled,
stop_sequence=st.stop_sequence,
timepoint=st.timepoint))
# add stoptimes to the stoptimes_list
stoptimes_list.append ( stoptimes )
return stoptimes_list | [
"def",
"GetFrequencyStopTimes",
"(",
"self",
",",
"problems",
"=",
"None",
")",
":",
"stoptimes_list",
"=",
"[",
"]",
"# list of stoptime lists to be returned",
"stoptime_pattern",
"=",
"self",
".",
"GetStopTimes",
"(",
")",
"first_secs",
"=",
"stoptime_pattern",
"[... | Return a list of StopTime objects for each headway-based run.
Returns:
a list of list of StopTime objects. Each list of StopTime objects
represents one run. If this trip doesn't have headways returns an empty
list. | [
"Return",
"a",
"list",
"of",
"StopTime",
"objects",
"for",
"each",
"headway",
"-",
"based",
"run",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/trip.py#L265-L301 |
239,018 | google/transitfeed | transitfeed/trip.py | Trip.GetFrequencyStartTimes | def GetFrequencyStartTimes(self):
"""Return a list of start time for each headway-based run.
Returns:
a sorted list of seconds since midnight, the start time of each run. If
this trip doesn't have headways returns an empty list."""
start_times = []
# for each headway period of the trip
for freq_tuple in self.GetFrequencyTuples():
(start_secs, end_secs, headway_secs) = freq_tuple[0:3]
# reset run secs to the start of the timeframe
run_secs = start_secs
while run_secs < end_secs:
start_times.append(run_secs)
# increment current run secs by headway secs
run_secs += headway_secs
return start_times | python | def GetFrequencyStartTimes(self):
start_times = []
# for each headway period of the trip
for freq_tuple in self.GetFrequencyTuples():
(start_secs, end_secs, headway_secs) = freq_tuple[0:3]
# reset run secs to the start of the timeframe
run_secs = start_secs
while run_secs < end_secs:
start_times.append(run_secs)
# increment current run secs by headway secs
run_secs += headway_secs
return start_times | [
"def",
"GetFrequencyStartTimes",
"(",
"self",
")",
":",
"start_times",
"=",
"[",
"]",
"# for each headway period of the trip",
"for",
"freq_tuple",
"in",
"self",
".",
"GetFrequencyTuples",
"(",
")",
":",
"(",
"start_secs",
",",
"end_secs",
",",
"headway_secs",
")"... | Return a list of start time for each headway-based run.
Returns:
a sorted list of seconds since midnight, the start time of each run. If
this trip doesn't have headways returns an empty list. | [
"Return",
"a",
"list",
"of",
"start",
"time",
"for",
"each",
"headway",
"-",
"based",
"run",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/trip.py#L327-L343 |
239,019 | google/transitfeed | transitfeed/trip.py | Trip._GenerateStopTimesTuples | def _GenerateStopTimesTuples(self):
"""Generator for rows of the stop_times file"""
stoptimes = self.GetStopTimes()
for i, st in enumerate(stoptimes):
yield st.GetFieldValuesTuple(self.trip_id) | python | def _GenerateStopTimesTuples(self):
stoptimes = self.GetStopTimes()
for i, st in enumerate(stoptimes):
yield st.GetFieldValuesTuple(self.trip_id) | [
"def",
"_GenerateStopTimesTuples",
"(",
"self",
")",
":",
"stoptimes",
"=",
"self",
".",
"GetStopTimes",
"(",
")",
"for",
"i",
",",
"st",
"in",
"enumerate",
"(",
"stoptimes",
")",
":",
"yield",
"st",
".",
"GetFieldValuesTuple",
"(",
"self",
".",
"trip_id",... | Generator for rows of the stop_times file | [
"Generator",
"for",
"rows",
"of",
"the",
"stop_times",
"file"
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/trip.py#L362-L366 |
239,020 | google/transitfeed | transitfeed/trip.py | Trip.GetPattern | def GetPattern(self):
"""Return a tuple of Stop objects, in the order visited"""
stoptimes = self.GetStopTimes()
return tuple(st.stop for st in stoptimes) | python | def GetPattern(self):
stoptimes = self.GetStopTimes()
return tuple(st.stop for st in stoptimes) | [
"def",
"GetPattern",
"(",
"self",
")",
":",
"stoptimes",
"=",
"self",
".",
"GetStopTimes",
"(",
")",
"return",
"tuple",
"(",
"st",
".",
"stop",
"for",
"st",
"in",
"stoptimes",
")"
] | Return a tuple of Stop objects, in the order visited | [
"Return",
"a",
"tuple",
"of",
"Stop",
"objects",
"in",
"the",
"order",
"visited"
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/trip.py#L374-L377 |
239,021 | google/transitfeed | transitfeed/trip.py | Trip.AddHeadwayPeriodObject | def AddHeadwayPeriodObject(self, headway_period, problem_reporter):
"""Deprecated. Please use AddFrequencyObject instead."""
warnings.warn("No longer supported. The HeadwayPeriod class was renamed to "
"Frequency, and all related functions were renamed "
"accordingly.", DeprecationWarning)
self.AddFrequencyObject(frequency, problem_reporter) | python | def AddHeadwayPeriodObject(self, headway_period, problem_reporter):
warnings.warn("No longer supported. The HeadwayPeriod class was renamed to "
"Frequency, and all related functions were renamed "
"accordingly.", DeprecationWarning)
self.AddFrequencyObject(frequency, problem_reporter) | [
"def",
"AddHeadwayPeriodObject",
"(",
"self",
",",
"headway_period",
",",
"problem_reporter",
")",
":",
"warnings",
".",
"warn",
"(",
"\"No longer supported. The HeadwayPeriod class was renamed to \"",
"\"Frequency, and all related functions were renamed \"",
"\"accordingly.\"",
",... | Deprecated. Please use AddFrequencyObject instead. | [
"Deprecated",
".",
"Please",
"use",
"AddFrequencyObject",
"instead",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/trip.py#L379-L384 |
239,022 | google/transitfeed | transitfeed/trip.py | Trip.AddFrequencyObject | def AddFrequencyObject(self, frequency, problem_reporter):
"""Add a Frequency object to this trip's list of Frequencies."""
if frequency is not None:
self.AddFrequency(frequency.StartTime(),
frequency.EndTime(),
frequency.HeadwaySecs(),
frequency.ExactTimes(),
problem_reporter) | python | def AddFrequencyObject(self, frequency, problem_reporter):
if frequency is not None:
self.AddFrequency(frequency.StartTime(),
frequency.EndTime(),
frequency.HeadwaySecs(),
frequency.ExactTimes(),
problem_reporter) | [
"def",
"AddFrequencyObject",
"(",
"self",
",",
"frequency",
",",
"problem_reporter",
")",
":",
"if",
"frequency",
"is",
"not",
"None",
":",
"self",
".",
"AddFrequency",
"(",
"frequency",
".",
"StartTime",
"(",
")",
",",
"frequency",
".",
"EndTime",
"(",
")... | Add a Frequency object to this trip's list of Frequencies. | [
"Add",
"a",
"Frequency",
"object",
"to",
"this",
"trip",
"s",
"list",
"of",
"Frequencies",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/trip.py#L386-L393 |
239,023 | google/transitfeed | transitfeed/trip.py | Trip.AddHeadwayPeriod | def AddHeadwayPeriod(self, start_time, end_time, headway_secs,
problem_reporter=problems_module.default_problem_reporter):
"""Deprecated. Please use AddFrequency instead."""
warnings.warn("No longer supported. The HeadwayPeriod class was renamed to "
"Frequency, and all related functions were renamed "
"accordingly.", DeprecationWarning)
self.AddFrequency(start_time, end_time, headway_secs, problem_reporter) | python | def AddHeadwayPeriod(self, start_time, end_time, headway_secs,
problem_reporter=problems_module.default_problem_reporter):
warnings.warn("No longer supported. The HeadwayPeriod class was renamed to "
"Frequency, and all related functions were renamed "
"accordingly.", DeprecationWarning)
self.AddFrequency(start_time, end_time, headway_secs, problem_reporter) | [
"def",
"AddHeadwayPeriod",
"(",
"self",
",",
"start_time",
",",
"end_time",
",",
"headway_secs",
",",
"problem_reporter",
"=",
"problems_module",
".",
"default_problem_reporter",
")",
":",
"warnings",
".",
"warn",
"(",
"\"No longer supported. The HeadwayPeriod class was r... | Deprecated. Please use AddFrequency instead. | [
"Deprecated",
".",
"Please",
"use",
"AddFrequency",
"instead",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/trip.py#L395-L401 |
239,024 | google/transitfeed | transitfeed/trip.py | Trip.Validate | def Validate(self, problems, validate_children=True):
"""Validate attributes of this object.
Check that this object has all required values set to a valid value without
reference to the rest of the schedule. If the _schedule attribute is set
then check that references such as route_id and service_id are correct.
Args:
problems: A ProblemReporter object
validate_children: if True and the _schedule attribute is set than call
ValidateChildren
"""
self.ValidateRouteId(problems)
self.ValidateServicePeriod(problems)
self.ValidateDirectionId(problems)
self.ValidateTripId(problems)
self.ValidateShapeIdsExistInShapeList(problems)
self.ValidateRouteIdExistsInRouteList(problems)
self.ValidateServiceIdExistsInServiceList(problems)
self.ValidateBikesAllowed(problems)
self.ValidateWheelchairAccessible(problems)
if self._schedule and validate_children:
self.ValidateChildren(problems) | python | def Validate(self, problems, validate_children=True):
self.ValidateRouteId(problems)
self.ValidateServicePeriod(problems)
self.ValidateDirectionId(problems)
self.ValidateTripId(problems)
self.ValidateShapeIdsExistInShapeList(problems)
self.ValidateRouteIdExistsInRouteList(problems)
self.ValidateServiceIdExistsInServiceList(problems)
self.ValidateBikesAllowed(problems)
self.ValidateWheelchairAccessible(problems)
if self._schedule and validate_children:
self.ValidateChildren(problems) | [
"def",
"Validate",
"(",
"self",
",",
"problems",
",",
"validate_children",
"=",
"True",
")",
":",
"self",
".",
"ValidateRouteId",
"(",
"problems",
")",
"self",
".",
"ValidateServicePeriod",
"(",
"problems",
")",
"self",
".",
"ValidateDirectionId",
"(",
"proble... | Validate attributes of this object.
Check that this object has all required values set to a valid value without
reference to the rest of the schedule. If the _schedule attribute is set
then check that references such as route_id and service_id are correct.
Args:
problems: A ProblemReporter object
validate_children: if True and the _schedule attribute is set than call
ValidateChildren | [
"Validate",
"attributes",
"of",
"this",
"object",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/trip.py#L551-L573 |
239,025 | google/transitfeed | transitfeed/trip.py | Trip.ValidateChildren | def ValidateChildren(self, problems):
"""Validate StopTimes and headways of this trip."""
assert self._schedule, "Trip must be in a schedule to ValidateChildren"
# TODO: validate distance values in stop times (if applicable)
self.ValidateNoDuplicateStopSequences(problems)
stoptimes = self.GetStopTimes(problems)
stoptimes.sort(key=lambda x: x.stop_sequence)
self.ValidateTripStartAndEndTimes(problems, stoptimes)
self.ValidateStopTimesSequenceHasIncreasingTimeAndDistance(problems,
stoptimes)
self.ValidateShapeDistTraveledSmallerThanMaxShapeDistance(problems,
stoptimes)
self.ValidateDistanceFromStopToShape(problems, stoptimes)
self.ValidateFrequencies(problems) | python | def ValidateChildren(self, problems):
assert self._schedule, "Trip must be in a schedule to ValidateChildren"
# TODO: validate distance values in stop times (if applicable)
self.ValidateNoDuplicateStopSequences(problems)
stoptimes = self.GetStopTimes(problems)
stoptimes.sort(key=lambda x: x.stop_sequence)
self.ValidateTripStartAndEndTimes(problems, stoptimes)
self.ValidateStopTimesSequenceHasIncreasingTimeAndDistance(problems,
stoptimes)
self.ValidateShapeDistTraveledSmallerThanMaxShapeDistance(problems,
stoptimes)
self.ValidateDistanceFromStopToShape(problems, stoptimes)
self.ValidateFrequencies(problems) | [
"def",
"ValidateChildren",
"(",
"self",
",",
"problems",
")",
":",
"assert",
"self",
".",
"_schedule",
",",
"\"Trip must be in a schedule to ValidateChildren\"",
"# TODO: validate distance values in stop times (if applicable)",
"self",
".",
"ValidateNoDuplicateStopSequences",
"("... | Validate StopTimes and headways of this trip. | [
"Validate",
"StopTimes",
"and",
"headways",
"of",
"this",
"trip",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/trip.py#L697-L711 |
239,026 | google/transitfeed | transitfeed/stoptime.py | StopTime.GetFieldValuesTuple | def GetFieldValuesTuple(self, trip_id):
"""Return a tuple that outputs a row of _FIELD_NAMES to be written to a
GTFS file.
Arguments:
trip_id: The trip_id of the trip to which this StopTime corresponds.
It must be provided, as it is not stored in StopTime.
"""
result = []
for fn in self._FIELD_NAMES:
if fn == 'trip_id':
result.append(trip_id)
else:
# Since we'll be writting to an output file, we want empty values to be
# outputted as an empty string
result.append(getattr(self, fn) or '' )
return tuple(result) | python | def GetFieldValuesTuple(self, trip_id):
result = []
for fn in self._FIELD_NAMES:
if fn == 'trip_id':
result.append(trip_id)
else:
# Since we'll be writting to an output file, we want empty values to be
# outputted as an empty string
result.append(getattr(self, fn) or '' )
return tuple(result) | [
"def",
"GetFieldValuesTuple",
"(",
"self",
",",
"trip_id",
")",
":",
"result",
"=",
"[",
"]",
"for",
"fn",
"in",
"self",
".",
"_FIELD_NAMES",
":",
"if",
"fn",
"==",
"'trip_id'",
":",
"result",
".",
"append",
"(",
"trip_id",
")",
"else",
":",
"# Since w... | Return a tuple that outputs a row of _FIELD_NAMES to be written to a
GTFS file.
Arguments:
trip_id: The trip_id of the trip to which this StopTime corresponds.
It must be provided, as it is not stored in StopTime. | [
"Return",
"a",
"tuple",
"that",
"outputs",
"a",
"row",
"of",
"_FIELD_NAMES",
"to",
"be",
"written",
"to",
"a",
"GTFS",
"file",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/stoptime.py#L165-L181 |
239,027 | google/transitfeed | transitfeed/stoptime.py | StopTime.GetSqlValuesTuple | def GetSqlValuesTuple(self, trip_id):
"""Return a tuple that outputs a row of _FIELD_NAMES to be written to a
SQLite database.
Arguments:
trip_id: The trip_id of the trip to which this StopTime corresponds.
It must be provided, as it is not stored in StopTime.
"""
result = []
for fn in self._SQL_FIELD_NAMES:
if fn == 'trip_id':
result.append(trip_id)
else:
# Since we'll be writting to SQLite, we want empty values to be
# outputted as NULL string (contrary to what happens in
# GetFieldValuesTuple)
result.append(getattr(self, fn))
return tuple(result) | python | def GetSqlValuesTuple(self, trip_id):
result = []
for fn in self._SQL_FIELD_NAMES:
if fn == 'trip_id':
result.append(trip_id)
else:
# Since we'll be writting to SQLite, we want empty values to be
# outputted as NULL string (contrary to what happens in
# GetFieldValuesTuple)
result.append(getattr(self, fn))
return tuple(result) | [
"def",
"GetSqlValuesTuple",
"(",
"self",
",",
"trip_id",
")",
":",
"result",
"=",
"[",
"]",
"for",
"fn",
"in",
"self",
".",
"_SQL_FIELD_NAMES",
":",
"if",
"fn",
"==",
"'trip_id'",
":",
"result",
".",
"append",
"(",
"trip_id",
")",
"else",
":",
"# Since... | Return a tuple that outputs a row of _FIELD_NAMES to be written to a
SQLite database.
Arguments:
trip_id: The trip_id of the trip to which this StopTime corresponds.
It must be provided, as it is not stored in StopTime. | [
"Return",
"a",
"tuple",
"that",
"outputs",
"a",
"row",
"of",
"_FIELD_NAMES",
"to",
"be",
"written",
"to",
"a",
"SQLite",
"database",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/stoptime.py#L183-L201 |
239,028 | google/transitfeed | transitfeed/stoptime.py | StopTime.GetTimeSecs | def GetTimeSecs(self):
"""Return the first of arrival_secs and departure_secs that is not None.
If both are None return None."""
if self.arrival_secs != None:
return self.arrival_secs
elif self.departure_secs != None:
return self.departure_secs
else:
return None | python | def GetTimeSecs(self):
if self.arrival_secs != None:
return self.arrival_secs
elif self.departure_secs != None:
return self.departure_secs
else:
return None | [
"def",
"GetTimeSecs",
"(",
"self",
")",
":",
"if",
"self",
".",
"arrival_secs",
"!=",
"None",
":",
"return",
"self",
".",
"arrival_secs",
"elif",
"self",
".",
"departure_secs",
"!=",
"None",
":",
"return",
"self",
".",
"departure_secs",
"else",
":",
"retur... | Return the first of arrival_secs and departure_secs that is not None.
If both are None return None. | [
"Return",
"the",
"first",
"of",
"arrival_secs",
"and",
"departure_secs",
"that",
"is",
"not",
"None",
".",
"If",
"both",
"are",
"None",
"return",
"None",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/stoptime.py#L203-L211 |
239,029 | equinor/segyio | python/segyio/create.py | create | def create(filename, spec):
"""Create a new segy file.
Create a new segy file with the geometry and properties given by `spec`.
This enables creating SEGY files from your data. The created file supports
all segyio modes, but has an emphasis on writing. The spec must be
complete, otherwise an exception will be raised. A default, empty spec can
be created with ``segyio.spec()``.
Very little data is written to the file, so just calling create is not
sufficient to re-read the file with segyio. Rather, every trace header and
trace must be written to the file to be considered complete.
Create should be used together with python's ``with`` statement. This ensure
the data is written. Please refer to the examples.
The ``segyio.spec()`` function will default sorting, offsets and everything
in the mandatory group, except format and samples, and requires the caller
to fill in *all* the fields in either of the exclusive groups.
If any field is missing from the first exclusive group, and the tracecount
is set, the resulting file will be considered unstructured. If the
tracecount is set, and all fields of the first exclusive group are
specified, the file is considered structured and the tracecount is inferred
from the xlines/ilines/offsets. The offsets are defaulted to ``[1]`` by
``segyio.spec()``.
Parameters
----------
filename : str
Path to file to create
spec : segyio.spec
Structure of the segy file
Returns
-------
file : segyio.SegyFile
An open segyio file handle, similar to that returned by `segyio.open`
See also
--------
segyio.spec : template for the `spec` argument
Notes
-----
.. versionadded:: 1.1
.. versionchanged:: 1.4
Support for creating unstructured files
.. versionchanged:: 1.8
Support for creating lsb files
The ``spec`` is any object that has the following attributes
Mandatory::
iline : int or segyio.BinField
xline : int or segyio.BinField
samples : array of int
format : { 1, 5 }
1 = IBM float, 5 = IEEE float
Exclusive::
ilines : array_like of int
xlines : array_like of int
offsets : array_like of int
sorting : int or segyio.TraceSortingFormat
OR
tracecount : int
Optional::
ext_headers : int
endian : str { 'big', 'msb', 'little', 'lsb' }
defaults to 'big'
Examples
--------
Create a file:
>>> spec = segyio.spec()
>>> spec.ilines = [1, 2, 3, 4]
>>> spec.xlines = [11, 12, 13]
>>> spec.samples = list(range(50))
>>> spec.sorting = 2
>>> spec.format = 1
>>> with segyio.create(path, spec) as f:
... ## fill the file with data
... pass
...
Copy a file, but shorten all traces by 50 samples:
>>> with segyio.open(srcpath) as src:
... spec = segyio.spec()
... spec.sorting = src.sorting
... spec.format = src.format
... spec.samples = src.samples[:len(src.samples) - 50]
... spec.ilines = src.ilines
... spec.xline = src.xlines
... with segyio.create(dstpath, spec) as dst:
... dst.text[0] = src.text[0]
... dst.bin = src.bin
... dst.header = src.header
... dst.trace = src.trace
Copy a file, but shift samples time by 50:
>>> with segyio.open(srcpath) as src:
... delrt = 50
... spec = segyio.spec()
... spec.samples = src.samples + delrt
... spec.ilines = src.ilines
... spec.xline = src.xlines
... with segyio.create(dstpath, spec) as dst:
... dst.text[0] = src.text[0]
... dst.bin = src.bin
... dst.header = src.header
... dst.header = { TraceField.DelayRecordingTime: delrt }
... dst.trace = src.trace
Copy a file, but shorten all traces by 50 samples (since v1.4):
>>> with segyio.open(srcpath) as src:
... spec = segyio.tools.metadata(src)
... spec.samples = spec.samples[:len(spec.samples) - 50]
... with segyio.create(dstpath, spec) as dst:
... dst.text[0] = src.text[0]
... dst.bin = src.bin
... dst.header = src.header
... dst.trace = src.trace
"""
from . import _segyio
if not structured(spec):
tracecount = spec.tracecount
else:
tracecount = len(spec.ilines) * len(spec.xlines) * len(spec.offsets)
ext_headers = spec.ext_headers if hasattr(spec, 'ext_headers') else 0
samples = numpy.asarray(spec.samples)
endians = {
'lsb': 256, # (1 << 8)
'little': 256,
'msb': 0,
'big': 0,
}
endian = spec.endian if hasattr(spec, 'endian') else 'big'
if endian is None:
endian = 'big'
if endian not in endians:
problem = 'unknown endianness {}, expected one of: '
opts = ' '.join(endians.keys())
raise ValueError(problem.format(endian) + opts)
fd = _segyio.segyiofd(str(filename), 'w+', endians[endian])
fd.segymake(
samples = len(samples),
tracecount = tracecount,
format = int(spec.format),
ext_headers = int(ext_headers),
)
f = segyio.SegyFile(fd,
filename = str(filename),
mode = 'w+',
iline = int(spec.iline),
xline = int(spec.xline),
endian = endian,
)
f._samples = samples
if structured(spec):
sorting = spec.sorting if hasattr(spec, 'sorting') else None
if sorting is None:
sorting = TraceSortingFormat.INLINE_SORTING
f.interpret(spec.ilines, spec.xlines, spec.offsets, sorting)
f.text[0] = default_text_header(f._il, f._xl, segyio.TraceField.offset)
if len(samples) == 1:
interval = int(samples[0] * 1000)
else:
interval = int((samples[1] - samples[0]) * 1000)
f.bin.update(
ntrpr = tracecount,
nart = tracecount,
hdt = interval,
dto = interval,
hns = len(samples),
nso = len(samples),
format = int(spec.format),
exth = ext_headers,
)
return f | python | def create(filename, spec):
from . import _segyio
if not structured(spec):
tracecount = spec.tracecount
else:
tracecount = len(spec.ilines) * len(spec.xlines) * len(spec.offsets)
ext_headers = spec.ext_headers if hasattr(spec, 'ext_headers') else 0
samples = numpy.asarray(spec.samples)
endians = {
'lsb': 256, # (1 << 8)
'little': 256,
'msb': 0,
'big': 0,
}
endian = spec.endian if hasattr(spec, 'endian') else 'big'
if endian is None:
endian = 'big'
if endian not in endians:
problem = 'unknown endianness {}, expected one of: '
opts = ' '.join(endians.keys())
raise ValueError(problem.format(endian) + opts)
fd = _segyio.segyiofd(str(filename), 'w+', endians[endian])
fd.segymake(
samples = len(samples),
tracecount = tracecount,
format = int(spec.format),
ext_headers = int(ext_headers),
)
f = segyio.SegyFile(fd,
filename = str(filename),
mode = 'w+',
iline = int(spec.iline),
xline = int(spec.xline),
endian = endian,
)
f._samples = samples
if structured(spec):
sorting = spec.sorting if hasattr(spec, 'sorting') else None
if sorting is None:
sorting = TraceSortingFormat.INLINE_SORTING
f.interpret(spec.ilines, spec.xlines, spec.offsets, sorting)
f.text[0] = default_text_header(f._il, f._xl, segyio.TraceField.offset)
if len(samples) == 1:
interval = int(samples[0] * 1000)
else:
interval = int((samples[1] - samples[0]) * 1000)
f.bin.update(
ntrpr = tracecount,
nart = tracecount,
hdt = interval,
dto = interval,
hns = len(samples),
nso = len(samples),
format = int(spec.format),
exth = ext_headers,
)
return f | [
"def",
"create",
"(",
"filename",
",",
"spec",
")",
":",
"from",
".",
"import",
"_segyio",
"if",
"not",
"structured",
"(",
"spec",
")",
":",
"tracecount",
"=",
"spec",
".",
"tracecount",
"else",
":",
"tracecount",
"=",
"len",
"(",
"spec",
".",
"ilines"... | Create a new segy file.
Create a new segy file with the geometry and properties given by `spec`.
This enables creating SEGY files from your data. The created file supports
all segyio modes, but has an emphasis on writing. The spec must be
complete, otherwise an exception will be raised. A default, empty spec can
be created with ``segyio.spec()``.
Very little data is written to the file, so just calling create is not
sufficient to re-read the file with segyio. Rather, every trace header and
trace must be written to the file to be considered complete.
Create should be used together with python's ``with`` statement. This ensure
the data is written. Please refer to the examples.
The ``segyio.spec()`` function will default sorting, offsets and everything
in the mandatory group, except format and samples, and requires the caller
to fill in *all* the fields in either of the exclusive groups.
If any field is missing from the first exclusive group, and the tracecount
is set, the resulting file will be considered unstructured. If the
tracecount is set, and all fields of the first exclusive group are
specified, the file is considered structured and the tracecount is inferred
from the xlines/ilines/offsets. The offsets are defaulted to ``[1]`` by
``segyio.spec()``.
Parameters
----------
filename : str
Path to file to create
spec : segyio.spec
Structure of the segy file
Returns
-------
file : segyio.SegyFile
An open segyio file handle, similar to that returned by `segyio.open`
See also
--------
segyio.spec : template for the `spec` argument
Notes
-----
.. versionadded:: 1.1
.. versionchanged:: 1.4
Support for creating unstructured files
.. versionchanged:: 1.8
Support for creating lsb files
The ``spec`` is any object that has the following attributes
Mandatory::
iline : int or segyio.BinField
xline : int or segyio.BinField
samples : array of int
format : { 1, 5 }
1 = IBM float, 5 = IEEE float
Exclusive::
ilines : array_like of int
xlines : array_like of int
offsets : array_like of int
sorting : int or segyio.TraceSortingFormat
OR
tracecount : int
Optional::
ext_headers : int
endian : str { 'big', 'msb', 'little', 'lsb' }
defaults to 'big'
Examples
--------
Create a file:
>>> spec = segyio.spec()
>>> spec.ilines = [1, 2, 3, 4]
>>> spec.xlines = [11, 12, 13]
>>> spec.samples = list(range(50))
>>> spec.sorting = 2
>>> spec.format = 1
>>> with segyio.create(path, spec) as f:
... ## fill the file with data
... pass
...
Copy a file, but shorten all traces by 50 samples:
>>> with segyio.open(srcpath) as src:
... spec = segyio.spec()
... spec.sorting = src.sorting
... spec.format = src.format
... spec.samples = src.samples[:len(src.samples) - 50]
... spec.ilines = src.ilines
... spec.xline = src.xlines
... with segyio.create(dstpath, spec) as dst:
... dst.text[0] = src.text[0]
... dst.bin = src.bin
... dst.header = src.header
... dst.trace = src.trace
Copy a file, but shift samples time by 50:
>>> with segyio.open(srcpath) as src:
... delrt = 50
... spec = segyio.spec()
... spec.samples = src.samples + delrt
... spec.ilines = src.ilines
... spec.xline = src.xlines
... with segyio.create(dstpath, spec) as dst:
... dst.text[0] = src.text[0]
... dst.bin = src.bin
... dst.header = src.header
... dst.header = { TraceField.DelayRecordingTime: delrt }
... dst.trace = src.trace
Copy a file, but shorten all traces by 50 samples (since v1.4):
>>> with segyio.open(srcpath) as src:
... spec = segyio.tools.metadata(src)
... spec.samples = spec.samples[:len(spec.samples) - 50]
... with segyio.create(dstpath, spec) as dst:
... dst.text[0] = src.text[0]
... dst.bin = src.bin
... dst.header = src.header
... dst.trace = src.trace | [
"Create",
"a",
"new",
"segy",
"file",
"."
] | 58fd449947ccd330b9af0699d6b8710550d34e8e | https://github.com/equinor/segyio/blob/58fd449947ccd330b9af0699d6b8710550d34e8e/python/segyio/create.py#L38-L246 |
239,030 | equinor/segyio | python/segyio/su/file.py | open | def open(filename, mode = 'r', iline = 189,
xline = 193,
strict = True,
ignore_geometry = False,
endian = 'big' ):
"""Open a seismic unix file.
Behaves identically to open(), except it expects the seismic unix format,
not SEG-Y.
Parameters
----------
filename : str
Path to file to open
mode : {'r', 'r+'}
File access mode, read-only ('r', default) or read-write ('r+')
iline : int or segyio.TraceField
Inline number field in the trace headers. Defaults to 189 as per the
SEG-Y rev1 specification
xline : int or segyio.TraceField
Crossline number field in the trace headers. Defaults to 193 as per the
SEG-Y rev1 specification
strict : bool, optional
Abort if a geometry cannot be inferred. Defaults to True.
ignore_geometry : bool, optional
Opt out on building geometry information, useful for e.g. shot
organised files. Defaults to False.
endian : {'big', 'msb', 'little', 'lsb'}
File endianness, big/msb (default) or little/lsb
Returns
-------
file : segyio.su.file
An open seismic unix file handle
Raises
------
ValueError
If the mode string contains 'w', as it would truncate the file
See also
--------
segyio.open : SEG-Y open
Notes
-----
.. versionadded:: 1.8
"""
if 'w' in mode:
problem = 'w in mode would truncate the file'
solution = 'use r+ to open in read-write'
raise ValueError(', '.join((problem, solution)))
endians = {
'little': 256, # (1 << 8)
'lsb': 256,
'big': 0,
'msb': 0,
}
if endian not in endians:
problem = 'unknown endianness, must be one of: '
candidates = ' '.join(endians.keys())
raise ValueError(problem + candidates)
from .. import _segyio
fd = _segyio.segyiofd(str(filename), mode, endians[endian])
fd.suopen()
metrics = fd.metrics()
f = sufile(
fd,
filename = str(filename),
mode = mode,
iline = iline,
xline = xline,
)
h0 = f.header[0]
dt = h0[words.dt] / 1000.0
t0 = h0[words.delrt]
samples = metrics['samplecount']
f._samples = (numpy.arange(samples) * dt) + t0
if ignore_geometry:
return f
return infer_geometry(f, metrics, iline, xline, strict) | python | def open(filename, mode = 'r', iline = 189,
xline = 193,
strict = True,
ignore_geometry = False,
endian = 'big' ):
if 'w' in mode:
problem = 'w in mode would truncate the file'
solution = 'use r+ to open in read-write'
raise ValueError(', '.join((problem, solution)))
endians = {
'little': 256, # (1 << 8)
'lsb': 256,
'big': 0,
'msb': 0,
}
if endian not in endians:
problem = 'unknown endianness, must be one of: '
candidates = ' '.join(endians.keys())
raise ValueError(problem + candidates)
from .. import _segyio
fd = _segyio.segyiofd(str(filename), mode, endians[endian])
fd.suopen()
metrics = fd.metrics()
f = sufile(
fd,
filename = str(filename),
mode = mode,
iline = iline,
xline = xline,
)
h0 = f.header[0]
dt = h0[words.dt] / 1000.0
t0 = h0[words.delrt]
samples = metrics['samplecount']
f._samples = (numpy.arange(samples) * dt) + t0
if ignore_geometry:
return f
return infer_geometry(f, metrics, iline, xline, strict) | [
"def",
"open",
"(",
"filename",
",",
"mode",
"=",
"'r'",
",",
"iline",
"=",
"189",
",",
"xline",
"=",
"193",
",",
"strict",
"=",
"True",
",",
"ignore_geometry",
"=",
"False",
",",
"endian",
"=",
"'big'",
")",
":",
"if",
"'w'",
"in",
"mode",
":",
... | Open a seismic unix file.
Behaves identically to open(), except it expects the seismic unix format,
not SEG-Y.
Parameters
----------
filename : str
Path to file to open
mode : {'r', 'r+'}
File access mode, read-only ('r', default) or read-write ('r+')
iline : int or segyio.TraceField
Inline number field in the trace headers. Defaults to 189 as per the
SEG-Y rev1 specification
xline : int or segyio.TraceField
Crossline number field in the trace headers. Defaults to 193 as per the
SEG-Y rev1 specification
strict : bool, optional
Abort if a geometry cannot be inferred. Defaults to True.
ignore_geometry : bool, optional
Opt out on building geometry information, useful for e.g. shot
organised files. Defaults to False.
endian : {'big', 'msb', 'little', 'lsb'}
File endianness, big/msb (default) or little/lsb
Returns
-------
file : segyio.su.file
An open seismic unix file handle
Raises
------
ValueError
If the mode string contains 'w', as it would truncate the file
See also
--------
segyio.open : SEG-Y open
Notes
-----
.. versionadded:: 1.8 | [
"Open",
"a",
"seismic",
"unix",
"file",
"."
] | 58fd449947ccd330b9af0699d6b8710550d34e8e | https://github.com/equinor/segyio/blob/58fd449947ccd330b9af0699d6b8710550d34e8e/python/segyio/su/file.py#L23-L118 |
239,031 | equinor/segyio | python/segyio/tools.py | create_text_header | def create_text_header(lines):
"""Format textual header
Create a "correct" SEG-Y textual header. Every line will be prefixed with
C## and there are 40 lines. The input must be a dictionary with the line
number[1-40] as a key. The value for each key should be up to 76 character
long string.
Parameters
----------
lines : dict
`lines` dictionary with fields:
- ``no`` : line number (`int`)
- ``line`` : line (`str`)
Returns
-------
text : str
"""
rows = []
for line_no in range(1, 41):
line = ""
if line_no in lines:
line = lines[line_no]
row = "C{0:>2} {1:76}".format(line_no, line)
rows.append(row)
rows = ''.join(rows)
return rows | python | def create_text_header(lines):
rows = []
for line_no in range(1, 41):
line = ""
if line_no in lines:
line = lines[line_no]
row = "C{0:>2} {1:76}".format(line_no, line)
rows.append(row)
rows = ''.join(rows)
return rows | [
"def",
"create_text_header",
"(",
"lines",
")",
":",
"rows",
"=",
"[",
"]",
"for",
"line_no",
"in",
"range",
"(",
"1",
",",
"41",
")",
":",
"line",
"=",
"\"\"",
"if",
"line_no",
"in",
"lines",
":",
"line",
"=",
"lines",
"[",
"line_no",
"]",
"row",
... | Format textual header
Create a "correct" SEG-Y textual header. Every line will be prefixed with
C## and there are 40 lines. The input must be a dictionary with the line
number[1-40] as a key. The value for each key should be up to 76 character
long string.
Parameters
----------
lines : dict
`lines` dictionary with fields:
- ``no`` : line number (`int`)
- ``line`` : line (`str`)
Returns
-------
text : str | [
"Format",
"textual",
"header"
] | 58fd449947ccd330b9af0699d6b8710550d34e8e | https://github.com/equinor/segyio/blob/58fd449947ccd330b9af0699d6b8710550d34e8e/python/segyio/tools.py#L65-L98 |
239,032 | equinor/segyio | python/segyio/tools.py | wrap | def wrap(s, width=80):
"""
Formats the text input with newlines given the user specified width for
each line.
Parameters
----------
s : str
width : int
Returns
-------
text : str
Notes
-----
.. versionadded:: 1.1
"""
return '\n'.join(textwrap.wrap(str(s), width=width)) | python | def wrap(s, width=80):
return '\n'.join(textwrap.wrap(str(s), width=width)) | [
"def",
"wrap",
"(",
"s",
",",
"width",
"=",
"80",
")",
":",
"return",
"'\\n'",
".",
"join",
"(",
"textwrap",
".",
"wrap",
"(",
"str",
"(",
"s",
")",
",",
"width",
"=",
"width",
")",
")"
] | Formats the text input with newlines given the user specified width for
each line.
Parameters
----------
s : str
width : int
Returns
-------
text : str
Notes
-----
.. versionadded:: 1.1 | [
"Formats",
"the",
"text",
"input",
"with",
"newlines",
"given",
"the",
"user",
"specified",
"width",
"for",
"each",
"line",
"."
] | 58fd449947ccd330b9af0699d6b8710550d34e8e | https://github.com/equinor/segyio/blob/58fd449947ccd330b9af0699d6b8710550d34e8e/python/segyio/tools.py#L100-L122 |
239,033 | equinor/segyio | python/segyio/tools.py | native | def native(data,
format = segyio.SegySampleFormat.IBM_FLOAT_4_BYTE,
copy = True):
"""Convert numpy array to native float
Converts a numpy array from raw segy trace data to native floats. Works for numpy ndarrays.
Parameters
----------
data : numpy.ndarray
format : int or segyio.SegySampleFormat
copy : bool
If True, convert on a copy, and leave the input array unmodified
Returns
-------
data : numpy.ndarray
Notes
-----
.. versionadded:: 1.1
Examples
--------
Convert mmap'd trace to native float:
>>> d = np.memmap('file.sgy', offset = 3600, dtype = np.uintc)
>>> samples = 1500
>>> trace = segyio.tools.native(d[240:240+samples])
"""
data = data.view( dtype = np.single )
if copy:
data = np.copy( data )
format = int(segyio.SegySampleFormat(format))
return segyio._segyio.native(data, format) | python | def native(data,
format = segyio.SegySampleFormat.IBM_FLOAT_4_BYTE,
copy = True):
data = data.view( dtype = np.single )
if copy:
data = np.copy( data )
format = int(segyio.SegySampleFormat(format))
return segyio._segyio.native(data, format) | [
"def",
"native",
"(",
"data",
",",
"format",
"=",
"segyio",
".",
"SegySampleFormat",
".",
"IBM_FLOAT_4_BYTE",
",",
"copy",
"=",
"True",
")",
":",
"data",
"=",
"data",
".",
"view",
"(",
"dtype",
"=",
"np",
".",
"single",
")",
"if",
"copy",
":",
"data"... | Convert numpy array to native float
Converts a numpy array from raw segy trace data to native floats. Works for numpy ndarrays.
Parameters
----------
data : numpy.ndarray
format : int or segyio.SegySampleFormat
copy : bool
If True, convert on a copy, and leave the input array unmodified
Returns
-------
data : numpy.ndarray
Notes
-----
.. versionadded:: 1.1
Examples
--------
Convert mmap'd trace to native float:
>>> d = np.memmap('file.sgy', offset = 3600, dtype = np.uintc)
>>> samples = 1500
>>> trace = segyio.tools.native(d[240:240+samples]) | [
"Convert",
"numpy",
"array",
"to",
"native",
"float"
] | 58fd449947ccd330b9af0699d6b8710550d34e8e | https://github.com/equinor/segyio/blob/58fd449947ccd330b9af0699d6b8710550d34e8e/python/segyio/tools.py#L125-L166 |
239,034 | equinor/segyio | python/segyio/tools.py | cube | def cube(f):
"""Read a full cube from a file
Takes an open segy file (created with segyio.open) or a file name.
If the file is a prestack file, the cube returned has the dimensions
``(fast, slow, offset, sample)``. If it is post-stack (only the one
offset), the dimensions are normalised to ``(fast, slow, sample)``
Parameters
----------
f : str or segyio.SegyFile
Returns
-------
cube : numpy.ndarray
Notes
-----
.. versionadded:: 1.1
"""
if not isinstance(f, segyio.SegyFile):
with segyio.open(f) as fl:
return cube(fl)
ilsort = f.sorting == segyio.TraceSortingFormat.INLINE_SORTING
fast = f.ilines if ilsort else f.xlines
slow = f.xlines if ilsort else f.ilines
fast, slow, offs = len(fast), len(slow), len(f.offsets)
smps = len(f.samples)
dims = (fast, slow, smps) if offs == 1 else (fast, slow, offs, smps)
return f.trace.raw[:].reshape(dims) | python | def cube(f):
if not isinstance(f, segyio.SegyFile):
with segyio.open(f) as fl:
return cube(fl)
ilsort = f.sorting == segyio.TraceSortingFormat.INLINE_SORTING
fast = f.ilines if ilsort else f.xlines
slow = f.xlines if ilsort else f.ilines
fast, slow, offs = len(fast), len(slow), len(f.offsets)
smps = len(f.samples)
dims = (fast, slow, smps) if offs == 1 else (fast, slow, offs, smps)
return f.trace.raw[:].reshape(dims) | [
"def",
"cube",
"(",
"f",
")",
":",
"if",
"not",
"isinstance",
"(",
"f",
",",
"segyio",
".",
"SegyFile",
")",
":",
"with",
"segyio",
".",
"open",
"(",
"f",
")",
"as",
"fl",
":",
"return",
"cube",
"(",
"fl",
")",
"ilsort",
"=",
"f",
".",
"sorting... | Read a full cube from a file
Takes an open segy file (created with segyio.open) or a file name.
If the file is a prestack file, the cube returned has the dimensions
``(fast, slow, offset, sample)``. If it is post-stack (only the one
offset), the dimensions are normalised to ``(fast, slow, sample)``
Parameters
----------
f : str or segyio.SegyFile
Returns
-------
cube : numpy.ndarray
Notes
-----
.. versionadded:: 1.1 | [
"Read",
"a",
"full",
"cube",
"from",
"a",
"file"
] | 58fd449947ccd330b9af0699d6b8710550d34e8e | https://github.com/equinor/segyio/blob/58fd449947ccd330b9af0699d6b8710550d34e8e/python/segyio/tools.py#L203-L239 |
239,035 | equinor/segyio | python/segyio/tools.py | rotation | def rotation(f, line = 'fast'):
""" Find rotation of the survey
Find the clock-wise rotation and origin of `line` as ``(rot, cdpx, cdpy)``
The clock-wise rotation is defined as the angle in radians between line
given by the first and last trace of the first line and the axis that gives
increasing CDP-Y, in the direction that gives increasing CDP-X.
By default, the first line is the 'fast' direction, which is inlines if the
file is inline sorted, and crossline if it's crossline sorted.
Parameters
----------
f : SegyFile
line : { 'fast', 'slow', 'iline', 'xline' }
Returns
-------
rotation : float
cdpx : int
cdpy : int
Notes
-----
.. versionadded:: 1.2
"""
if f.unstructured:
raise ValueError("Rotation requires a structured file")
lines = { 'fast': f.fast,
'slow': f.slow,
'iline': f.iline,
'xline': f.xline,
}
if line not in lines:
error = "Unknown line {}".format(line)
solution = "Must be any of: {}".format(' '.join(lines.keys()))
raise ValueError('{} {}'.format(error, solution))
l = lines[line]
origin = f.header[0][segyio.su.cdpx, segyio.su.cdpy]
cdpx, cdpy = origin[segyio.su.cdpx], origin[segyio.su.cdpy]
rot = f.xfd.rotation( len(l),
l.stride,
len(f.offsets),
np.fromiter(l.keys(), dtype = np.intc) )
return rot, cdpx, cdpy | python | def rotation(f, line = 'fast'):
if f.unstructured:
raise ValueError("Rotation requires a structured file")
lines = { 'fast': f.fast,
'slow': f.slow,
'iline': f.iline,
'xline': f.xline,
}
if line not in lines:
error = "Unknown line {}".format(line)
solution = "Must be any of: {}".format(' '.join(lines.keys()))
raise ValueError('{} {}'.format(error, solution))
l = lines[line]
origin = f.header[0][segyio.su.cdpx, segyio.su.cdpy]
cdpx, cdpy = origin[segyio.su.cdpx], origin[segyio.su.cdpy]
rot = f.xfd.rotation( len(l),
l.stride,
len(f.offsets),
np.fromiter(l.keys(), dtype = np.intc) )
return rot, cdpx, cdpy | [
"def",
"rotation",
"(",
"f",
",",
"line",
"=",
"'fast'",
")",
":",
"if",
"f",
".",
"unstructured",
":",
"raise",
"ValueError",
"(",
"\"Rotation requires a structured file\"",
")",
"lines",
"=",
"{",
"'fast'",
":",
"f",
".",
"fast",
",",
"'slow'",
":",
"f... | Find rotation of the survey
Find the clock-wise rotation and origin of `line` as ``(rot, cdpx, cdpy)``
The clock-wise rotation is defined as the angle in radians between line
given by the first and last trace of the first line and the axis that gives
increasing CDP-Y, in the direction that gives increasing CDP-X.
By default, the first line is the 'fast' direction, which is inlines if the
file is inline sorted, and crossline if it's crossline sorted.
Parameters
----------
f : SegyFile
line : { 'fast', 'slow', 'iline', 'xline' }
Returns
-------
rotation : float
cdpx : int
cdpy : int
Notes
-----
.. versionadded:: 1.2 | [
"Find",
"rotation",
"of",
"the",
"survey"
] | 58fd449947ccd330b9af0699d6b8710550d34e8e | https://github.com/equinor/segyio/blob/58fd449947ccd330b9af0699d6b8710550d34e8e/python/segyio/tools.py#L241-L297 |
239,036 | equinor/segyio | python/segyio/tools.py | metadata | def metadata(f):
"""Get survey structural properties and metadata
Create a description object that, when passed to ``segyio.create()``, would
create a new file with the same structure, dimensions, and metadata as
``f``.
Takes an open segy file (created with segyio.open) or a file name.
Parameters
----------
f : str or segyio.SegyFile
Returns
-------
spec : segyio.spec
Notes
-----
.. versionadded:: 1.4
"""
if not isinstance(f, segyio.SegyFile):
with segyio.open(f) as fl:
return metadata(fl)
spec = segyio.spec()
spec.iline = f._il
spec.xline = f._xl
spec.samples = f.samples
spec.format = f.format
spec.ilines = f.ilines
spec.xlines = f.xlines
spec.offsets = f.offsets
spec.sorting = f.sorting
spec.tracecount = f.tracecount
spec.ext_headers = f.ext_headers
spec.endian = f.endian
return spec | python | def metadata(f):
if not isinstance(f, segyio.SegyFile):
with segyio.open(f) as fl:
return metadata(fl)
spec = segyio.spec()
spec.iline = f._il
spec.xline = f._xl
spec.samples = f.samples
spec.format = f.format
spec.ilines = f.ilines
spec.xlines = f.xlines
spec.offsets = f.offsets
spec.sorting = f.sorting
spec.tracecount = f.tracecount
spec.ext_headers = f.ext_headers
spec.endian = f.endian
return spec | [
"def",
"metadata",
"(",
"f",
")",
":",
"if",
"not",
"isinstance",
"(",
"f",
",",
"segyio",
".",
"SegyFile",
")",
":",
"with",
"segyio",
".",
"open",
"(",
"f",
")",
"as",
"fl",
":",
"return",
"metadata",
"(",
"fl",
")",
"spec",
"=",
"segyio",
".",... | Get survey structural properties and metadata
Create a description object that, when passed to ``segyio.create()``, would
create a new file with the same structure, dimensions, and metadata as
``f``.
Takes an open segy file (created with segyio.open) or a file name.
Parameters
----------
f : str or segyio.SegyFile
Returns
-------
spec : segyio.spec
Notes
-----
.. versionadded:: 1.4 | [
"Get",
"survey",
"structural",
"properties",
"and",
"metadata"
] | 58fd449947ccd330b9af0699d6b8710550d34e8e | https://github.com/equinor/segyio/blob/58fd449947ccd330b9af0699d6b8710550d34e8e/python/segyio/tools.py#L299-L345 |
239,037 | equinor/segyio | python/segyio/tools.py | resample | def resample(f, rate = None, delay = None, micro = False,
trace = True,
binary = True):
"""Resample a file
Resample all data traces, and update the file handle to reflect the new
sample rate. No actual samples (data traces) are modified, only the header
fields and interpretation.
By default, the rate and the delay are in millseconds - if you need higher
resolution, passing micro=True interprets rate as microseconds (as it is
represented in the file). Delay is always milliseconds.
By default, both the global binary header and the trace headers are updated
to reflect this. If preserving either the trace header interval field or
the binary header interval field is important, pass trace=False and
binary=False respectively, to not have that field updated. This only apply
to sample rates - the recording delay is only found in trace headers and
will be written unconditionally, if delay is not None.
.. warning::
This function requires an open file handle and is **DESTRUCTIVE**. It
will modify the file, and if an exception is raised then partial writes
might have happened and the file might be corrupted.
This function assumes all traces have uniform delays and frequencies.
Parameters
----------
f : SegyFile
rate : int
delay : int
micro : bool
if True, interpret rate as microseconds
trace : bool
Update the trace header if True
binary : bool
Update the binary header if True
Notes
-----
.. versionadded:: 1.4
"""
if rate is not None:
if not micro: rate *= 1000
if binary: f.bin[segyio.su.hdt] = rate
if trace: f.header = { segyio.su.dt: rate}
if delay is not None:
f.header = { segyio.su.delrt: delay }
t0 = delay if delay is not None else f.samples[0]
rate = rate / 1000 if rate is not None else f.samples[1] - f.samples[0]
f._samples = (np.arange(len(f.samples)) * rate) + t0
return f | python | def resample(f, rate = None, delay = None, micro = False,
trace = True,
binary = True):
if rate is not None:
if not micro: rate *= 1000
if binary: f.bin[segyio.su.hdt] = rate
if trace: f.header = { segyio.su.dt: rate}
if delay is not None:
f.header = { segyio.su.delrt: delay }
t0 = delay if delay is not None else f.samples[0]
rate = rate / 1000 if rate is not None else f.samples[1] - f.samples[0]
f._samples = (np.arange(len(f.samples)) * rate) + t0
return f | [
"def",
"resample",
"(",
"f",
",",
"rate",
"=",
"None",
",",
"delay",
"=",
"None",
",",
"micro",
"=",
"False",
",",
"trace",
"=",
"True",
",",
"binary",
"=",
"True",
")",
":",
"if",
"rate",
"is",
"not",
"None",
":",
"if",
"not",
"micro",
":",
"r... | Resample a file
Resample all data traces, and update the file handle to reflect the new
sample rate. No actual samples (data traces) are modified, only the header
fields and interpretation.
By default, the rate and the delay are in millseconds - if you need higher
resolution, passing micro=True interprets rate as microseconds (as it is
represented in the file). Delay is always milliseconds.
By default, both the global binary header and the trace headers are updated
to reflect this. If preserving either the trace header interval field or
the binary header interval field is important, pass trace=False and
binary=False respectively, to not have that field updated. This only apply
to sample rates - the recording delay is only found in trace headers and
will be written unconditionally, if delay is not None.
.. warning::
This function requires an open file handle and is **DESTRUCTIVE**. It
will modify the file, and if an exception is raised then partial writes
might have happened and the file might be corrupted.
This function assumes all traces have uniform delays and frequencies.
Parameters
----------
f : SegyFile
rate : int
delay : int
micro : bool
if True, interpret rate as microseconds
trace : bool
Update the trace header if True
binary : bool
Update the binary header if True
Notes
-----
.. versionadded:: 1.4 | [
"Resample",
"a",
"file"
] | 58fd449947ccd330b9af0699d6b8710550d34e8e | https://github.com/equinor/segyio/blob/58fd449947ccd330b9af0699d6b8710550d34e8e/python/segyio/tools.py#L347-L408 |
239,038 | equinor/segyio | python/segyio/tools.py | from_array3D | def from_array3D(filename, data, iline=189,
xline=193,
format=SegySampleFormat.IBM_FLOAT_4_BYTE,
dt=4000,
delrt=0):
""" Create a new SEGY file from a 3D array
Create an structured SEGY file with defaulted headers from a 3-dimensional
array. The file is inline-sorted. ilines, xlines and samples are inferred
from the array. Structure-defining fields in the binary header and
in the traceheaders are set accordingly. Such fields include, but are not
limited to iline, xline and offset. The file also contains a defaulted
textual header.
The 3-dimensional array is interpreted as::
xl0 xl1 xl2
-----------------
/ | tr0 | tr1 | tr2 | il0
-----------------
| / | tr3 | tr4 | tr5 | il1
-----------------
| / | tr6 | tr7 | tr8 | il2
-----------------
| / / / / n-samples
------------------
ilines = [1, len(axis(0) + 1]
xlines = [1, len(axis(1) + 1]
samples = [0, len(axis(2)]
Parameters
----------
filename : string-like
Path to new file
data : 3-dimensional array-like
iline : int or segyio.TraceField
Inline number field in the trace headers. Defaults to 189 as per the
SEG-Y rev1 specification
xline : int or segyio.TraceField
Crossline number field in the trace headers. Defaults to 193 as per the
SEG-Y rev1 specification
format : int or segyio.SegySampleFormat
Sample format field in the trace header. Defaults to IBM float 4 byte
dt : int-like
sample interval
delrt : int-like
Notes
-----
.. versionadded:: 1.8
Examples
--------
Create a file from a 3D array, open it and read an iline:
>>> segyio.tools.from_array3D(path, array3d)
>>> segyio.open(path, mode) as f:
... iline = f.iline[0]
...
"""
data = np.asarray(data)
dimensions = len(data.shape)
if dimensions != 3:
problem = "Expected 3 dimensions, {} was given".format(dimensions)
raise ValueError(problem)
from_array(filename, data, iline=iline, xline=xline, format=format,
dt=dt,
delrt=delrt) | python | def from_array3D(filename, data, iline=189,
xline=193,
format=SegySampleFormat.IBM_FLOAT_4_BYTE,
dt=4000,
delrt=0):
data = np.asarray(data)
dimensions = len(data.shape)
if dimensions != 3:
problem = "Expected 3 dimensions, {} was given".format(dimensions)
raise ValueError(problem)
from_array(filename, data, iline=iline, xline=xline, format=format,
dt=dt,
delrt=delrt) | [
"def",
"from_array3D",
"(",
"filename",
",",
"data",
",",
"iline",
"=",
"189",
",",
"xline",
"=",
"193",
",",
"format",
"=",
"SegySampleFormat",
".",
"IBM_FLOAT_4_BYTE",
",",
"dt",
"=",
"4000",
",",
"delrt",
"=",
"0",
")",
":",
"data",
"=",
"np",
"."... | Create a new SEGY file from a 3D array
Create an structured SEGY file with defaulted headers from a 3-dimensional
array. The file is inline-sorted. ilines, xlines and samples are inferred
from the array. Structure-defining fields in the binary header and
in the traceheaders are set accordingly. Such fields include, but are not
limited to iline, xline and offset. The file also contains a defaulted
textual header.
The 3-dimensional array is interpreted as::
xl0 xl1 xl2
-----------------
/ | tr0 | tr1 | tr2 | il0
-----------------
| / | tr3 | tr4 | tr5 | il1
-----------------
| / | tr6 | tr7 | tr8 | il2
-----------------
| / / / / n-samples
------------------
ilines = [1, len(axis(0) + 1]
xlines = [1, len(axis(1) + 1]
samples = [0, len(axis(2)]
Parameters
----------
filename : string-like
Path to new file
data : 3-dimensional array-like
iline : int or segyio.TraceField
Inline number field in the trace headers. Defaults to 189 as per the
SEG-Y rev1 specification
xline : int or segyio.TraceField
Crossline number field in the trace headers. Defaults to 193 as per the
SEG-Y rev1 specification
format : int or segyio.SegySampleFormat
Sample format field in the trace header. Defaults to IBM float 4 byte
dt : int-like
sample interval
delrt : int-like
Notes
-----
.. versionadded:: 1.8
Examples
--------
Create a file from a 3D array, open it and read an iline:
>>> segyio.tools.from_array3D(path, array3d)
>>> segyio.open(path, mode) as f:
... iline = f.iline[0]
... | [
"Create",
"a",
"new",
"SEGY",
"file",
"from",
"a",
"3D",
"array",
"Create",
"an",
"structured",
"SEGY",
"file",
"with",
"defaulted",
"headers",
"from",
"a",
"3",
"-",
"dimensional",
"array",
".",
"The",
"file",
"is",
"inline",
"-",
"sorted",
".",
"ilines... | 58fd449947ccd330b9af0699d6b8710550d34e8e | https://github.com/equinor/segyio/blob/58fd449947ccd330b9af0699d6b8710550d34e8e/python/segyio/tools.py#L592-L662 |
239,039 | equinor/segyio | python/segyio/open.py | open | def open(filename, mode="r", iline = 189,
xline = 193,
strict = True,
ignore_geometry = False,
endian = 'big'):
"""Open a segy file.
Opens a segy file and tries to figure out its sorting, inline numbers,
crossline numbers, and offsets, and enables reading and writing to this
file in a simple manner.
For reading, the access mode `r` is preferred. All write operations will
raise an exception. For writing, the mode `r+` is preferred (as `rw` would
truncate the file). Any mode with `w` will raise an error. The modes used
are standard C file modes; please refer to that documentation for a
complete reference.
Open should be used together with python's ``with`` statement. Please refer
to the examples. When the ``with`` statement is used the file will
automatically be closed when the routine completes or an exception is
raised.
By default, segyio tries to open in ``strict`` mode. This means the file will
be assumed to represent a geometry with consistent inline, crosslines and
offsets. If strict is False, segyio will still try to establish a geometry,
but it won't abort if it fails. When in non-strict mode is opened,
geometry-dependent modes such as iline will raise an error.
If ``ignore_geometry=True``, segyio will *not* try to build iline/xline or
other geometry related structures, which leads to faster opens. This is
essentially the same as using ``strict=False`` on a file that has no
geometry.
Parameters
----------
filename : str
Path to file to open
mode : {'r', 'r+'}
File access mode, read-only ('r', default) or read-write ('r+')
iline : int or segyio.TraceField
Inline number field in the trace headers. Defaults to 189 as per the
SEG-Y rev1 specification
xline : int or segyio.TraceField
Crossline number field in the trace headers. Defaults to 193 as per the
SEG-Y rev1 specification
strict : bool, optional
Abort if a geometry cannot be inferred. Defaults to True.
ignore_geometry : bool, optional
Opt out on building geometry information, useful for e.g. shot
organised files. Defaults to False.
endian : {'big', 'msb', 'little', 'lsb'}
File endianness, big/msb (default) or little/lsb
Returns
-------
file : segyio.SegyFile
An open segyio file handle
Raises
------
ValueError
If the mode string contains 'w', as it would truncate the file
Notes
-----
.. versionadded:: 1.1
.. versionchanged:: 1.8
endian argument
When a file is opened non-strict, only raw traces access is allowed, and
using modes such as ``iline`` raise an error.
Examples
--------
Open a file in read-only mode:
>>> with segyio.open(path, "r") as f:
... print(f.ilines)
...
[1, 2, 3, 4, 5]
Open a file in read-write mode:
>>> with segyio.open(path, "r+") as f:
... f.trace = np.arange(100)
Open two files at once:
>>> with segyio.open(path) as src, segyio.open(path, "r+") as dst:
... dst.trace = src.trace # copy all traces from src to dst
Open a file little-endian file:
>>> with segyio.open(path, endian = 'little') as f:
... f.trace[0]
"""
if 'w' in mode:
problem = 'w in mode would truncate the file'
solution = 'use r+ to open in read-write'
raise ValueError(', '.join((problem, solution)))
endians = {
'little': 256, # (1 << 8)
'lsb': 256,
'big': 0,
'msb': 0,
}
if endian not in endians:
problem = 'unknown endianness {}, expected one of: '
opts = ' '.join(endians.keys())
raise ValueError(problem.format(endian) + opts)
from . import _segyio
fd = _segyio.segyiofd(str(filename), mode, endians[endian])
fd.segyopen()
metrics = fd.metrics()
f = segyio.SegyFile(fd,
filename = str(filename),
mode = mode,
iline = iline,
xline = xline,
endian = endian,
)
try:
dt = segyio.tools.dt(f, fallback_dt = 4000.0) / 1000.0
t0 = f.header[0][segyio.TraceField.DelayRecordingTime]
samples = metrics['samplecount']
f._samples = (numpy.arange(samples) * dt) + t0
except:
f.close()
raise
if ignore_geometry:
return f
return infer_geometry(f, metrics, iline, xline, strict) | python | def open(filename, mode="r", iline = 189,
xline = 193,
strict = True,
ignore_geometry = False,
endian = 'big'):
if 'w' in mode:
problem = 'w in mode would truncate the file'
solution = 'use r+ to open in read-write'
raise ValueError(', '.join((problem, solution)))
endians = {
'little': 256, # (1 << 8)
'lsb': 256,
'big': 0,
'msb': 0,
}
if endian not in endians:
problem = 'unknown endianness {}, expected one of: '
opts = ' '.join(endians.keys())
raise ValueError(problem.format(endian) + opts)
from . import _segyio
fd = _segyio.segyiofd(str(filename), mode, endians[endian])
fd.segyopen()
metrics = fd.metrics()
f = segyio.SegyFile(fd,
filename = str(filename),
mode = mode,
iline = iline,
xline = xline,
endian = endian,
)
try:
dt = segyio.tools.dt(f, fallback_dt = 4000.0) / 1000.0
t0 = f.header[0][segyio.TraceField.DelayRecordingTime]
samples = metrics['samplecount']
f._samples = (numpy.arange(samples) * dt) + t0
except:
f.close()
raise
if ignore_geometry:
return f
return infer_geometry(f, metrics, iline, xline, strict) | [
"def",
"open",
"(",
"filename",
",",
"mode",
"=",
"\"r\"",
",",
"iline",
"=",
"189",
",",
"xline",
"=",
"193",
",",
"strict",
"=",
"True",
",",
"ignore_geometry",
"=",
"False",
",",
"endian",
"=",
"'big'",
")",
":",
"if",
"'w'",
"in",
"mode",
":",
... | Open a segy file.
Opens a segy file and tries to figure out its sorting, inline numbers,
crossline numbers, and offsets, and enables reading and writing to this
file in a simple manner.
For reading, the access mode `r` is preferred. All write operations will
raise an exception. For writing, the mode `r+` is preferred (as `rw` would
truncate the file). Any mode with `w` will raise an error. The modes used
are standard C file modes; please refer to that documentation for a
complete reference.
Open should be used together with python's ``with`` statement. Please refer
to the examples. When the ``with`` statement is used the file will
automatically be closed when the routine completes or an exception is
raised.
By default, segyio tries to open in ``strict`` mode. This means the file will
be assumed to represent a geometry with consistent inline, crosslines and
offsets. If strict is False, segyio will still try to establish a geometry,
but it won't abort if it fails. When in non-strict mode is opened,
geometry-dependent modes such as iline will raise an error.
If ``ignore_geometry=True``, segyio will *not* try to build iline/xline or
other geometry related structures, which leads to faster opens. This is
essentially the same as using ``strict=False`` on a file that has no
geometry.
Parameters
----------
filename : str
Path to file to open
mode : {'r', 'r+'}
File access mode, read-only ('r', default) or read-write ('r+')
iline : int or segyio.TraceField
Inline number field in the trace headers. Defaults to 189 as per the
SEG-Y rev1 specification
xline : int or segyio.TraceField
Crossline number field in the trace headers. Defaults to 193 as per the
SEG-Y rev1 specification
strict : bool, optional
Abort if a geometry cannot be inferred. Defaults to True.
ignore_geometry : bool, optional
Opt out on building geometry information, useful for e.g. shot
organised files. Defaults to False.
endian : {'big', 'msb', 'little', 'lsb'}
File endianness, big/msb (default) or little/lsb
Returns
-------
file : segyio.SegyFile
An open segyio file handle
Raises
------
ValueError
If the mode string contains 'w', as it would truncate the file
Notes
-----
.. versionadded:: 1.1
.. versionchanged:: 1.8
endian argument
When a file is opened non-strict, only raw traces access is allowed, and
using modes such as ``iline`` raise an error.
Examples
--------
Open a file in read-only mode:
>>> with segyio.open(path, "r") as f:
... print(f.ilines)
...
[1, 2, 3, 4, 5]
Open a file in read-write mode:
>>> with segyio.open(path, "r+") as f:
... f.trace = np.arange(100)
Open two files at once:
>>> with segyio.open(path) as src, segyio.open(path, "r+") as dst:
... dst.trace = src.trace # copy all traces from src to dst
Open a file little-endian file:
>>> with segyio.open(path, endian = 'little') as f:
... f.trace[0] | [
"Open",
"a",
"segy",
"file",
"."
] | 58fd449947ccd330b9af0699d6b8710550d34e8e | https://github.com/equinor/segyio/blob/58fd449947ccd330b9af0699d6b8710550d34e8e/python/segyio/open.py#L33-L187 |
239,040 | equinor/segyio | python/segyio/field.py | Field.fetch | def fetch(self, buf = None, traceno = None):
"""Fetch the header from disk
This object will read header when it is constructed, which means it
might be out-of-date if the file is updated through some other handle.
This method is largely meant for internal use - if you need to reload
disk contents, use ``reload``.
Fetch does not update any internal state (unless `buf` is ``None`` on a
trace header, and the read succeeds), but returns the fetched header
contents.
This method can be used to reposition the trace header, which is useful
for constructing generators.
If this is called on a writable, new file, and this header has not yet
been written to, it will successfully return an empty buffer that, when
written to, will be reflected on disk.
Parameters
----------
buf : bytearray
buffer to read into instead of ``self.buf``
traceno : int
Returns
-------
buf : bytearray
Notes
-----
.. versionadded:: 1.6
This method is not intended as user-oriented functionality, but might
be useful in high-performance code.
"""
if buf is None:
buf = self.buf
if traceno is None:
traceno = self.traceno
try:
if self.kind == TraceField:
if traceno is None: return buf
return self.filehandle.getth(traceno, buf)
else:
return self.filehandle.getbin()
except IOError:
if not self.readonly:
# the file was probably newly created and the trace header
# hasn't been written yet, and we set the buffer to zero. if
# this is the case we want to try and write it later, and if
# the file was broken, permissions were wrong etc writing will
# fail too
#
# if the file is opened read-only and this happens, there's no
# way to actually write and the error is an actual error
return bytearray(len(self.buf))
else: raise | python | def fetch(self, buf = None, traceno = None):
if buf is None:
buf = self.buf
if traceno is None:
traceno = self.traceno
try:
if self.kind == TraceField:
if traceno is None: return buf
return self.filehandle.getth(traceno, buf)
else:
return self.filehandle.getbin()
except IOError:
if not self.readonly:
# the file was probably newly created and the trace header
# hasn't been written yet, and we set the buffer to zero. if
# this is the case we want to try and write it later, and if
# the file was broken, permissions were wrong etc writing will
# fail too
#
# if the file is opened read-only and this happens, there's no
# way to actually write and the error is an actual error
return bytearray(len(self.buf))
else: raise | [
"def",
"fetch",
"(",
"self",
",",
"buf",
"=",
"None",
",",
"traceno",
"=",
"None",
")",
":",
"if",
"buf",
"is",
"None",
":",
"buf",
"=",
"self",
".",
"buf",
"if",
"traceno",
"is",
"None",
":",
"traceno",
"=",
"self",
".",
"traceno",
"try",
":",
... | Fetch the header from disk
This object will read header when it is constructed, which means it
might be out-of-date if the file is updated through some other handle.
This method is largely meant for internal use - if you need to reload
disk contents, use ``reload``.
Fetch does not update any internal state (unless `buf` is ``None`` on a
trace header, and the read succeeds), but returns the fetched header
contents.
This method can be used to reposition the trace header, which is useful
for constructing generators.
If this is called on a writable, new file, and this header has not yet
been written to, it will successfully return an empty buffer that, when
written to, will be reflected on disk.
Parameters
----------
buf : bytearray
buffer to read into instead of ``self.buf``
traceno : int
Returns
-------
buf : bytearray
Notes
-----
.. versionadded:: 1.6
This method is not intended as user-oriented functionality, but might
be useful in high-performance code. | [
"Fetch",
"the",
"header",
"from",
"disk"
] | 58fd449947ccd330b9af0699d6b8710550d34e8e | https://github.com/equinor/segyio/blob/58fd449947ccd330b9af0699d6b8710550d34e8e/python/segyio/field.py#L183-L243 |
239,041 | equinor/segyio | python/segyio/field.py | Field.reload | def reload(self):
"""
This object will read header when it is constructed, which means it
might be out-of-date if the file is updated through some other handle.
It's rarely required to call this method, and it's a symptom of fragile
code. However, if you have multiple handles to the same header, it
might be necessary. Consider the following example::
>>> x = f.header[10]
>>> y = f.header[10]
>>> x[1, 5]
{ 1: 5, 5: 10 }
>>> y[1, 5]
{ 1: 5, 5: 10 }
>>> x[1] = 6
>>> x[1], y[1] # write to x[1] is invisible to y
6, 5
>>> y.reload()
>>> x[1], y[1]
6, 6
>>> x[1] = 5
>>> x[1], y[1]
5, 6
>>> y[5] = 1
>>> x.reload()
>>> x[1], y[1, 5] # the write to x[1] is lost
6, { 1: 6; 5: 1 }
In segyio, headers writes are atomic, and the write to disk writes the
full cache. If this cache is out of date, some writes might get lost,
even though the updates are compatible.
The fix to this issue is either to use ``reload`` and maintain buffer
consistency, or simply don't let header handles alias and overlap in
lifetime.
Notes
-----
.. versionadded:: 1.6
"""
self.buf = self.fetch(buf = self.buf)
return self | python | def reload(self):
self.buf = self.fetch(buf = self.buf)
return self | [
"def",
"reload",
"(",
"self",
")",
":",
"self",
".",
"buf",
"=",
"self",
".",
"fetch",
"(",
"buf",
"=",
"self",
".",
"buf",
")",
"return",
"self"
] | This object will read header when it is constructed, which means it
might be out-of-date if the file is updated through some other handle.
It's rarely required to call this method, and it's a symptom of fragile
code. However, if you have multiple handles to the same header, it
might be necessary. Consider the following example::
>>> x = f.header[10]
>>> y = f.header[10]
>>> x[1, 5]
{ 1: 5, 5: 10 }
>>> y[1, 5]
{ 1: 5, 5: 10 }
>>> x[1] = 6
>>> x[1], y[1] # write to x[1] is invisible to y
6, 5
>>> y.reload()
>>> x[1], y[1]
6, 6
>>> x[1] = 5
>>> x[1], y[1]
5, 6
>>> y[5] = 1
>>> x.reload()
>>> x[1], y[1, 5] # the write to x[1] is lost
6, { 1: 6; 5: 1 }
In segyio, headers writes are atomic, and the write to disk writes the
full cache. If this cache is out of date, some writes might get lost,
even though the updates are compatible.
The fix to this issue is either to use ``reload`` and maintain buffer
consistency, or simply don't let header handles alias and overlap in
lifetime.
Notes
-----
.. versionadded:: 1.6 | [
"This",
"object",
"will",
"read",
"header",
"when",
"it",
"is",
"constructed",
"which",
"means",
"it",
"might",
"be",
"out",
"-",
"of",
"-",
"date",
"if",
"the",
"file",
"is",
"updated",
"through",
"some",
"other",
"handle",
"."
] | 58fd449947ccd330b9af0699d6b8710550d34e8e | https://github.com/equinor/segyio/blob/58fd449947ccd330b9af0699d6b8710550d34e8e/python/segyio/field.py#L245-L288 |
239,042 | equinor/segyio | python/segyio/field.py | Field.flush | def flush(self):
"""Commit backing storage to disk
This method is largely internal, and it is not necessary to call this
from user code. It should not be explicitly invoked and may be removed
in future versions.
"""
if self.kind == TraceField:
self.filehandle.putth(self.traceno, self.buf)
elif self.kind == BinField:
self.filehandle.putbin(self.buf)
else:
msg = 'Object corrupted: kind {} not valid'
raise RuntimeError(msg.format(self.kind)) | python | def flush(self):
if self.kind == TraceField:
self.filehandle.putth(self.traceno, self.buf)
elif self.kind == BinField:
self.filehandle.putbin(self.buf)
else:
msg = 'Object corrupted: kind {} not valid'
raise RuntimeError(msg.format(self.kind)) | [
"def",
"flush",
"(",
"self",
")",
":",
"if",
"self",
".",
"kind",
"==",
"TraceField",
":",
"self",
".",
"filehandle",
".",
"putth",
"(",
"self",
".",
"traceno",
",",
"self",
".",
"buf",
")",
"elif",
"self",
".",
"kind",
"==",
"BinField",
":",
"self... | Commit backing storage to disk
This method is largely internal, and it is not necessary to call this
from user code. It should not be explicitly invoked and may be removed
in future versions. | [
"Commit",
"backing",
"storage",
"to",
"disk"
] | 58fd449947ccd330b9af0699d6b8710550d34e8e | https://github.com/equinor/segyio/blob/58fd449947ccd330b9af0699d6b8710550d34e8e/python/segyio/field.py#L290-L306 |
239,043 | equinor/segyio | python/segyio/trace.py | Trace.raw | def raw(self):
"""
An eager version of Trace
Returns
-------
raw : RawTrace
"""
return RawTrace(self.filehandle,
self.dtype,
len(self),
self.shape,
self.readonly,
) | python | def raw(self):
return RawTrace(self.filehandle,
self.dtype,
len(self),
self.shape,
self.readonly,
) | [
"def",
"raw",
"(",
"self",
")",
":",
"return",
"RawTrace",
"(",
"self",
".",
"filehandle",
",",
"self",
".",
"dtype",
",",
"len",
"(",
"self",
")",
",",
"self",
".",
"shape",
",",
"self",
".",
"readonly",
",",
")"
] | An eager version of Trace
Returns
-------
raw : RawTrace | [
"An",
"eager",
"version",
"of",
"Trace"
] | 58fd449947ccd330b9af0699d6b8710550d34e8e | https://github.com/equinor/segyio/blob/58fd449947ccd330b9af0699d6b8710550d34e8e/python/segyio/trace.py#L253-L266 |
239,044 | equinor/segyio | python/segyio/trace.py | Trace.ref | def ref(self):
"""
A write-back version of Trace
Returns
-------
ref : RefTrace
`ref` is returned in a context manager, and must be in a ``with``
statement
Notes
-----
.. versionadded:: 1.6
Examples
--------
>>> with trace.ref as ref:
... ref[10] += 1.617
"""
x = RefTrace(self.filehandle,
self.dtype,
len(self),
self.shape,
self.readonly,
)
yield x
x.flush() | python | def ref(self):
x = RefTrace(self.filehandle,
self.dtype,
len(self),
self.shape,
self.readonly,
)
yield x
x.flush() | [
"def",
"ref",
"(",
"self",
")",
":",
"x",
"=",
"RefTrace",
"(",
"self",
".",
"filehandle",
",",
"self",
".",
"dtype",
",",
"len",
"(",
"self",
")",
",",
"self",
".",
"shape",
",",
"self",
".",
"readonly",
",",
")",
"yield",
"x",
"x",
".",
"flus... | A write-back version of Trace
Returns
-------
ref : RefTrace
`ref` is returned in a context manager, and must be in a ``with``
statement
Notes
-----
.. versionadded:: 1.6
Examples
--------
>>> with trace.ref as ref:
... ref[10] += 1.617 | [
"A",
"write",
"-",
"back",
"version",
"of",
"Trace"
] | 58fd449947ccd330b9af0699d6b8710550d34e8e | https://github.com/equinor/segyio/blob/58fd449947ccd330b9af0699d6b8710550d34e8e/python/segyio/trace.py#L270-L297 |
239,045 | equinor/segyio | python/segyio/trace.py | RefTrace.flush | def flush(self):
"""
Commit cached writes to the file handle. Does not flush libc buffers or
notifies the kernel, so these changes may not immediately be visible to
other processes.
Updates the fingerprints whena writes happen, so successive ``flush()``
invocations are no-ops.
It is not necessary to call this method in user code.
Notes
-----
.. versionadded:: 1.6
This method is not intended as user-oriented functionality, but might
be useful in certain contexts to provide stronger guarantees.
"""
garbage = []
for i, (x, signature) in self.refs.items():
if sys.getrefcount(x) == 3:
garbage.append(i)
if fingerprint(x) == signature: continue
self.filehandle.puttr(i, x)
signature = fingerprint(x)
# to avoid too many resource leaks, when this dict is the only one
# holding references to already-produced traces, clear them
for i in garbage:
del self.refs[i] | python | def flush(self):
garbage = []
for i, (x, signature) in self.refs.items():
if sys.getrefcount(x) == 3:
garbage.append(i)
if fingerprint(x) == signature: continue
self.filehandle.puttr(i, x)
signature = fingerprint(x)
# to avoid too many resource leaks, when this dict is the only one
# holding references to already-produced traces, clear them
for i in garbage:
del self.refs[i] | [
"def",
"flush",
"(",
"self",
")",
":",
"garbage",
"=",
"[",
"]",
"for",
"i",
",",
"(",
"x",
",",
"signature",
")",
"in",
"self",
".",
"refs",
".",
"items",
"(",
")",
":",
"if",
"sys",
".",
"getrefcount",
"(",
"x",
")",
"==",
"3",
":",
"garbag... | Commit cached writes to the file handle. Does not flush libc buffers or
notifies the kernel, so these changes may not immediately be visible to
other processes.
Updates the fingerprints whena writes happen, so successive ``flush()``
invocations are no-ops.
It is not necessary to call this method in user code.
Notes
-----
.. versionadded:: 1.6
This method is not intended as user-oriented functionality, but might
be useful in certain contexts to provide stronger guarantees. | [
"Commit",
"cached",
"writes",
"to",
"the",
"file",
"handle",
".",
"Does",
"not",
"flush",
"libc",
"buffers",
"or",
"notifies",
"the",
"kernel",
"so",
"these",
"changes",
"may",
"not",
"immediately",
"be",
"visible",
"to",
"other",
"processes",
"."
] | 58fd449947ccd330b9af0699d6b8710550d34e8e | https://github.com/equinor/segyio/blob/58fd449947ccd330b9af0699d6b8710550d34e8e/python/segyio/trace.py#L376-L408 |
239,046 | equinor/segyio | python/segyio/segy.py | SegyFile.iline | def iline(self):
"""
Interact with segy in inline mode
Returns
-------
iline : Line or None
Raises
------
ValueError
If the file is unstructured
Notes
-----
.. versionadded:: 1.1
"""
if self.unstructured:
raise ValueError(self._unstructured_errmsg)
if self._iline is not None:
return self._iline
self._iline = Line(self,
self.ilines,
self._iline_length,
self._iline_stride,
self.offsets,
'inline',
)
return self._iline | python | def iline(self):
if self.unstructured:
raise ValueError(self._unstructured_errmsg)
if self._iline is not None:
return self._iline
self._iline = Line(self,
self.ilines,
self._iline_length,
self._iline_stride,
self.offsets,
'inline',
)
return self._iline | [
"def",
"iline",
"(",
"self",
")",
":",
"if",
"self",
".",
"unstructured",
":",
"raise",
"ValueError",
"(",
"self",
".",
"_unstructured_errmsg",
")",
"if",
"self",
".",
"_iline",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_iline",
"self",
".",
"_... | Interact with segy in inline mode
Returns
-------
iline : Line or None
Raises
------
ValueError
If the file is unstructured
Notes
-----
.. versionadded:: 1.1 | [
"Interact",
"with",
"segy",
"in",
"inline",
"mode"
] | 58fd449947ccd330b9af0699d6b8710550d34e8e | https://github.com/equinor/segyio/blob/58fd449947ccd330b9af0699d6b8710550d34e8e/python/segyio/segy.py#L501-L532 |
239,047 | equinor/segyio | python/segyio/segy.py | SegyFile.xline | def xline(self):
"""
Interact with segy in crossline mode
Returns
-------
xline : Line or None
Raises
------
ValueError
If the file is unstructured
Notes
-----
.. versionadded:: 1.1
"""
if self.unstructured:
raise ValueError(self._unstructured_errmsg)
if self._xline is not None:
return self._xline
self._xline = Line(self,
self.xlines,
self._xline_length,
self._xline_stride,
self.offsets,
'crossline',
)
return self._xline | python | def xline(self):
if self.unstructured:
raise ValueError(self._unstructured_errmsg)
if self._xline is not None:
return self._xline
self._xline = Line(self,
self.xlines,
self._xline_length,
self._xline_stride,
self.offsets,
'crossline',
)
return self._xline | [
"def",
"xline",
"(",
"self",
")",
":",
"if",
"self",
".",
"unstructured",
":",
"raise",
"ValueError",
"(",
"self",
".",
"_unstructured_errmsg",
")",
"if",
"self",
".",
"_xline",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_xline",
"self",
".",
"_... | Interact with segy in crossline mode
Returns
-------
xline : Line or None
Raises
------
ValueError
If the file is unstructured
Notes
-----
.. versionadded:: 1.1 | [
"Interact",
"with",
"segy",
"in",
"crossline",
"mode"
] | 58fd449947ccd330b9af0699d6b8710550d34e8e | https://github.com/equinor/segyio/blob/58fd449947ccd330b9af0699d6b8710550d34e8e/python/segyio/segy.py#L573-L603 |
239,048 | equinor/segyio | python/segyio/segy.py | SegyFile.fast | def fast(self):
"""Access the 'fast' dimension
This mode yields iline or xline mode, depending on which one is laid
out `faster`, i.e. the line with linear disk layout. Use this mode if
the inline/crossline distinction isn't as interesting as traversing in
a fast manner (typically when you want to apply a function to the whole
file, line-by-line).
Returns
-------
fast : Line
line addressing mode
Notes
-----
.. versionadded:: 1.1
"""
if self.sorting == TraceSortingFormat.INLINE_SORTING:
return self.iline
elif self.sorting == TraceSortingFormat.CROSSLINE_SORTING:
return self.xline
else:
raise RuntimeError("Unknown sorting.") | python | def fast(self):
if self.sorting == TraceSortingFormat.INLINE_SORTING:
return self.iline
elif self.sorting == TraceSortingFormat.CROSSLINE_SORTING:
return self.xline
else:
raise RuntimeError("Unknown sorting.") | [
"def",
"fast",
"(",
"self",
")",
":",
"if",
"self",
".",
"sorting",
"==",
"TraceSortingFormat",
".",
"INLINE_SORTING",
":",
"return",
"self",
".",
"iline",
"elif",
"self",
".",
"sorting",
"==",
"TraceSortingFormat",
".",
"CROSSLINE_SORTING",
":",
"return",
"... | Access the 'fast' dimension
This mode yields iline or xline mode, depending on which one is laid
out `faster`, i.e. the line with linear disk layout. Use this mode if
the inline/crossline distinction isn't as interesting as traversing in
a fast manner (typically when you want to apply a function to the whole
file, line-by-line).
Returns
-------
fast : Line
line addressing mode
Notes
-----
.. versionadded:: 1.1 | [
"Access",
"the",
"fast",
"dimension"
] | 58fd449947ccd330b9af0699d6b8710550d34e8e | https://github.com/equinor/segyio/blob/58fd449947ccd330b9af0699d6b8710550d34e8e/python/segyio/segy.py#L630-L653 |
239,049 | equinor/segyio | python/segyio/segy.py | SegyFile.gather | def gather(self):
"""
Interact with segy in gather mode
Returns
-------
gather : Gather
"""
if self.unstructured:
raise ValueError(self._unstructured_errmsg)
if self._gather is not None:
return self._gather
self._gather = Gather(self.trace, self.iline, self.xline, self.offsets)
return self._gather | python | def gather(self):
if self.unstructured:
raise ValueError(self._unstructured_errmsg)
if self._gather is not None:
return self._gather
self._gather = Gather(self.trace, self.iline, self.xline, self.offsets)
return self._gather | [
"def",
"gather",
"(",
"self",
")",
":",
"if",
"self",
".",
"unstructured",
":",
"raise",
"ValueError",
"(",
"self",
".",
"_unstructured_errmsg",
")",
"if",
"self",
".",
"_gather",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_gather",
"self",
".",
... | Interact with segy in gather mode
Returns
-------
gather : Gather | [
"Interact",
"with",
"segy",
"in",
"gather",
"mode"
] | 58fd449947ccd330b9af0699d6b8710550d34e8e | https://github.com/equinor/segyio/blob/58fd449947ccd330b9af0699d6b8710550d34e8e/python/segyio/segy.py#L729-L744 |
239,050 | pymc-devs/pymc | pymc/StepMethods.py | pick_best_methods | def pick_best_methods(stochastic):
"""
Picks the StepMethods best suited to handle
a stochastic variable.
"""
# Keep track of most competent methohd
max_competence = 0
# Empty set of appropriate StepMethods
best_candidates = set([])
# Loop over StepMethodRegistry
for method in StepMethodRegistry:
# Parse method and its associated competence
try:
competence = method.competence(stochastic)
except:
competence = 0
# If better than current best method, promote it
if competence > max_competence:
best_candidates = set([method])
max_competence = competence
# If same competence, add it to the set of best methods
elif competence == max_competence:
best_candidates.add(method)
if max_competence <= 0:
raise ValueError(
'Maximum competence reported for stochastic %s is <= 0... you may need to write a custom step method class.' %
stochastic.__name__)
# print_(s.__name__ + ': ', best_candidates, ' ', max_competence)
return best_candidates | python | def pick_best_methods(stochastic):
# Keep track of most competent methohd
max_competence = 0
# Empty set of appropriate StepMethods
best_candidates = set([])
# Loop over StepMethodRegistry
for method in StepMethodRegistry:
# Parse method and its associated competence
try:
competence = method.competence(stochastic)
except:
competence = 0
# If better than current best method, promote it
if competence > max_competence:
best_candidates = set([method])
max_competence = competence
# If same competence, add it to the set of best methods
elif competence == max_competence:
best_candidates.add(method)
if max_competence <= 0:
raise ValueError(
'Maximum competence reported for stochastic %s is <= 0... you may need to write a custom step method class.' %
stochastic.__name__)
# print_(s.__name__ + ': ', best_candidates, ' ', max_competence)
return best_candidates | [
"def",
"pick_best_methods",
"(",
"stochastic",
")",
":",
"# Keep track of most competent methohd",
"max_competence",
"=",
"0",
"# Empty set of appropriate StepMethods",
"best_candidates",
"=",
"set",
"(",
"[",
"]",
")",
"# Loop over StepMethodRegistry",
"for",
"method",
"in... | Picks the StepMethods best suited to handle
a stochastic variable. | [
"Picks",
"the",
"StepMethods",
"best",
"suited",
"to",
"handle",
"a",
"stochastic",
"variable",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L59-L94 |
239,051 | pymc-devs/pymc | pymc/StepMethods.py | StepMethod.loglike | def loglike(self):
'''
The summed log-probability of all stochastic variables that depend on
self.stochastics, with self.stochastics removed.
'''
sum = logp_of_set(self.children)
if self.verbose > 2:
print_('\t' + self._id + ' Current log-likelihood ', sum)
return sum | python | def loglike(self):
'''
The summed log-probability of all stochastic variables that depend on
self.stochastics, with self.stochastics removed.
'''
sum = logp_of_set(self.children)
if self.verbose > 2:
print_('\t' + self._id + ' Current log-likelihood ', sum)
return sum | [
"def",
"loglike",
"(",
"self",
")",
":",
"sum",
"=",
"logp_of_set",
"(",
"self",
".",
"children",
")",
"if",
"self",
".",
"verbose",
">",
"2",
":",
"print_",
"(",
"'\\t'",
"+",
"self",
".",
"_id",
"+",
"' Current log-likelihood '",
",",
"sum",
")",
"... | The summed log-probability of all stochastic variables that depend on
self.stochastics, with self.stochastics removed. | [
"The",
"summed",
"log",
"-",
"probability",
"of",
"all",
"stochastic",
"variables",
"that",
"depend",
"on",
"self",
".",
"stochastics",
"with",
"self",
".",
"stochastics",
"removed",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L292-L300 |
239,052 | pymc-devs/pymc | pymc/StepMethods.py | StepMethod.logp_plus_loglike | def logp_plus_loglike(self):
'''
The summed log-probability of all stochastic variables that depend on
self.stochastics, and self.stochastics.
'''
sum = logp_of_set(self.markov_blanket)
if self.verbose > 2:
print_('\t' + self._id +
' Current log-likelihood plus current log-probability', sum)
return sum | python | def logp_plus_loglike(self):
'''
The summed log-probability of all stochastic variables that depend on
self.stochastics, and self.stochastics.
'''
sum = logp_of_set(self.markov_blanket)
if self.verbose > 2:
print_('\t' + self._id +
' Current log-likelihood plus current log-probability', sum)
return sum | [
"def",
"logp_plus_loglike",
"(",
"self",
")",
":",
"sum",
"=",
"logp_of_set",
"(",
"self",
".",
"markov_blanket",
")",
"if",
"self",
".",
"verbose",
">",
"2",
":",
"print_",
"(",
"'\\t'",
"+",
"self",
".",
"_id",
"+",
"' Current log-likelihood plus current l... | The summed log-probability of all stochastic variables that depend on
self.stochastics, and self.stochastics. | [
"The",
"summed",
"log",
"-",
"probability",
"of",
"all",
"stochastic",
"variables",
"that",
"depend",
"on",
"self",
".",
"stochastics",
"and",
"self",
".",
"stochastics",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L303-L312 |
239,053 | pymc-devs/pymc | pymc/StepMethods.py | StepMethod.current_state | def current_state(self):
"""Return a dictionary with the current value of the variables defining
the state of the step method."""
state = {}
for s in self._state:
state[s] = getattr(self, s)
return state | python | def current_state(self):
state = {}
for s in self._state:
state[s] = getattr(self, s)
return state | [
"def",
"current_state",
"(",
"self",
")",
":",
"state",
"=",
"{",
"}",
"for",
"s",
"in",
"self",
".",
"_state",
":",
"state",
"[",
"s",
"]",
"=",
"getattr",
"(",
"self",
",",
"s",
")",
"return",
"state"
] | Return a dictionary with the current value of the variables defining
the state of the step method. | [
"Return",
"a",
"dictionary",
"with",
"the",
"current",
"value",
"of",
"the",
"variables",
"defining",
"the",
"state",
"of",
"the",
"step",
"method",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L318-L324 |
239,054 | pymc-devs/pymc | pymc/StepMethods.py | Metropolis.step | def step(self):
"""
The default step method applies if the variable is floating-point
valued, and is not being proposed from its prior.
"""
# Probability and likelihood for s's current value:
if self.verbose > 2:
print_()
print_(self._id + ' getting initial logp.')
if self.proposal_distribution == "prior":
logp = self.loglike
else:
logp = self.logp_plus_loglike
if self.verbose > 2:
print_(self._id + ' proposing.')
# Sample a candidate value
self.propose()
# Probability and likelihood for s's proposed value:
try:
if self.proposal_distribution == "prior":
logp_p = self.loglike
# Check for weirdness before accepting jump
if self.check_before_accepting:
self.stochastic.logp
else:
logp_p = self.logp_plus_loglike
except ZeroProbability:
# Reject proposal
if self.verbose > 2:
print_(self._id + ' rejecting due to ZeroProbability.')
self.reject()
# Increment rejected count
self.rejected += 1
if self.verbose > 2:
print_(self._id + ' returning.')
return
if self.verbose > 2:
print_('logp_p - logp: ', logp_p - logp)
HF = self.hastings_factor()
# Evaluate acceptance ratio
if log(random()) > logp_p - logp + HF:
# Revert s if fail
self.reject()
# Increment rejected count
self.rejected += 1
if self.verbose > 2:
print_(self._id + ' rejecting')
else:
# Increment accepted count
self.accepted += 1
if self.verbose > 2:
print_(self._id + ' accepting')
if self.verbose > 2:
print_(self._id + ' returning.') | python | def step(self):
# Probability and likelihood for s's current value:
if self.verbose > 2:
print_()
print_(self._id + ' getting initial logp.')
if self.proposal_distribution == "prior":
logp = self.loglike
else:
logp = self.logp_plus_loglike
if self.verbose > 2:
print_(self._id + ' proposing.')
# Sample a candidate value
self.propose()
# Probability and likelihood for s's proposed value:
try:
if self.proposal_distribution == "prior":
logp_p = self.loglike
# Check for weirdness before accepting jump
if self.check_before_accepting:
self.stochastic.logp
else:
logp_p = self.logp_plus_loglike
except ZeroProbability:
# Reject proposal
if self.verbose > 2:
print_(self._id + ' rejecting due to ZeroProbability.')
self.reject()
# Increment rejected count
self.rejected += 1
if self.verbose > 2:
print_(self._id + ' returning.')
return
if self.verbose > 2:
print_('logp_p - logp: ', logp_p - logp)
HF = self.hastings_factor()
# Evaluate acceptance ratio
if log(random()) > logp_p - logp + HF:
# Revert s if fail
self.reject()
# Increment rejected count
self.rejected += 1
if self.verbose > 2:
print_(self._id + ' rejecting')
else:
# Increment accepted count
self.accepted += 1
if self.verbose > 2:
print_(self._id + ' accepting')
if self.verbose > 2:
print_(self._id + ' returning.') | [
"def",
"step",
"(",
"self",
")",
":",
"# Probability and likelihood for s's current value:",
"if",
"self",
".",
"verbose",
">",
"2",
":",
"print_",
"(",
")",
"print_",
"(",
"self",
".",
"_id",
"+",
"' getting initial logp.'",
")",
"if",
"self",
".",
"proposal_... | The default step method applies if the variable is floating-point
valued, and is not being proposed from its prior. | [
"The",
"default",
"step",
"method",
"applies",
"if",
"the",
"variable",
"is",
"floating",
"-",
"point",
"valued",
"and",
"is",
"not",
"being",
"proposed",
"from",
"its",
"prior",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L470-L539 |
239,055 | pymc-devs/pymc | pymc/StepMethods.py | PDMatrixMetropolis.competence | def competence(s):
"""
The competence function for MatrixMetropolis
"""
# MatrixMetropolis handles the Wishart family, which are valued as
# _symmetric_ matrices.
if any([isinstance(s, cls)
for cls in [distributions.Wishart, distributions.WishartCov]]):
return 2
else:
return 0 | python | def competence(s):
# MatrixMetropolis handles the Wishart family, which are valued as
# _symmetric_ matrices.
if any([isinstance(s, cls)
for cls in [distributions.Wishart, distributions.WishartCov]]):
return 2
else:
return 0 | [
"def",
"competence",
"(",
"s",
")",
":",
"# MatrixMetropolis handles the Wishart family, which are valued as",
"# _symmetric_ matrices.",
"if",
"any",
"(",
"[",
"isinstance",
"(",
"s",
",",
"cls",
")",
"for",
"cls",
"in",
"[",
"distributions",
".",
"Wishart",
",",
... | The competence function for MatrixMetropolis | [
"The",
"competence",
"function",
"for",
"MatrixMetropolis"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L657-L667 |
239,056 | pymc-devs/pymc | pymc/StepMethods.py | PDMatrixMetropolis.propose | def propose(self):
"""
Proposals for positive definite matrix using random walk deviations on the Cholesky
factor of the current value.
"""
# Locally store size of matrix
dims = self.stochastic.value.shape
# Add normal deviate to value and symmetrize
dev = rnormal(
0,
self.adaptive_scale_factor *
self.proposal_sd,
size=dims)
symmetrize(dev)
# Replace
self.stochastic.value = dev + self.stochastic.value | python | def propose(self):
# Locally store size of matrix
dims = self.stochastic.value.shape
# Add normal deviate to value and symmetrize
dev = rnormal(
0,
self.adaptive_scale_factor *
self.proposal_sd,
size=dims)
symmetrize(dev)
# Replace
self.stochastic.value = dev + self.stochastic.value | [
"def",
"propose",
"(",
"self",
")",
":",
"# Locally store size of matrix",
"dims",
"=",
"self",
".",
"stochastic",
".",
"value",
".",
"shape",
"# Add normal deviate to value and symmetrize",
"dev",
"=",
"rnormal",
"(",
"0",
",",
"self",
".",
"adaptive_scale_factor",... | Proposals for positive definite matrix using random walk deviations on the Cholesky
factor of the current value. | [
"Proposals",
"for",
"positive",
"definite",
"matrix",
"using",
"random",
"walk",
"deviations",
"on",
"the",
"Cholesky",
"factor",
"of",
"the",
"current",
"value",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L669-L687 |
239,057 | pymc-devs/pymc | pymc/StepMethods.py | BinaryMetropolis.competence | def competence(stochastic):
"""
The competence function for Binary One-At-A-Time Metropolis
"""
if stochastic.dtype in bool_dtypes:
return 2
elif isinstance(stochastic, distributions.Bernoulli):
return 2
elif (isinstance(stochastic, distributions.Categorical) and
(len(stochastic.parents['p'])==2)):
return 2
else:
return 0 | python | def competence(stochastic):
if stochastic.dtype in bool_dtypes:
return 2
elif isinstance(stochastic, distributions.Bernoulli):
return 2
elif (isinstance(stochastic, distributions.Categorical) and
(len(stochastic.parents['p'])==2)):
return 2
else:
return 0 | [
"def",
"competence",
"(",
"stochastic",
")",
":",
"if",
"stochastic",
".",
"dtype",
"in",
"bool_dtypes",
":",
"return",
"2",
"elif",
"isinstance",
"(",
"stochastic",
",",
"distributions",
".",
"Bernoulli",
")",
":",
"return",
"2",
"elif",
"(",
"isinstance",
... | The competence function for Binary One-At-A-Time Metropolis | [
"The",
"competence",
"function",
"for",
"Binary",
"One",
"-",
"At",
"-",
"A",
"-",
"Time",
"Metropolis"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L901-L916 |
239,058 | pymc-devs/pymc | pymc/StepMethods.py | AdaptiveMetropolis.cov_from_value | def cov_from_value(self, scaling):
"""Return a covariance matrix for the jump distribution using
the actual value of the stochastic as a guess of their variance,
divided by the `scaling` argument.
Note that this is likely to return a poor guess.
"""
rv = []
for s in self.stochastics:
rv.extend(np.ravel(s.value).copy())
# Remove 0 values since this would lead to quite small jumps...
arv = np.array(rv)
arv[arv == 0] = 1.
# Create a diagonal covariance matrix using the scaling factor.
return np.eye(self.dim) * np.abs(arv) / scaling | python | def cov_from_value(self, scaling):
rv = []
for s in self.stochastics:
rv.extend(np.ravel(s.value).copy())
# Remove 0 values since this would lead to quite small jumps...
arv = np.array(rv)
arv[arv == 0] = 1.
# Create a diagonal covariance matrix using the scaling factor.
return np.eye(self.dim) * np.abs(arv) / scaling | [
"def",
"cov_from_value",
"(",
"self",
",",
"scaling",
")",
":",
"rv",
"=",
"[",
"]",
"for",
"s",
"in",
"self",
".",
"stochastics",
":",
"rv",
".",
"extend",
"(",
"np",
".",
"ravel",
"(",
"s",
".",
"value",
")",
".",
"copy",
"(",
")",
")",
"# Re... | Return a covariance matrix for the jump distribution using
the actual value of the stochastic as a guess of their variance,
divided by the `scaling` argument.
Note that this is likely to return a poor guess. | [
"Return",
"a",
"covariance",
"matrix",
"for",
"the",
"jump",
"distribution",
"using",
"the",
"actual",
"value",
"of",
"the",
"stochastic",
"as",
"a",
"guess",
"of",
"their",
"variance",
"divided",
"by",
"the",
"scaling",
"argument",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L1135-L1151 |
239,059 | pymc-devs/pymc | pymc/StepMethods.py | AdaptiveMetropolis.cov_from_scales | def cov_from_scales(self, scales):
"""Return a covariance matrix built from a dictionary of scales.
`scales` is a dictionary keyed by stochastic instances, and the
values refer are the variance of the jump distribution for each
stochastic. If a stochastic is a sequence, the variance must
have the same length.
"""
# Get array of scales
ord_sc = []
for stochastic in self.stochastics:
ord_sc.append(np.ravel(scales[stochastic]))
ord_sc = np.concatenate(ord_sc)
if np.squeeze(ord_sc).shape[0] != self.dim:
raise ValueError("Improper initial scales, dimension don't match",
(np.squeeze(ord_sc), self.dim))
# Scale identity matrix
return np.eye(self.dim) * ord_sc | python | def cov_from_scales(self, scales):
# Get array of scales
ord_sc = []
for stochastic in self.stochastics:
ord_sc.append(np.ravel(scales[stochastic]))
ord_sc = np.concatenate(ord_sc)
if np.squeeze(ord_sc).shape[0] != self.dim:
raise ValueError("Improper initial scales, dimension don't match",
(np.squeeze(ord_sc), self.dim))
# Scale identity matrix
return np.eye(self.dim) * ord_sc | [
"def",
"cov_from_scales",
"(",
"self",
",",
"scales",
")",
":",
"# Get array of scales",
"ord_sc",
"=",
"[",
"]",
"for",
"stochastic",
"in",
"self",
".",
"stochastics",
":",
"ord_sc",
".",
"append",
"(",
"np",
".",
"ravel",
"(",
"scales",
"[",
"stochastic"... | Return a covariance matrix built from a dictionary of scales.
`scales` is a dictionary keyed by stochastic instances, and the
values refer are the variance of the jump distribution for each
stochastic. If a stochastic is a sequence, the variance must
have the same length. | [
"Return",
"a",
"covariance",
"matrix",
"built",
"from",
"a",
"dictionary",
"of",
"scales",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L1153-L1173 |
239,060 | pymc-devs/pymc | pymc/StepMethods.py | AdaptiveMetropolis.cov_from_trace | def cov_from_trace(self, trace=slice(None)):
"""Define the jump distribution covariance matrix from the object's
stored trace.
:Parameters:
- `trace` : slice or int
A slice for the stochastic object's trace in the last chain, or a
an integer indicating the how many of the last samples will be used.
"""
n = []
for s in self.stochastics:
n.append(s.trace.length())
n = set(n)
if len(n) > 1:
raise ValueError('Traces do not have the same length.')
elif n == 0:
raise AttributeError(
'Stochastic has no trace to compute covariance.')
else:
n = n.pop()
if not isinstance(trace, slice):
trace = slice(trace, n)
a = self.trace2array(trace)
return np.cov(a, rowvar=0) | python | def cov_from_trace(self, trace=slice(None)):
n = []
for s in self.stochastics:
n.append(s.trace.length())
n = set(n)
if len(n) > 1:
raise ValueError('Traces do not have the same length.')
elif n == 0:
raise AttributeError(
'Stochastic has no trace to compute covariance.')
else:
n = n.pop()
if not isinstance(trace, slice):
trace = slice(trace, n)
a = self.trace2array(trace)
return np.cov(a, rowvar=0) | [
"def",
"cov_from_trace",
"(",
"self",
",",
"trace",
"=",
"slice",
"(",
"None",
")",
")",
":",
"n",
"=",
"[",
"]",
"for",
"s",
"in",
"self",
".",
"stochastics",
":",
"n",
".",
"append",
"(",
"s",
".",
"trace",
".",
"length",
"(",
")",
")",
"n",
... | Define the jump distribution covariance matrix from the object's
stored trace.
:Parameters:
- `trace` : slice or int
A slice for the stochastic object's trace in the last chain, or a
an integer indicating the how many of the last samples will be used. | [
"Define",
"the",
"jump",
"distribution",
"covariance",
"matrix",
"from",
"the",
"object",
"s",
"stored",
"trace",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L1175-L1202 |
239,061 | pymc-devs/pymc | pymc/StepMethods.py | AdaptiveMetropolis.check_type | def check_type(self):
"""Make sure each stochastic has a correct type, and identify discrete stochastics."""
self.isdiscrete = {}
for stochastic in self.stochastics:
if stochastic.dtype in integer_dtypes:
self.isdiscrete[stochastic] = True
elif stochastic.dtype in bool_dtypes:
raise ValueError(
'Binary stochastics not supported by AdaptativeMetropolis.')
else:
self.isdiscrete[stochastic] = False | python | def check_type(self):
self.isdiscrete = {}
for stochastic in self.stochastics:
if stochastic.dtype in integer_dtypes:
self.isdiscrete[stochastic] = True
elif stochastic.dtype in bool_dtypes:
raise ValueError(
'Binary stochastics not supported by AdaptativeMetropolis.')
else:
self.isdiscrete[stochastic] = False | [
"def",
"check_type",
"(",
"self",
")",
":",
"self",
".",
"isdiscrete",
"=",
"{",
"}",
"for",
"stochastic",
"in",
"self",
".",
"stochastics",
":",
"if",
"stochastic",
".",
"dtype",
"in",
"integer_dtypes",
":",
"self",
".",
"isdiscrete",
"[",
"stochastic",
... | Make sure each stochastic has a correct type, and identify discrete stochastics. | [
"Make",
"sure",
"each",
"stochastic",
"has",
"a",
"correct",
"type",
"and",
"identify",
"discrete",
"stochastics",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L1204-L1214 |
239,062 | pymc-devs/pymc | pymc/StepMethods.py | AdaptiveMetropolis.dimension | def dimension(self):
"""Compute the dimension of the sampling space and identify the slices
belonging to each stochastic.
"""
self.dim = 0
self._slices = {}
for stochastic in self.stochastics:
if isinstance(stochastic.value, np.matrix):
p_len = len(stochastic.value.A.ravel())
elif isinstance(stochastic.value, np.ndarray):
p_len = len(stochastic.value.ravel())
else:
p_len = 1
self._slices[stochastic] = slice(self.dim, self.dim + p_len)
self.dim += p_len | python | def dimension(self):
self.dim = 0
self._slices = {}
for stochastic in self.stochastics:
if isinstance(stochastic.value, np.matrix):
p_len = len(stochastic.value.A.ravel())
elif isinstance(stochastic.value, np.ndarray):
p_len = len(stochastic.value.ravel())
else:
p_len = 1
self._slices[stochastic] = slice(self.dim, self.dim + p_len)
self.dim += p_len | [
"def",
"dimension",
"(",
"self",
")",
":",
"self",
".",
"dim",
"=",
"0",
"self",
".",
"_slices",
"=",
"{",
"}",
"for",
"stochastic",
"in",
"self",
".",
"stochastics",
":",
"if",
"isinstance",
"(",
"stochastic",
".",
"value",
",",
"np",
".",
"matrix",... | Compute the dimension of the sampling space and identify the slices
belonging to each stochastic. | [
"Compute",
"the",
"dimension",
"of",
"the",
"sampling",
"space",
"and",
"identify",
"the",
"slices",
"belonging",
"to",
"each",
"stochastic",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L1216-L1230 |
239,063 | pymc-devs/pymc | pymc/StepMethods.py | AdaptiveMetropolis.update_cov | def update_cov(self):
"""Recursively compute the covariance matrix for the multivariate normal
proposal distribution.
This method is called every self.interval once self.delay iterations
have been performed.
"""
scaling = (2.4) ** 2 / self.dim # Gelman et al. 1996.
epsilon = 1.0e-5
chain = np.asarray(self._trace)
# Recursively compute the chain mean
self.C, self.chain_mean = self.recursive_cov(self.C, self._trace_count,
self.chain_mean, chain, scaling=scaling, epsilon=epsilon)
# Shrink covariance if acceptance rate is too small
acc_rate = self.accepted / (self.accepted + self.rejected)
if self.shrink_if_necessary:
if acc_rate < .001:
self.C *= .01
elif acc_rate < .01:
self.C *= .25
if self.verbose > 1:
if acc_rate < .01:
print_(
'\tAcceptance rate was',
acc_rate,
'shrinking covariance')
self.accepted = 0.
self.rejected = 0.
if self.verbose > 1:
print_("\tUpdating covariance ...\n", self.C)
print_("\tUpdating mean ... ", self.chain_mean)
# Update state
adjustmentwarning = '\n' +\
'Covariance was not positive definite and proposal_sd cannot be computed by \n' + \
'Cholesky decomposition. The next jumps will be based on the last \n' + \
'valid covariance matrix. This situation may have arisen because no \n' + \
'jumps were accepted during the last `interval`. One solution is to \n' + \
'increase the interval, or specify an initial covariance matrix with \n' + \
'a smaller variance. For this simulation, each time a similar error \n' + \
'occurs, proposal_sd will be reduced by a factor .9 to reduce the \n' + \
'jumps and increase the likelihood of accepted jumps.'
try:
self.updateproposal_sd()
except np.linalg.LinAlgError:
warnings.warn(adjustmentwarning)
self.covariance_adjustment(.9)
self._trace_count += len(self._trace)
self._trace = [] | python | def update_cov(self):
scaling = (2.4) ** 2 / self.dim # Gelman et al. 1996.
epsilon = 1.0e-5
chain = np.asarray(self._trace)
# Recursively compute the chain mean
self.C, self.chain_mean = self.recursive_cov(self.C, self._trace_count,
self.chain_mean, chain, scaling=scaling, epsilon=epsilon)
# Shrink covariance if acceptance rate is too small
acc_rate = self.accepted / (self.accepted + self.rejected)
if self.shrink_if_necessary:
if acc_rate < .001:
self.C *= .01
elif acc_rate < .01:
self.C *= .25
if self.verbose > 1:
if acc_rate < .01:
print_(
'\tAcceptance rate was',
acc_rate,
'shrinking covariance')
self.accepted = 0.
self.rejected = 0.
if self.verbose > 1:
print_("\tUpdating covariance ...\n", self.C)
print_("\tUpdating mean ... ", self.chain_mean)
# Update state
adjustmentwarning = '\n' +\
'Covariance was not positive definite and proposal_sd cannot be computed by \n' + \
'Cholesky decomposition. The next jumps will be based on the last \n' + \
'valid covariance matrix. This situation may have arisen because no \n' + \
'jumps were accepted during the last `interval`. One solution is to \n' + \
'increase the interval, or specify an initial covariance matrix with \n' + \
'a smaller variance. For this simulation, each time a similar error \n' + \
'occurs, proposal_sd will be reduced by a factor .9 to reduce the \n' + \
'jumps and increase the likelihood of accepted jumps.'
try:
self.updateproposal_sd()
except np.linalg.LinAlgError:
warnings.warn(adjustmentwarning)
self.covariance_adjustment(.9)
self._trace_count += len(self._trace)
self._trace = [] | [
"def",
"update_cov",
"(",
"self",
")",
":",
"scaling",
"=",
"(",
"2.4",
")",
"**",
"2",
"/",
"self",
".",
"dim",
"# Gelman et al. 1996.",
"epsilon",
"=",
"1.0e-5",
"chain",
"=",
"np",
".",
"asarray",
"(",
"self",
".",
"_trace",
")",
"# Recursively comput... | Recursively compute the covariance matrix for the multivariate normal
proposal distribution.
This method is called every self.interval once self.delay iterations
have been performed. | [
"Recursively",
"compute",
"the",
"covariance",
"matrix",
"for",
"the",
"multivariate",
"normal",
"proposal",
"distribution",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L1232-L1286 |
239,064 | pymc-devs/pymc | pymc/StepMethods.py | AdaptiveMetropolis.recursive_cov | def recursive_cov(self, cov, length, mean, chain, scaling=1, epsilon=0):
r"""Compute the covariance recursively.
Return the new covariance and the new mean.
.. math::
C_k & = \frac{1}{k-1} (\sum_{i=1}^k x_i x_i^T - k\bar{x_k}\bar{x_k}^T)
C_n & = \frac{1}{n-1} (\sum_{i=1}^k x_i x_i^T + \sum_{i=k+1}^n x_i x_i^T - n\bar{x_n}\bar{x_n}^T)
& = \frac{1}{n-1} ((k-1)C_k + k\bar{x_k}\bar{x_k}^T + \sum_{i=k+1}^n x_i x_i^T - n\bar{x_n}\bar{x_n}^T)
:Parameters:
- cov : matrix
Previous covariance matrix.
- length : int
Length of chain used to compute the previous covariance.
- mean : array
Previous mean.
- chain : array
Sample used to update covariance.
- scaling : float
Scaling parameter
- epsilon : float
Set to a small value to avoid singular matrices.
"""
n = length + len(chain)
k = length
new_mean = self.recursive_mean(mean, length, chain)
t0 = k * np.outer(mean, mean)
t1 = np.dot(chain.T, chain)
t2 = n * np.outer(new_mean, new_mean)
t3 = epsilon * np.eye(cov.shape[0])
new_cov = (
k - 1) / (
n - 1.) * cov + scaling / (
n - 1.) * (
t0 + t1 - t2 + t3)
return new_cov, new_mean | python | def recursive_cov(self, cov, length, mean, chain, scaling=1, epsilon=0):
r"""Compute the covariance recursively.
Return the new covariance and the new mean.
.. math::
C_k & = \frac{1}{k-1} (\sum_{i=1}^k x_i x_i^T - k\bar{x_k}\bar{x_k}^T)
C_n & = \frac{1}{n-1} (\sum_{i=1}^k x_i x_i^T + \sum_{i=k+1}^n x_i x_i^T - n\bar{x_n}\bar{x_n}^T)
& = \frac{1}{n-1} ((k-1)C_k + k\bar{x_k}\bar{x_k}^T + \sum_{i=k+1}^n x_i x_i^T - n\bar{x_n}\bar{x_n}^T)
:Parameters:
- cov : matrix
Previous covariance matrix.
- length : int
Length of chain used to compute the previous covariance.
- mean : array
Previous mean.
- chain : array
Sample used to update covariance.
- scaling : float
Scaling parameter
- epsilon : float
Set to a small value to avoid singular matrices.
"""
n = length + len(chain)
k = length
new_mean = self.recursive_mean(mean, length, chain)
t0 = k * np.outer(mean, mean)
t1 = np.dot(chain.T, chain)
t2 = n * np.outer(new_mean, new_mean)
t3 = epsilon * np.eye(cov.shape[0])
new_cov = (
k - 1) / (
n - 1.) * cov + scaling / (
n - 1.) * (
t0 + t1 - t2 + t3)
return new_cov, new_mean | [
"def",
"recursive_cov",
"(",
"self",
",",
"cov",
",",
"length",
",",
"mean",
",",
"chain",
",",
"scaling",
"=",
"1",
",",
"epsilon",
"=",
"0",
")",
":",
"n",
"=",
"length",
"+",
"len",
"(",
"chain",
")",
"k",
"=",
"length",
"new_mean",
"=",
"self... | r"""Compute the covariance recursively.
Return the new covariance and the new mean.
.. math::
C_k & = \frac{1}{k-1} (\sum_{i=1}^k x_i x_i^T - k\bar{x_k}\bar{x_k}^T)
C_n & = \frac{1}{n-1} (\sum_{i=1}^k x_i x_i^T + \sum_{i=k+1}^n x_i x_i^T - n\bar{x_n}\bar{x_n}^T)
& = \frac{1}{n-1} ((k-1)C_k + k\bar{x_k}\bar{x_k}^T + \sum_{i=k+1}^n x_i x_i^T - n\bar{x_n}\bar{x_n}^T)
:Parameters:
- cov : matrix
Previous covariance matrix.
- length : int
Length of chain used to compute the previous covariance.
- mean : array
Previous mean.
- chain : array
Sample used to update covariance.
- scaling : float
Scaling parameter
- epsilon : float
Set to a small value to avoid singular matrices. | [
"r",
"Compute",
"the",
"covariance",
"recursively",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L1297-L1335 |
239,065 | pymc-devs/pymc | pymc/StepMethods.py | AdaptiveMetropolis.recursive_mean | def recursive_mean(self, mean, length, chain):
r"""Compute the chain mean recursively.
Instead of computing the mean :math:`\bar{x_n}` of the entire chain,
use the last computed mean :math:`bar{x_j}` and the tail of the chain
to recursively estimate the mean.
.. math::
\bar{x_n} & = \frac{1}{n} \sum_{i=1}^n x_i
& = \frac{1}{n} (\sum_{i=1}^j x_i + \sum_{i=j+1}^n x_i)
& = \frac{j\bar{x_j}}{n} + \frac{\sum_{i=j+1}^n x_i}{n}
:Parameters:
- mean : array
Previous mean.
- length : int
Length of chain used to compute the previous mean.
- chain : array
Sample used to update mean.
"""
n = length + len(chain)
return length * mean / n + chain.sum(0) / n | python | def recursive_mean(self, mean, length, chain):
r"""Compute the chain mean recursively.
Instead of computing the mean :math:`\bar{x_n}` of the entire chain,
use the last computed mean :math:`bar{x_j}` and the tail of the chain
to recursively estimate the mean.
.. math::
\bar{x_n} & = \frac{1}{n} \sum_{i=1}^n x_i
& = \frac{1}{n} (\sum_{i=1}^j x_i + \sum_{i=j+1}^n x_i)
& = \frac{j\bar{x_j}}{n} + \frac{\sum_{i=j+1}^n x_i}{n}
:Parameters:
- mean : array
Previous mean.
- length : int
Length of chain used to compute the previous mean.
- chain : array
Sample used to update mean.
"""
n = length + len(chain)
return length * mean / n + chain.sum(0) / n | [
"def",
"recursive_mean",
"(",
"self",
",",
"mean",
",",
"length",
",",
"chain",
")",
":",
"n",
"=",
"length",
"+",
"len",
"(",
"chain",
")",
"return",
"length",
"*",
"mean",
"/",
"n",
"+",
"chain",
".",
"sum",
"(",
"0",
")",
"/",
"n"
] | r"""Compute the chain mean recursively.
Instead of computing the mean :math:`\bar{x_n}` of the entire chain,
use the last computed mean :math:`bar{x_j}` and the tail of the chain
to recursively estimate the mean.
.. math::
\bar{x_n} & = \frac{1}{n} \sum_{i=1}^n x_i
& = \frac{1}{n} (\sum_{i=1}^j x_i + \sum_{i=j+1}^n x_i)
& = \frac{j\bar{x_j}}{n} + \frac{\sum_{i=j+1}^n x_i}{n}
:Parameters:
- mean : array
Previous mean.
- length : int
Length of chain used to compute the previous mean.
- chain : array
Sample used to update mean. | [
"r",
"Compute",
"the",
"chain",
"mean",
"recursively",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L1337-L1358 |
239,066 | pymc-devs/pymc | pymc/StepMethods.py | AdaptiveMetropolis.propose | def propose(self):
"""
This method proposes values for stochastics based on the empirical
covariance of the values sampled so far.
The proposal jumps are drawn from a multivariate normal distribution.
"""
arrayjump = np.dot(
self.proposal_sd,
np.random.normal(
size=self.proposal_sd.shape[
0]))
if self.verbose > 2:
print_('Jump :', arrayjump)
# Update each stochastic individually.
for stochastic in self.stochastics:
jump = arrayjump[self._slices[stochastic]].squeeze()
if np.iterable(stochastic.value):
jump = np.reshape(
arrayjump[
self._slices[
stochastic]],
np.shape(
stochastic.value))
if self.isdiscrete[stochastic]:
jump = round_array(jump)
stochastic.value = stochastic.value + jump | python | def propose(self):
arrayjump = np.dot(
self.proposal_sd,
np.random.normal(
size=self.proposal_sd.shape[
0]))
if self.verbose > 2:
print_('Jump :', arrayjump)
# Update each stochastic individually.
for stochastic in self.stochastics:
jump = arrayjump[self._slices[stochastic]].squeeze()
if np.iterable(stochastic.value):
jump = np.reshape(
arrayjump[
self._slices[
stochastic]],
np.shape(
stochastic.value))
if self.isdiscrete[stochastic]:
jump = round_array(jump)
stochastic.value = stochastic.value + jump | [
"def",
"propose",
"(",
"self",
")",
":",
"arrayjump",
"=",
"np",
".",
"dot",
"(",
"self",
".",
"proposal_sd",
",",
"np",
".",
"random",
".",
"normal",
"(",
"size",
"=",
"self",
".",
"proposal_sd",
".",
"shape",
"[",
"0",
"]",
")",
")",
"if",
"sel... | This method proposes values for stochastics based on the empirical
covariance of the values sampled so far.
The proposal jumps are drawn from a multivariate normal distribution. | [
"This",
"method",
"proposes",
"values",
"for",
"stochastics",
"based",
"on",
"the",
"empirical",
"covariance",
"of",
"the",
"values",
"sampled",
"so",
"far",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L1360-L1388 |
239,067 | pymc-devs/pymc | pymc/StepMethods.py | AdaptiveMetropolis.step | def step(self):
"""
Perform a Metropolis step.
Stochastic parameters are block-updated using a multivariate normal
distribution whose covariance is updated every self.interval once
self.delay steps have been performed.
The AM instance keeps a local copy of the stochastic parameter's trace.
This trace is used to computed the empirical covariance, and is
completely independent from the Database backend.
If self.greedy is True and the number of iterations is smaller than
self.delay, only accepted jumps are stored in the internal
trace to avoid computing singular covariance matrices.
"""
# Probability and likelihood for stochastic's current value:
logp = self.logp_plus_loglike
if self.verbose > 1:
print_('Current value: ', self.stoch2array())
print_('Current likelihood: ', logp)
# Sample a candidate value
self.propose()
# Metropolis acception/rejection test
accept = False
try:
# Probability and likelihood for stochastic's proposed value:
logp_p = self.logp_plus_loglike
if self.verbose > 2:
print_('Current value: ', self.stoch2array())
print_('Current likelihood: ', logp_p)
if np.log(random()) < logp_p - logp:
accept = True
self.accepted += 1
if self.verbose > 2:
print_('Accepted')
else:
self.rejected += 1
if self.verbose > 2:
print_('Rejected')
except ZeroProbability:
self.rejected += 1
logp_p = None
if self.verbose > 2:
print_('Rejected with ZeroProbability Error.')
if (not self._current_iter % self.interval) and self.verbose > 1:
print_("Step ", self._current_iter)
print_("\tLogprobability (current, proposed): ", logp, logp_p)
for stochastic in self.stochastics:
print_(
"\t",
stochastic.__name__,
stochastic.last_value,
stochastic.value)
if accept:
print_("\tAccepted\t*******\n")
else:
print_("\tRejected\n")
print_(
"\tAcceptance ratio: ",
self.accepted / (
self.accepted + self.rejected))
if self._current_iter == self.delay:
self.greedy = False
if not accept:
self.reject()
if accept or not self.greedy:
self.internal_tally()
if self._current_iter > self.delay and self._current_iter % self.interval == 0:
self.update_cov()
self._current_iter += 1 | python | def step(self):
# Probability and likelihood for stochastic's current value:
logp = self.logp_plus_loglike
if self.verbose > 1:
print_('Current value: ', self.stoch2array())
print_('Current likelihood: ', logp)
# Sample a candidate value
self.propose()
# Metropolis acception/rejection test
accept = False
try:
# Probability and likelihood for stochastic's proposed value:
logp_p = self.logp_plus_loglike
if self.verbose > 2:
print_('Current value: ', self.stoch2array())
print_('Current likelihood: ', logp_p)
if np.log(random()) < logp_p - logp:
accept = True
self.accepted += 1
if self.verbose > 2:
print_('Accepted')
else:
self.rejected += 1
if self.verbose > 2:
print_('Rejected')
except ZeroProbability:
self.rejected += 1
logp_p = None
if self.verbose > 2:
print_('Rejected with ZeroProbability Error.')
if (not self._current_iter % self.interval) and self.verbose > 1:
print_("Step ", self._current_iter)
print_("\tLogprobability (current, proposed): ", logp, logp_p)
for stochastic in self.stochastics:
print_(
"\t",
stochastic.__name__,
stochastic.last_value,
stochastic.value)
if accept:
print_("\tAccepted\t*******\n")
else:
print_("\tRejected\n")
print_(
"\tAcceptance ratio: ",
self.accepted / (
self.accepted + self.rejected))
if self._current_iter == self.delay:
self.greedy = False
if not accept:
self.reject()
if accept or not self.greedy:
self.internal_tally()
if self._current_iter > self.delay and self._current_iter % self.interval == 0:
self.update_cov()
self._current_iter += 1 | [
"def",
"step",
"(",
"self",
")",
":",
"# Probability and likelihood for stochastic's current value:",
"logp",
"=",
"self",
".",
"logp_plus_loglike",
"if",
"self",
".",
"verbose",
">",
"1",
":",
"print_",
"(",
"'Current value: '",
",",
"self",
".",
"stoch2array",
"... | Perform a Metropolis step.
Stochastic parameters are block-updated using a multivariate normal
distribution whose covariance is updated every self.interval once
self.delay steps have been performed.
The AM instance keeps a local copy of the stochastic parameter's trace.
This trace is used to computed the empirical covariance, and is
completely independent from the Database backend.
If self.greedy is True and the number of iterations is smaller than
self.delay, only accepted jumps are stored in the internal
trace to avoid computing singular covariance matrices. | [
"Perform",
"a",
"Metropolis",
"step",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L1390-L1470 |
239,068 | pymc-devs/pymc | pymc/StepMethods.py | AdaptiveMetropolis.internal_tally | def internal_tally(self):
"""Store the trace of stochastics for the computation of the covariance.
This trace is completely independent from the backend used by the
sampler to store the samples."""
chain = []
for stochastic in self.stochastics:
chain.append(np.ravel(stochastic.value))
self._trace.append(np.concatenate(chain)) | python | def internal_tally(self):
chain = []
for stochastic in self.stochastics:
chain.append(np.ravel(stochastic.value))
self._trace.append(np.concatenate(chain)) | [
"def",
"internal_tally",
"(",
"self",
")",
":",
"chain",
"=",
"[",
"]",
"for",
"stochastic",
"in",
"self",
".",
"stochastics",
":",
"chain",
".",
"append",
"(",
"np",
".",
"ravel",
"(",
"stochastic",
".",
"value",
")",
")",
"self",
".",
"_trace",
"."... | Store the trace of stochastics for the computation of the covariance.
This trace is completely independent from the backend used by the
sampler to store the samples. | [
"Store",
"the",
"trace",
"of",
"stochastics",
"for",
"the",
"computation",
"of",
"the",
"covariance",
".",
"This",
"trace",
"is",
"completely",
"independent",
"from",
"the",
"backend",
"used",
"by",
"the",
"sampler",
"to",
"store",
"the",
"samples",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L1479-L1486 |
239,069 | pymc-devs/pymc | pymc/StepMethods.py | AdaptiveMetropolis.trace2array | def trace2array(self, sl):
"""Return an array with the trace of all stochastics, sliced by sl."""
chain = []
for stochastic in self.stochastics:
tr = stochastic.trace.gettrace(slicing=sl)
if tr is None:
raise AttributeError
chain.append(tr)
return np.hstack(chain) | python | def trace2array(self, sl):
chain = []
for stochastic in self.stochastics:
tr = stochastic.trace.gettrace(slicing=sl)
if tr is None:
raise AttributeError
chain.append(tr)
return np.hstack(chain) | [
"def",
"trace2array",
"(",
"self",
",",
"sl",
")",
":",
"chain",
"=",
"[",
"]",
"for",
"stochastic",
"in",
"self",
".",
"stochastics",
":",
"tr",
"=",
"stochastic",
".",
"trace",
".",
"gettrace",
"(",
"slicing",
"=",
"sl",
")",
"if",
"tr",
"is",
"N... | Return an array with the trace of all stochastics, sliced by sl. | [
"Return",
"an",
"array",
"with",
"the",
"trace",
"of",
"all",
"stochastics",
"sliced",
"by",
"sl",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L1488-L1496 |
239,070 | pymc-devs/pymc | pymc/StepMethods.py | AdaptiveMetropolis.stoch2array | def stoch2array(self):
"""Return the stochastic objects as an array."""
a = np.empty(self.dim)
for stochastic in self.stochastics:
a[self._slices[stochastic]] = stochastic.value
return a | python | def stoch2array(self):
a = np.empty(self.dim)
for stochastic in self.stochastics:
a[self._slices[stochastic]] = stochastic.value
return a | [
"def",
"stoch2array",
"(",
"self",
")",
":",
"a",
"=",
"np",
".",
"empty",
"(",
"self",
".",
"dim",
")",
"for",
"stochastic",
"in",
"self",
".",
"stochastics",
":",
"a",
"[",
"self",
".",
"_slices",
"[",
"stochastic",
"]",
"]",
"=",
"stochastic",
"... | Return the stochastic objects as an array. | [
"Return",
"the",
"stochastic",
"objects",
"as",
"an",
"array",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L1498-L1503 |
239,071 | pymc-devs/pymc | pymc/StepMethods.py | TWalk.walk | def walk(self):
"""Walk proposal kernel"""
if self.verbose > 1:
print_('\t' + self._id + ' Running Walk proposal kernel')
# Mask for values to move
phi = self.phi
theta = self.walk_theta
u = random(len(phi))
z = (theta / (1 + theta)) * (theta * u ** 2 + 2 * u - 1)
if self._prime:
xp, x = self.values
else:
x, xp = self.values
if self.verbose > 1:
print_('\t' + 'Current value = ' + str(x))
x = x + phi * (x - xp) * z
if self.verbose > 1:
print_('\t' + 'Proposed value = ' + str(x))
self.stochastic.value = x
# Set proposal adjustment factor
self.hastings_factor = 0.0 | python | def walk(self):
if self.verbose > 1:
print_('\t' + self._id + ' Running Walk proposal kernel')
# Mask for values to move
phi = self.phi
theta = self.walk_theta
u = random(len(phi))
z = (theta / (1 + theta)) * (theta * u ** 2 + 2 * u - 1)
if self._prime:
xp, x = self.values
else:
x, xp = self.values
if self.verbose > 1:
print_('\t' + 'Current value = ' + str(x))
x = x + phi * (x - xp) * z
if self.verbose > 1:
print_('\t' + 'Proposed value = ' + str(x))
self.stochastic.value = x
# Set proposal adjustment factor
self.hastings_factor = 0.0 | [
"def",
"walk",
"(",
"self",
")",
":",
"if",
"self",
".",
"verbose",
">",
"1",
":",
"print_",
"(",
"'\\t'",
"+",
"self",
".",
"_id",
"+",
"' Running Walk proposal kernel'",
")",
"# Mask for values to move",
"phi",
"=",
"self",
".",
"phi",
"theta",
"=",
"s... | Walk proposal kernel | [
"Walk",
"proposal",
"kernel"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L1631-L1661 |
239,072 | pymc-devs/pymc | pymc/StepMethods.py | TWalk.traverse | def traverse(self):
"""Traverse proposal kernel"""
if self.verbose > 1:
print_('\t' + self._id + ' Running Traverse proposal kernel')
# Mask for values to move
phi = self.phi
theta = self.traverse_theta
# Calculate beta
if (random() < (theta - 1) / (2 * theta)):
beta = exp(1 / (theta + 1) * log(random()))
else:
beta = exp(1 / (1 - theta) * log(random()))
if self._prime:
xp, x = self.values
else:
x, xp = self.values
if self.verbose > 1:
print_('\t' + 'Current value = ' + str(x))
x = (xp + beta * (xp - x)) * phi + x * (phi == False)
if self.verbose > 1:
print_('\t' + 'Proposed value = ' + str(x))
self.stochastic.value = x
# Set proposal adjustment factor
self.hastings_factor = (sum(phi) - 2) * log(beta) | python | def traverse(self):
if self.verbose > 1:
print_('\t' + self._id + ' Running Traverse proposal kernel')
# Mask for values to move
phi = self.phi
theta = self.traverse_theta
# Calculate beta
if (random() < (theta - 1) / (2 * theta)):
beta = exp(1 / (theta + 1) * log(random()))
else:
beta = exp(1 / (1 - theta) * log(random()))
if self._prime:
xp, x = self.values
else:
x, xp = self.values
if self.verbose > 1:
print_('\t' + 'Current value = ' + str(x))
x = (xp + beta * (xp - x)) * phi + x * (phi == False)
if self.verbose > 1:
print_('\t' + 'Proposed value = ' + str(x))
self.stochastic.value = x
# Set proposal adjustment factor
self.hastings_factor = (sum(phi) - 2) * log(beta) | [
"def",
"traverse",
"(",
"self",
")",
":",
"if",
"self",
".",
"verbose",
">",
"1",
":",
"print_",
"(",
"'\\t'",
"+",
"self",
".",
"_id",
"+",
"' Running Traverse proposal kernel'",
")",
"# Mask for values to move",
"phi",
"=",
"self",
".",
"phi",
"theta",
"... | Traverse proposal kernel | [
"Traverse",
"proposal",
"kernel"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L1663-L1696 |
239,073 | pymc-devs/pymc | pymc/StepMethods.py | TWalk.blow | def blow(self):
"""Blow proposal kernel"""
if self.verbose > 1:
print_('\t' + self._id + ' Running Blow proposal kernel')
# Mask for values to move
phi = self.phi
if self._prime:
xp, x = self.values
else:
x, xp = self.values
if self.verbose > 1:
print_('\t' + 'Current value ' + str(x))
sigma = max(phi * abs(xp - x))
x = x + phi * sigma * rnormal()
if self.verbose > 1:
print_('\t' + 'Proposed value = ' + str(x))
self.hastings_factor = self._g(
x,
xp,
sigma) - self._g(
self.stochastic.value,
xp,
sigma)
self.stochastic.value = x | python | def blow(self):
if self.verbose > 1:
print_('\t' + self._id + ' Running Blow proposal kernel')
# Mask for values to move
phi = self.phi
if self._prime:
xp, x = self.values
else:
x, xp = self.values
if self.verbose > 1:
print_('\t' + 'Current value ' + str(x))
sigma = max(phi * abs(xp - x))
x = x + phi * sigma * rnormal()
if self.verbose > 1:
print_('\t' + 'Proposed value = ' + str(x))
self.hastings_factor = self._g(
x,
xp,
sigma) - self._g(
self.stochastic.value,
xp,
sigma)
self.stochastic.value = x | [
"def",
"blow",
"(",
"self",
")",
":",
"if",
"self",
".",
"verbose",
">",
"1",
":",
"print_",
"(",
"'\\t'",
"+",
"self",
".",
"_id",
"+",
"' Running Blow proposal kernel'",
")",
"# Mask for values to move",
"phi",
"=",
"self",
".",
"phi",
"if",
"self",
".... | Blow proposal kernel | [
"Blow",
"proposal",
"kernel"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L1698-L1730 |
239,074 | pymc-devs/pymc | pymc/StepMethods.py | TWalk._g | def _g(self, h, xp, s):
"""Density function for blow and hop moves"""
nphi = sum(self.phi)
return (nphi / 2.0) * log(2 * pi) + nphi * \
log(s) + 0.5 * sum((h - xp) ** 2) / (s ** 2) | python | def _g(self, h, xp, s):
nphi = sum(self.phi)
return (nphi / 2.0) * log(2 * pi) + nphi * \
log(s) + 0.5 * sum((h - xp) ** 2) / (s ** 2) | [
"def",
"_g",
"(",
"self",
",",
"h",
",",
"xp",
",",
"s",
")",
":",
"nphi",
"=",
"sum",
"(",
"self",
".",
"phi",
")",
"return",
"(",
"nphi",
"/",
"2.0",
")",
"*",
"log",
"(",
"2",
"*",
"pi",
")",
"+",
"nphi",
"*",
"log",
"(",
"s",
")",
"... | Density function for blow and hop moves | [
"Density",
"function",
"for",
"blow",
"and",
"hop",
"moves"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L1732-L1738 |
239,075 | pymc-devs/pymc | pymc/StepMethods.py | TWalk.reject | def reject(self):
"""Sets current s value to the last accepted value"""
self.stochastic.revert()
# Increment rejected count
self.rejected[self.current_kernel] += 1
if self.verbose > 1:
print_(
self._id,
"rejected, reverting to value =",
self.stochastic.value) | python | def reject(self):
self.stochastic.revert()
# Increment rejected count
self.rejected[self.current_kernel] += 1
if self.verbose > 1:
print_(
self._id,
"rejected, reverting to value =",
self.stochastic.value) | [
"def",
"reject",
"(",
"self",
")",
":",
"self",
".",
"stochastic",
".",
"revert",
"(",
")",
"# Increment rejected count",
"self",
".",
"rejected",
"[",
"self",
".",
"current_kernel",
"]",
"+=",
"1",
"if",
"self",
".",
"verbose",
">",
"1",
":",
"print_",
... | Sets current s value to the last accepted value | [
"Sets",
"current",
"s",
"value",
"to",
"the",
"last",
"accepted",
"value"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L1774-L1785 |
239,076 | pymc-devs/pymc | pymc/StepMethods.py | TWalk.step | def step(self):
"""Single iteration of t-walk algorithm"""
valid_proposal = False
# Use x or xprime as pivot
self._prime = (random() < 0.5)
if self.verbose > 1:
print_("\n\nUsing x%s as pivot" % (" prime" * self._prime or ""))
if self._prime:
# Set the value of the stochastic to the auxiliary
self.stochastic.value = self.values[1]
if self.verbose > 1:
print_(
self._id,
"setting value to auxiliary",
self.stochastic.value)
# Current log-probability
logp = self.logp_plus_loglike
if self.verbose > 1:
print_("Current logp", logp)
try:
# Propose new value
while not valid_proposal:
self.propose()
# Check that proposed value lies in support
valid_proposal = self._support(self.stochastic.value)
if not sum(self.phi):
raise ZeroProbability
# Proposed log-probability
logp_p = self.logp_plus_loglike
if self.verbose > 1:
print_("Proposed logp", logp_p)
except ZeroProbability:
# Reject proposal
if self.verbose > 1:
print_(self._id + ' rejecting due to ZeroProbability.')
self.reject()
if self._prime:
# Update value list
self.values[1] = self.stochastic.value
# Revert to stochastic's value for next iteration
self.stochastic.value = self.values[0]
if self.verbose > 1:
print_(
self._id,
"reverting stochastic to primary value",
self.stochastic.value)
else:
# Update value list
self.values[0] = self.stochastic.value
if self.verbose > 1:
print_(self._id + ' returning.')
return
if self.verbose > 1:
print_('logp_p - logp: ', logp_p - logp)
# Evaluate acceptance ratio
if log(random()) > (logp_p - logp + self.hastings_factor):
# Revert s if fail
self.reject()
else:
# Increment accepted count
self.accepted[self.current_kernel] += 1
if self.verbose > 1:
print_(self._id + ' accepting')
if self._prime:
# Update value list
self.values[1] = self.stochastic.value
# Revert to stochastic's value for next iteration
self.stochastic.value = self.values[0]
if self.verbose > 1:
print_(
self._id,
"reverting stochastic to primary value",
self.stochastic.value)
else:
# Update value list
self.values[0] = self.stochastic.value | python | def step(self):
valid_proposal = False
# Use x or xprime as pivot
self._prime = (random() < 0.5)
if self.verbose > 1:
print_("\n\nUsing x%s as pivot" % (" prime" * self._prime or ""))
if self._prime:
# Set the value of the stochastic to the auxiliary
self.stochastic.value = self.values[1]
if self.verbose > 1:
print_(
self._id,
"setting value to auxiliary",
self.stochastic.value)
# Current log-probability
logp = self.logp_plus_loglike
if self.verbose > 1:
print_("Current logp", logp)
try:
# Propose new value
while not valid_proposal:
self.propose()
# Check that proposed value lies in support
valid_proposal = self._support(self.stochastic.value)
if not sum(self.phi):
raise ZeroProbability
# Proposed log-probability
logp_p = self.logp_plus_loglike
if self.verbose > 1:
print_("Proposed logp", logp_p)
except ZeroProbability:
# Reject proposal
if self.verbose > 1:
print_(self._id + ' rejecting due to ZeroProbability.')
self.reject()
if self._prime:
# Update value list
self.values[1] = self.stochastic.value
# Revert to stochastic's value for next iteration
self.stochastic.value = self.values[0]
if self.verbose > 1:
print_(
self._id,
"reverting stochastic to primary value",
self.stochastic.value)
else:
# Update value list
self.values[0] = self.stochastic.value
if self.verbose > 1:
print_(self._id + ' returning.')
return
if self.verbose > 1:
print_('logp_p - logp: ', logp_p - logp)
# Evaluate acceptance ratio
if log(random()) > (logp_p - logp + self.hastings_factor):
# Revert s if fail
self.reject()
else:
# Increment accepted count
self.accepted[self.current_kernel] += 1
if self.verbose > 1:
print_(self._id + ' accepting')
if self._prime:
# Update value list
self.values[1] = self.stochastic.value
# Revert to stochastic's value for next iteration
self.stochastic.value = self.values[0]
if self.verbose > 1:
print_(
self._id,
"reverting stochastic to primary value",
self.stochastic.value)
else:
# Update value list
self.values[0] = self.stochastic.value | [
"def",
"step",
"(",
"self",
")",
":",
"valid_proposal",
"=",
"False",
"# Use x or xprime as pivot",
"self",
".",
"_prime",
"=",
"(",
"random",
"(",
")",
"<",
"0.5",
")",
"if",
"self",
".",
"verbose",
">",
"1",
":",
"print_",
"(",
"\"\\n\\nUsing x%s as pivo... | Single iteration of t-walk algorithm | [
"Single",
"iteration",
"of",
"t",
"-",
"walk",
"algorithm"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L1800-L1896 |
239,077 | pymc-devs/pymc | pymc/StepMethods.py | Slicer.step | def step(self):
"""
Slice step method
From Neal 2003 (doi:10.1214/aos/1056562461)
"""
logy = self.loglike - rexponential(1)
L = self.stochastic.value - runiform(0, self.w)
R = L + self.w
if self.doubling:
# Doubling procedure
K = self.m
while (K and (logy < self.fll(L) or logy < self.fll(R))):
if random() < 0.5:
L -= R - L
else:
R += R - L
K -= 1
else:
# Stepping out procedure
J = np.floor(runiform(0, self.m))
K = (self.m - 1) - J
while(J > 0 and logy < self.fll(L)):
L -= self.w
J -= 1
while(K > 0 and logy < self.fll(R)):
R += self.w
K -= 1
# Shrinkage procedure
self.stochastic.value = runiform(L, R)
try:
logy_new = self.loglike
except ZeroProbability:
logy_new = -np.infty
while(logy_new < logy):
if (self.stochastic.value < self.stochastic.last_value):
L = float(self.stochastic.value)
else:
R = float(self.stochastic.value)
self.stochastic.revert()
self.stochastic.value = runiform(L, R)
try:
logy_new = self.loglike
except ZeroProbability:
logy_new = -np.infty | python | def step(self):
logy = self.loglike - rexponential(1)
L = self.stochastic.value - runiform(0, self.w)
R = L + self.w
if self.doubling:
# Doubling procedure
K = self.m
while (K and (logy < self.fll(L) or logy < self.fll(R))):
if random() < 0.5:
L -= R - L
else:
R += R - L
K -= 1
else:
# Stepping out procedure
J = np.floor(runiform(0, self.m))
K = (self.m - 1) - J
while(J > 0 and logy < self.fll(L)):
L -= self.w
J -= 1
while(K > 0 and logy < self.fll(R)):
R += self.w
K -= 1
# Shrinkage procedure
self.stochastic.value = runiform(L, R)
try:
logy_new = self.loglike
except ZeroProbability:
logy_new = -np.infty
while(logy_new < logy):
if (self.stochastic.value < self.stochastic.last_value):
L = float(self.stochastic.value)
else:
R = float(self.stochastic.value)
self.stochastic.revert()
self.stochastic.value = runiform(L, R)
try:
logy_new = self.loglike
except ZeroProbability:
logy_new = -np.infty | [
"def",
"step",
"(",
"self",
")",
":",
"logy",
"=",
"self",
".",
"loglike",
"-",
"rexponential",
"(",
"1",
")",
"L",
"=",
"self",
".",
"stochastic",
".",
"value",
"-",
"runiform",
"(",
"0",
",",
"self",
".",
"w",
")",
"R",
"=",
"L",
"+",
"self",... | Slice step method
From Neal 2003 (doi:10.1214/aos/1056562461) | [
"Slice",
"step",
"method"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L1960-L2007 |
239,078 | pymc-devs/pymc | pymc/StepMethods.py | Slicer.fll | def fll(self, value):
"""
Returns loglike of value
"""
self.stochastic.value = value
try:
ll = self.loglike
except ZeroProbability:
ll = -np.infty
self.stochastic.revert()
return ll | python | def fll(self, value):
self.stochastic.value = value
try:
ll = self.loglike
except ZeroProbability:
ll = -np.infty
self.stochastic.revert()
return ll | [
"def",
"fll",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"stochastic",
".",
"value",
"=",
"value",
"try",
":",
"ll",
"=",
"self",
".",
"loglike",
"except",
"ZeroProbability",
":",
"ll",
"=",
"-",
"np",
".",
"infty",
"self",
".",
"stochastic",
... | Returns loglike of value | [
"Returns",
"loglike",
"of",
"value"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L2009-L2019 |
239,079 | pymc-devs/pymc | pymc/StepMethods.py | Slicer.tune | def tune(self, verbose=None):
"""
Tuning initial slice width parameter
"""
if not self._tune:
return False
else:
self.w_tune.append(
abs(self.stochastic.last_value - self.stochastic.value))
self.w = 2 * (sum(self.w_tune) / len(self.w_tune))
return True | python | def tune(self, verbose=None):
if not self._tune:
return False
else:
self.w_tune.append(
abs(self.stochastic.last_value - self.stochastic.value))
self.w = 2 * (sum(self.w_tune) / len(self.w_tune))
return True | [
"def",
"tune",
"(",
"self",
",",
"verbose",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_tune",
":",
"return",
"False",
"else",
":",
"self",
".",
"w_tune",
".",
"append",
"(",
"abs",
"(",
"self",
".",
"stochastic",
".",
"last_value",
"-",
"se... | Tuning initial slice width parameter | [
"Tuning",
"initial",
"slice",
"width",
"parameter"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L2021-L2031 |
239,080 | pymc-devs/pymc | pymc/database/ram.py | Trace.tally | def tally(self, chain):
"""Store the object's current value to a chain.
:Parameters:
chain : integer
Chain index.
"""
value = self._getfunc()
try:
self._trace[chain][self._index[chain]] = value.copy()
except AttributeError:
self._trace[chain][self._index[chain]] = value
self._index[chain] += 1 | python | def tally(self, chain):
value = self._getfunc()
try:
self._trace[chain][self._index[chain]] = value.copy()
except AttributeError:
self._trace[chain][self._index[chain]] = value
self._index[chain] += 1 | [
"def",
"tally",
"(",
"self",
",",
"chain",
")",
":",
"value",
"=",
"self",
".",
"_getfunc",
"(",
")",
"try",
":",
"self",
".",
"_trace",
"[",
"chain",
"]",
"[",
"self",
".",
"_index",
"[",
"chain",
"]",
"]",
"=",
"value",
".",
"copy",
"(",
")",... | Store the object's current value to a chain.
:Parameters:
chain : integer
Chain index. | [
"Store",
"the",
"object",
"s",
"current",
"value",
"to",
"a",
"chain",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/ram.py#L86-L100 |
239,081 | pymc-devs/pymc | pymc/database/ram.py | Trace.truncate | def truncate(self, index, chain):
"""
Truncate the trace array to some index.
:Parameters:
index : int
The index within the chain after which all values will be removed.
chain : int
The chain index (>=0).
"""
self._trace[chain] = self._trace[chain][:index] | python | def truncate(self, index, chain):
self._trace[chain] = self._trace[chain][:index] | [
"def",
"truncate",
"(",
"self",
",",
"index",
",",
"chain",
")",
":",
"self",
".",
"_trace",
"[",
"chain",
"]",
"=",
"self",
".",
"_trace",
"[",
"chain",
"]",
"[",
":",
"index",
"]"
] | Truncate the trace array to some index.
:Parameters:
index : int
The index within the chain after which all values will be removed.
chain : int
The chain index (>=0). | [
"Truncate",
"the",
"trace",
"array",
"to",
"some",
"index",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/ram.py#L102-L112 |
239,082 | pymc-devs/pymc | pymc/database/ram.py | Trace.gettrace | def gettrace(self, burn=0, thin=1, chain=-1, slicing=None):
"""Return the trace.
:Stochastics:
- burn (int): The number of transient steps to skip.
- thin (int): Keep one in thin.
- chain (int): The index of the chain to fetch. If None, return all chains.
- slicing: A slice, overriding burn and thin assignement.
"""
if slicing is None:
slicing = slice(burn, None, thin)
if chain is not None:
if chain < 0:
chain = range(self.db.chains)[chain]
return self._trace[chain][slicing]
else:
return concatenate(list(self._trace.values()))[slicing] | python | def gettrace(self, burn=0, thin=1, chain=-1, slicing=None):
if slicing is None:
slicing = slice(burn, None, thin)
if chain is not None:
if chain < 0:
chain = range(self.db.chains)[chain]
return self._trace[chain][slicing]
else:
return concatenate(list(self._trace.values()))[slicing] | [
"def",
"gettrace",
"(",
"self",
",",
"burn",
"=",
"0",
",",
"thin",
"=",
"1",
",",
"chain",
"=",
"-",
"1",
",",
"slicing",
"=",
"None",
")",
":",
"if",
"slicing",
"is",
"None",
":",
"slicing",
"=",
"slice",
"(",
"burn",
",",
"None",
",",
"thin"... | Return the trace.
:Stochastics:
- burn (int): The number of transient steps to skip.
- thin (int): Keep one in thin.
- chain (int): The index of the chain to fetch. If None, return all chains.
- slicing: A slice, overriding burn and thin assignement. | [
"Return",
"the",
"trace",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/ram.py#L114-L130 |
239,083 | pymc-devs/pymc | pymc/database/hdf5ea.py | load | def load(dbname, dbmode='a'):
"""Load an existing hdf5 database.
Return a Database instance.
:Parameters:
filename : string
Name of the hdf5 database to open.
mode : 'a', 'r'
File mode : 'a': append, 'r': read-only.
"""
if dbmode == 'w':
raise AttributeError("dbmode='w' not allowed for load.")
db = Database(dbname, dbmode=dbmode)
return db | python | def load(dbname, dbmode='a'):
if dbmode == 'w':
raise AttributeError("dbmode='w' not allowed for load.")
db = Database(dbname, dbmode=dbmode)
return db | [
"def",
"load",
"(",
"dbname",
",",
"dbmode",
"=",
"'a'",
")",
":",
"if",
"dbmode",
"==",
"'w'",
":",
"raise",
"AttributeError",
"(",
"\"dbmode='w' not allowed for load.\"",
")",
"db",
"=",
"Database",
"(",
"dbname",
",",
"dbmode",
"=",
"dbmode",
")",
"retu... | Load an existing hdf5 database.
Return a Database instance.
:Parameters:
filename : string
Name of the hdf5 database to open.
mode : 'a', 'r'
File mode : 'a': append, 'r': read-only. | [
"Load",
"an",
"existing",
"hdf5",
"database",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/hdf5ea.py#L300-L315 |
239,084 | pymc-devs/pymc | pymc/database/txt.py | load | def load(dirname):
"""Create a Database instance from the data stored in the directory."""
if not os.path.exists(dirname):
raise AttributeError('No txt database named %s' % dirname)
db = Database(dirname, dbmode='a')
chain_folders = [os.path.join(dirname, c) for c in db.get_chains()]
db.chains = len(chain_folders)
data = {}
for chain, folder in enumerate(chain_folders):
files = os.listdir(folder)
funnames = funname(files)
db.trace_names.append(funnames)
for file in files:
name = funname(file)
if name not in data:
data[
name] = {
} # This could be simplified using "collections.defaultdict(dict)". New in Python 2.5
# Read the shape information
with open(os.path.join(folder, file)) as f:
f.readline()
shape = eval(f.readline()[16:])
data[
name][
chain] = np.loadtxt(
os.path.join(
folder,
file),
delimiter=',').reshape(
shape)
f.close()
# Create the Traces.
for name, values in six.iteritems(data):
db._traces[name] = Trace(name=name, value=values, db=db)
setattr(db, name, db._traces[name])
# Load the state.
statefile = os.path.join(dirname, 'state.txt')
if os.path.exists(statefile):
with open(statefile, 'r') as f:
db._state_ = eval(f.read())
else:
db._state_ = {}
return db | python | def load(dirname):
if not os.path.exists(dirname):
raise AttributeError('No txt database named %s' % dirname)
db = Database(dirname, dbmode='a')
chain_folders = [os.path.join(dirname, c) for c in db.get_chains()]
db.chains = len(chain_folders)
data = {}
for chain, folder in enumerate(chain_folders):
files = os.listdir(folder)
funnames = funname(files)
db.trace_names.append(funnames)
for file in files:
name = funname(file)
if name not in data:
data[
name] = {
} # This could be simplified using "collections.defaultdict(dict)". New in Python 2.5
# Read the shape information
with open(os.path.join(folder, file)) as f:
f.readline()
shape = eval(f.readline()[16:])
data[
name][
chain] = np.loadtxt(
os.path.join(
folder,
file),
delimiter=',').reshape(
shape)
f.close()
# Create the Traces.
for name, values in six.iteritems(data):
db._traces[name] = Trace(name=name, value=values, db=db)
setattr(db, name, db._traces[name])
# Load the state.
statefile = os.path.join(dirname, 'state.txt')
if os.path.exists(statefile):
with open(statefile, 'r') as f:
db._state_ = eval(f.read())
else:
db._state_ = {}
return db | [
"def",
"load",
"(",
"dirname",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dirname",
")",
":",
"raise",
"AttributeError",
"(",
"'No txt database named %s'",
"%",
"dirname",
")",
"db",
"=",
"Database",
"(",
"dirname",
",",
"dbmode",
"="... | Create a Database instance from the data stored in the directory. | [
"Create",
"a",
"Database",
"instance",
"from",
"the",
"data",
"stored",
"in",
"the",
"directory",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/txt.py#L148-L195 |
239,085 | pymc-devs/pymc | pymc/database/txt.py | funname | def funname(file):
"""Return variable names from file names."""
if isinstance(file, str):
files = [file]
else:
files = file
bases = [os.path.basename(f) for f in files]
names = [os.path.splitext(b)[0] for b in bases]
if isinstance(file, str):
return names[0]
else:
return names | python | def funname(file):
if isinstance(file, str):
files = [file]
else:
files = file
bases = [os.path.basename(f) for f in files]
names = [os.path.splitext(b)[0] for b in bases]
if isinstance(file, str):
return names[0]
else:
return names | [
"def",
"funname",
"(",
"file",
")",
":",
"if",
"isinstance",
"(",
"file",
",",
"str",
")",
":",
"files",
"=",
"[",
"file",
"]",
"else",
":",
"files",
"=",
"file",
"bases",
"=",
"[",
"os",
".",
"path",
".",
"basename",
"(",
"f",
")",
"for",
"f",... | Return variable names from file names. | [
"Return",
"variable",
"names",
"from",
"file",
"names",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/txt.py#L198-L209 |
239,086 | pymc-devs/pymc | pymc/database/txt.py | Trace._finalize | def _finalize(self, chain):
"""Write the trace to an ASCII file.
:Parameter:
chain : int
The chain index.
"""
path = os.path.join(
self.db._directory,
self.db.get_chains()[chain],
self.name + '.txt')
arr = self.gettrace(chain=chain)
# Following numpy's example.
if six.PY3:
mode = 'wb'
else:
mode = 'w'
with open(path, mode) as f:
f.write(six.b('# Variable: %s\n' % self.name))
f.write(six.b('# Sample shape: %s\n' % str(arr.shape)))
f.write(six.b('# Date: %s\n' % datetime.datetime.now()))
np.savetxt(f, arr.reshape((-1, arr[0].size)), delimiter=',') | python | def _finalize(self, chain):
path = os.path.join(
self.db._directory,
self.db.get_chains()[chain],
self.name + '.txt')
arr = self.gettrace(chain=chain)
# Following numpy's example.
if six.PY3:
mode = 'wb'
else:
mode = 'w'
with open(path, mode) as f:
f.write(six.b('# Variable: %s\n' % self.name))
f.write(six.b('# Sample shape: %s\n' % str(arr.shape)))
f.write(six.b('# Date: %s\n' % datetime.datetime.now()))
np.savetxt(f, arr.reshape((-1, arr[0].size)), delimiter=',') | [
"def",
"_finalize",
"(",
"self",
",",
"chain",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"db",
".",
"_directory",
",",
"self",
".",
"db",
".",
"get_chains",
"(",
")",
"[",
"chain",
"]",
",",
"self",
".",
"name",
"... | Write the trace to an ASCII file.
:Parameter:
chain : int
The chain index. | [
"Write",
"the",
"trace",
"to",
"an",
"ASCII",
"file",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/txt.py#L59-L81 |
239,087 | pymc-devs/pymc | pymc/database/txt.py | Database._initialize | def _initialize(self, funs_to_tally, length):
"""Create folder to store simulation results."""
dir = os.path.join(self._directory, CHAIN_NAME % self.chains)
os.mkdir(dir)
base.Database._initialize(self, funs_to_tally, length) | python | def _initialize(self, funs_to_tally, length):
dir = os.path.join(self._directory, CHAIN_NAME % self.chains)
os.mkdir(dir)
base.Database._initialize(self, funs_to_tally, length) | [
"def",
"_initialize",
"(",
"self",
",",
"funs_to_tally",
",",
"length",
")",
":",
"dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_directory",
",",
"CHAIN_NAME",
"%",
"self",
".",
"chains",
")",
"os",
".",
"mkdir",
"(",
"dir",
")",
"... | Create folder to store simulation results. | [
"Create",
"folder",
"to",
"store",
"simulation",
"results",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/txt.py#L129-L135 |
239,088 | pymc-devs/pymc | pymc/database/txt.py | Database.savestate | def savestate(self, state):
"""Save the sampler's state in a state.txt file."""
oldstate = np.get_printoptions()
np.set_printoptions(threshold=1e6)
try:
with open(os.path.join(self._directory, 'state.txt'), 'w') as f:
print_(state, file=f)
finally:
np.set_printoptions(**oldstate) | python | def savestate(self, state):
oldstate = np.get_printoptions()
np.set_printoptions(threshold=1e6)
try:
with open(os.path.join(self._directory, 'state.txt'), 'w') as f:
print_(state, file=f)
finally:
np.set_printoptions(**oldstate) | [
"def",
"savestate",
"(",
"self",
",",
"state",
")",
":",
"oldstate",
"=",
"np",
".",
"get_printoptions",
"(",
")",
"np",
".",
"set_printoptions",
"(",
"threshold",
"=",
"1e6",
")",
"try",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",... | Save the sampler's state in a state.txt file. | [
"Save",
"the",
"sampler",
"s",
"state",
"in",
"a",
"state",
".",
"txt",
"file",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/txt.py#L137-L145 |
239,089 | pymc-devs/pymc | pymc/examples/disaster_model_missing.py | rate | def rate(s=switch, e=early_mean, l=late_mean):
"""Allocate appropriate mean to time series"""
out = np.empty(len(disasters_array))
# Early mean prior to switchpoint
out[:s] = e
# Late mean following switchpoint
out[s:] = l
return out | python | def rate(s=switch, e=early_mean, l=late_mean):
out = np.empty(len(disasters_array))
# Early mean prior to switchpoint
out[:s] = e
# Late mean following switchpoint
out[s:] = l
return out | [
"def",
"rate",
"(",
"s",
"=",
"switch",
",",
"e",
"=",
"early_mean",
",",
"l",
"=",
"late_mean",
")",
":",
"out",
"=",
"np",
".",
"empty",
"(",
"len",
"(",
"disasters_array",
")",
")",
"# Early mean prior to switchpoint",
"out",
"[",
":",
"s",
"]",
"... | Allocate appropriate mean to time series | [
"Allocate",
"appropriate",
"mean",
"to",
"time",
"series"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/examples/disaster_model_missing.py#L36-L43 |
239,090 | pymc-devs/pymc | pymc/gp/GPutils.py | fast_matrix_copy | def fast_matrix_copy(f, t=None, n_threads=1):
"""
Not any faster than a serial copy so far.
"""
if not f.flags['F_CONTIGUOUS']:
raise RuntimeError(
'This will not be fast unless input array f is Fortran-contiguous.')
if t is None:
t = asmatrix(empty(f.shape, order='F'))
elif not t.flags['F_CONTIGUOUS']:
raise RuntimeError(
'This will not be fast unless input array t is Fortran-contiguous.')
# Figure out how to divide job up between threads.
dcopy_wrap(ravel(asarray(f.T)), ravel(asarray(t.T)))
return t | python | def fast_matrix_copy(f, t=None, n_threads=1):
if not f.flags['F_CONTIGUOUS']:
raise RuntimeError(
'This will not be fast unless input array f is Fortran-contiguous.')
if t is None:
t = asmatrix(empty(f.shape, order='F'))
elif not t.flags['F_CONTIGUOUS']:
raise RuntimeError(
'This will not be fast unless input array t is Fortran-contiguous.')
# Figure out how to divide job up between threads.
dcopy_wrap(ravel(asarray(f.T)), ravel(asarray(t.T)))
return t | [
"def",
"fast_matrix_copy",
"(",
"f",
",",
"t",
"=",
"None",
",",
"n_threads",
"=",
"1",
")",
":",
"if",
"not",
"f",
".",
"flags",
"[",
"'F_CONTIGUOUS'",
"]",
":",
"raise",
"RuntimeError",
"(",
"'This will not be fast unless input array f is Fortran-contiguous.'",
... | Not any faster than a serial copy so far. | [
"Not",
"any",
"faster",
"than",
"a",
"serial",
"copy",
"so",
"far",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/gp/GPutils.py#L34-L50 |
239,091 | pymc-devs/pymc | pymc/gp/GPutils.py | vecs_to_datmesh | def vecs_to_datmesh(x, y):
"""
Converts input arguments x and y to a 2d meshgrid,
suitable for calling Means, Covariances and Realizations.
"""
x, y = meshgrid(x, y)
out = zeros(x.shape + (2,), dtype=float)
out[:, :, 0] = x
out[:, :, 1] = y
return out | python | def vecs_to_datmesh(x, y):
x, y = meshgrid(x, y)
out = zeros(x.shape + (2,), dtype=float)
out[:, :, 0] = x
out[:, :, 1] = y
return out | [
"def",
"vecs_to_datmesh",
"(",
"x",
",",
"y",
")",
":",
"x",
",",
"y",
"=",
"meshgrid",
"(",
"x",
",",
"y",
")",
"out",
"=",
"zeros",
"(",
"x",
".",
"shape",
"+",
"(",
"2",
",",
")",
",",
"dtype",
"=",
"float",
")",
"out",
"[",
":",
",",
... | Converts input arguments x and y to a 2d meshgrid,
suitable for calling Means, Covariances and Realizations. | [
"Converts",
"input",
"arguments",
"x",
"and",
"y",
"to",
"a",
"2d",
"meshgrid",
"suitable",
"for",
"calling",
"Means",
"Covariances",
"and",
"Realizations",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/gp/GPutils.py#L150-L159 |
239,092 | pymc-devs/pymc | pymc/database/base.py | batchsd | def batchsd(trace, batches=5):
"""
Calculates the simulation standard error, accounting for non-independent
samples. The trace is divided into batches, and the standard deviation of
the batch means is calculated.
"""
if len(np.shape(trace)) > 1:
dims = np.shape(trace)
# ttrace = np.transpose(np.reshape(trace, (dims[0], sum(dims[1:]))))
ttrace = np.transpose([t.ravel() for t in trace])
return np.reshape([batchsd(t, batches) for t in ttrace], dims[1:])
else:
if batches == 1:
return np.std(trace) / np.sqrt(len(trace))
try:
batched_traces = np.resize(trace, (batches, int(len(trace) / batches)))
except ValueError:
# If batches do not divide evenly, trim excess samples
resid = len(trace) % batches
batched_traces = np.resize(trace[:-resid],
(batches, len(trace[:-resid]) / batches))
means = np.mean(batched_traces, 1)
return np.std(means) / np.sqrt(batches) | python | def batchsd(trace, batches=5):
if len(np.shape(trace)) > 1:
dims = np.shape(trace)
# ttrace = np.transpose(np.reshape(trace, (dims[0], sum(dims[1:]))))
ttrace = np.transpose([t.ravel() for t in trace])
return np.reshape([batchsd(t, batches) for t in ttrace], dims[1:])
else:
if batches == 1:
return np.std(trace) / np.sqrt(len(trace))
try:
batched_traces = np.resize(trace, (batches, int(len(trace) / batches)))
except ValueError:
# If batches do not divide evenly, trim excess samples
resid = len(trace) % batches
batched_traces = np.resize(trace[:-resid],
(batches, len(trace[:-resid]) / batches))
means = np.mean(batched_traces, 1)
return np.std(means) / np.sqrt(batches) | [
"def",
"batchsd",
"(",
"trace",
",",
"batches",
"=",
"5",
")",
":",
"if",
"len",
"(",
"np",
".",
"shape",
"(",
"trace",
")",
")",
">",
"1",
":",
"dims",
"=",
"np",
".",
"shape",
"(",
"trace",
")",
"# ttrace = np.transpose(np.reshape(trace, (dims[0], sum(... | Calculates the simulation standard error, accounting for non-independent
samples. The trace is divided into batches, and the standard deviation of
the batch means is calculated. | [
"Calculates",
"the",
"simulation",
"standard",
"error",
"accounting",
"for",
"non",
"-",
"independent",
"samples",
".",
"The",
"trace",
"is",
"divided",
"into",
"batches",
"and",
"the",
"standard",
"deviation",
"of",
"the",
"batch",
"means",
"is",
"calculated",
... | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/base.py#L395-L424 |
239,093 | pymc-devs/pymc | pymc/database/base.py | Trace._initialize | def _initialize(self, chain, length):
"""Prepare for tallying. Create a new chain."""
# If this db was loaded from the disk, it may not have its
# tallied step methods' getfuncs yet.
if self._getfunc is None:
self._getfunc = self.db.model._funs_to_tally[self.name] | python | def _initialize(self, chain, length):
# If this db was loaded from the disk, it may not have its
# tallied step methods' getfuncs yet.
if self._getfunc is None:
self._getfunc = self.db.model._funs_to_tally[self.name] | [
"def",
"_initialize",
"(",
"self",
",",
"chain",
",",
"length",
")",
":",
"# If this db was loaded from the disk, it may not have its",
"# tallied step methods' getfuncs yet.",
"if",
"self",
".",
"_getfunc",
"is",
"None",
":",
"self",
".",
"_getfunc",
"=",
"self",
"."... | Prepare for tallying. Create a new chain. | [
"Prepare",
"for",
"tallying",
".",
"Create",
"a",
"new",
"chain",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/base.py#L88-L93 |
239,094 | pymc-devs/pymc | pymc/database/base.py | Database._initialize | def _initialize(self, funs_to_tally, length=None):
"""Initialize the tallyable objects.
Makes sure a Trace object exists for each variable and then initialize
the Traces.
:Parameters:
funs_to_tally : dict
Name- function pairs.
length : int
The expected length of the chain. Some database may need the argument
to preallocate memory.
"""
for name, fun in six.iteritems(funs_to_tally):
if name not in self._traces:
self._traces[
name] = self.__Trace__(
name=name,
getfunc=fun,
db=self)
self._traces[name]._initialize(self.chains, length)
self.trace_names.append(list(funs_to_tally.keys()))
self.chains += 1 | python | def _initialize(self, funs_to_tally, length=None):
for name, fun in six.iteritems(funs_to_tally):
if name not in self._traces:
self._traces[
name] = self.__Trace__(
name=name,
getfunc=fun,
db=self)
self._traces[name]._initialize(self.chains, length)
self.trace_names.append(list(funs_to_tally.keys()))
self.chains += 1 | [
"def",
"_initialize",
"(",
"self",
",",
"funs_to_tally",
",",
"length",
"=",
"None",
")",
":",
"for",
"name",
",",
"fun",
"in",
"six",
".",
"iteritems",
"(",
"funs_to_tally",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"_traces",
":",
"self",
"... | Initialize the tallyable objects.
Makes sure a Trace object exists for each variable and then initialize
the Traces.
:Parameters:
funs_to_tally : dict
Name- function pairs.
length : int
The expected length of the chain. Some database may need the argument
to preallocate memory. | [
"Initialize",
"the",
"tallyable",
"objects",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/base.py#L232-L258 |
239,095 | pymc-devs/pymc | pymc/database/base.py | Database._finalize | def _finalize(self, chain=-1):
"""Finalize the chain for all tallyable objects."""
chain = range(self.chains)[chain]
for name in self.trace_names[chain]:
self._traces[name]._finalize(chain)
self.commit() | python | def _finalize(self, chain=-1):
chain = range(self.chains)[chain]
for name in self.trace_names[chain]:
self._traces[name]._finalize(chain)
self.commit() | [
"def",
"_finalize",
"(",
"self",
",",
"chain",
"=",
"-",
"1",
")",
":",
"chain",
"=",
"range",
"(",
"self",
".",
"chains",
")",
"[",
"chain",
"]",
"for",
"name",
"in",
"self",
".",
"trace_names",
"[",
"chain",
"]",
":",
"self",
".",
"_traces",
"[... | Finalize the chain for all tallyable objects. | [
"Finalize",
"the",
"chain",
"for",
"all",
"tallyable",
"objects",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/base.py#L332-L337 |
239,096 | pymc-devs/pymc | pymc/database/base.py | Database.truncate | def truncate(self, index, chain=-1):
"""Tell the traces to truncate themselves at the given index."""
chain = range(self.chains)[chain]
for name in self.trace_names[chain]:
self._traces[name].truncate(index, chain) | python | def truncate(self, index, chain=-1):
chain = range(self.chains)[chain]
for name in self.trace_names[chain]:
self._traces[name].truncate(index, chain) | [
"def",
"truncate",
"(",
"self",
",",
"index",
",",
"chain",
"=",
"-",
"1",
")",
":",
"chain",
"=",
"range",
"(",
"self",
".",
"chains",
")",
"[",
"chain",
"]",
"for",
"name",
"in",
"self",
".",
"trace_names",
"[",
"chain",
"]",
":",
"self",
".",
... | Tell the traces to truncate themselves at the given index. | [
"Tell",
"the",
"traces",
"to",
"truncate",
"themselves",
"at",
"the",
"given",
"index",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/base.py#L339-L343 |
239,097 | pymc-devs/pymc | pymc/gp/Mean.py | Mean.observe | def observe(self, C, obs_mesh_new, obs_vals_new, mean_under=None):
"""
Synchronizes self's observation status with C's.
Values of observation are given by obs_vals.
obs_mesh_new and obs_vals_new should already have
been sliced, as Covariance.observe(..., output_type='o') does.
"""
self.C = C
self.obs_mesh = C.obs_mesh
self.obs_len = C.obs_len
self.Uo = C.Uo
# Evaluate the underlying mean function on the new observation mesh.
if mean_under is None:
mean_under_new = C._mean_under_new(self, obs_mesh_new)
else:
mean_under_new = mean_under
# If self hasn't been observed yet:
if not self.observed:
self.dev = (obs_vals_new - mean_under_new)
self.reg_mat = C._unobs_reg(self)
# If self has been observed already:
elif len(obs_vals_new) > 0:
# Rank of old observations.
m_old = len(self.dev)
# Deviation of new observation from mean without regard to old
# observations.
dev_new = (obs_vals_new - mean_under_new)
# Again, basis covariances get special treatment.
self.reg_mat = C._obs_reg(self, dev_new, m_old)
# Stack deviations of old and new observations from unobserved
# mean.
self.dev = hstack((self.dev, dev_new))
self.observed = True | python | def observe(self, C, obs_mesh_new, obs_vals_new, mean_under=None):
self.C = C
self.obs_mesh = C.obs_mesh
self.obs_len = C.obs_len
self.Uo = C.Uo
# Evaluate the underlying mean function on the new observation mesh.
if mean_under is None:
mean_under_new = C._mean_under_new(self, obs_mesh_new)
else:
mean_under_new = mean_under
# If self hasn't been observed yet:
if not self.observed:
self.dev = (obs_vals_new - mean_under_new)
self.reg_mat = C._unobs_reg(self)
# If self has been observed already:
elif len(obs_vals_new) > 0:
# Rank of old observations.
m_old = len(self.dev)
# Deviation of new observation from mean without regard to old
# observations.
dev_new = (obs_vals_new - mean_under_new)
# Again, basis covariances get special treatment.
self.reg_mat = C._obs_reg(self, dev_new, m_old)
# Stack deviations of old and new observations from unobserved
# mean.
self.dev = hstack((self.dev, dev_new))
self.observed = True | [
"def",
"observe",
"(",
"self",
",",
"C",
",",
"obs_mesh_new",
",",
"obs_vals_new",
",",
"mean_under",
"=",
"None",
")",
":",
"self",
".",
"C",
"=",
"C",
"self",
".",
"obs_mesh",
"=",
"C",
".",
"obs_mesh",
"self",
".",
"obs_len",
"=",
"C",
".",
"obs... | Synchronizes self's observation status with C's.
Values of observation are given by obs_vals.
obs_mesh_new and obs_vals_new should already have
been sliced, as Covariance.observe(..., output_type='o') does. | [
"Synchronizes",
"self",
"s",
"observation",
"status",
"with",
"C",
"s",
".",
"Values",
"of",
"observation",
"are",
"given",
"by",
"obs_vals",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/gp/Mean.py#L49-L93 |
239,098 | pymc-devs/pymc | pymc/InstantiationDecorators.py | _extract | def _extract(__func__, kwds, keys, classname, probe=True):
"""
Used by decorators stochastic and deterministic to inspect declarations
"""
# Add docs and name
kwds['doc'] = __func__.__doc__
if not 'name' in kwds:
kwds['name'] = __func__.__name__
# kwds.update({'doc':__func__.__doc__, 'name':__func__.__name__})
# Instanitate dictionary of parents
parents = {}
# This gets used by stochastic to check for long-format logp and random:
if probe:
cur_status = check_special_methods()
disable_special_methods()
# Define global tracing function (I assume this is for debugging??)
# No, it's to get out the logp and random functions, if they're in
# there.
def probeFunc(frame, event, arg):
if event == 'return':
locals = frame.f_locals
kwds.update(dict((k, locals.get(k)) for k in keys))
sys.settrace(None)
return probeFunc
sys.settrace(probeFunc)
# Get the functions logp and random (complete interface).
# Disable special methods to prevent the formation of a hurricane of
# Deterministics
try:
__func__()
except:
if 'logp' in keys:
kwds['logp'] = __func__
else:
kwds['eval'] = __func__
# Reenable special methods.
if cur_status:
enable_special_methods()
for key in keys:
if not key in kwds:
kwds[key] = None
for key in ['logp', 'eval']:
if key in keys:
if kwds[key] is None:
kwds[key] = __func__
# Build parents dictionary by parsing the __func__tion's arguments.
(args, defaults) = get_signature(__func__)
if defaults is None:
defaults = ()
# Make sure all parents were defined
arg_deficit = (len(args) - ('value' in args)) - len(defaults)
if arg_deficit > 0:
err_str = classname + ' ' + __func__.__name__ + \
': no parent provided for the following labels:'
for i in range(arg_deficit):
err_str += " " + args[i + ('value' in args)]
if i < arg_deficit - 1:
err_str += ','
raise ValueError(err_str)
# Fill in parent dictionary
try:
parents.update(dict(zip(args[-len(defaults):], defaults)))
except TypeError:
pass
value = parents.pop('value', None)
return (value, parents) | python | def _extract(__func__, kwds, keys, classname, probe=True):
# Add docs and name
kwds['doc'] = __func__.__doc__
if not 'name' in kwds:
kwds['name'] = __func__.__name__
# kwds.update({'doc':__func__.__doc__, 'name':__func__.__name__})
# Instanitate dictionary of parents
parents = {}
# This gets used by stochastic to check for long-format logp and random:
if probe:
cur_status = check_special_methods()
disable_special_methods()
# Define global tracing function (I assume this is for debugging??)
# No, it's to get out the logp and random functions, if they're in
# there.
def probeFunc(frame, event, arg):
if event == 'return':
locals = frame.f_locals
kwds.update(dict((k, locals.get(k)) for k in keys))
sys.settrace(None)
return probeFunc
sys.settrace(probeFunc)
# Get the functions logp and random (complete interface).
# Disable special methods to prevent the formation of a hurricane of
# Deterministics
try:
__func__()
except:
if 'logp' in keys:
kwds['logp'] = __func__
else:
kwds['eval'] = __func__
# Reenable special methods.
if cur_status:
enable_special_methods()
for key in keys:
if not key in kwds:
kwds[key] = None
for key in ['logp', 'eval']:
if key in keys:
if kwds[key] is None:
kwds[key] = __func__
# Build parents dictionary by parsing the __func__tion's arguments.
(args, defaults) = get_signature(__func__)
if defaults is None:
defaults = ()
# Make sure all parents were defined
arg_deficit = (len(args) - ('value' in args)) - len(defaults)
if arg_deficit > 0:
err_str = classname + ' ' + __func__.__name__ + \
': no parent provided for the following labels:'
for i in range(arg_deficit):
err_str += " " + args[i + ('value' in args)]
if i < arg_deficit - 1:
err_str += ','
raise ValueError(err_str)
# Fill in parent dictionary
try:
parents.update(dict(zip(args[-len(defaults):], defaults)))
except TypeError:
pass
value = parents.pop('value', None)
return (value, parents) | [
"def",
"_extract",
"(",
"__func__",
",",
"kwds",
",",
"keys",
",",
"classname",
",",
"probe",
"=",
"True",
")",
":",
"# Add docs and name",
"kwds",
"[",
"'doc'",
"]",
"=",
"__func__",
".",
"__doc__",
"if",
"not",
"'name'",
"in",
"kwds",
":",
"kwds",
"[... | Used by decorators stochastic and deterministic to inspect declarations | [
"Used",
"by",
"decorators",
"stochastic",
"and",
"deterministic",
"to",
"inspect",
"declarations"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/InstantiationDecorators.py#L47-L126 |
239,099 | pymc-devs/pymc | pymc/InstantiationDecorators.py | observed | def observed(obj=None, **kwds):
"""
Decorator function to instantiate data objects.
If given a Stochastic, sets a the observed flag to True.
Can be used as
@observed
def A(value = ., parent_name = ., ...):
return foo(value, parent_name, ...)
or as
@stochastic(observed=True)
def A(value = ., parent_name = ., ...):
return foo(value, parent_name, ...)
:SeeAlso:
stochastic, Stochastic, dtrm, Deterministic, potential, Potential, Model,
distributions
"""
if obj is not None:
if isinstance(obj, Stochastic):
obj._observed = True
return obj
else:
p = stochastic(__func__=obj, observed=True, **kwds)
return p
kwds['observed'] = True
def instantiate_observed(func):
return stochastic(func, **kwds)
return instantiate_observed | python | def observed(obj=None, **kwds):
if obj is not None:
if isinstance(obj, Stochastic):
obj._observed = True
return obj
else:
p = stochastic(__func__=obj, observed=True, **kwds)
return p
kwds['observed'] = True
def instantiate_observed(func):
return stochastic(func, **kwds)
return instantiate_observed | [
"def",
"observed",
"(",
"obj",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"if",
"obj",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"obj",
",",
"Stochastic",
")",
":",
"obj",
".",
"_observed",
"=",
"True",
"return",
"obj",
"else",
":",
"... | Decorator function to instantiate data objects.
If given a Stochastic, sets a the observed flag to True.
Can be used as
@observed
def A(value = ., parent_name = ., ...):
return foo(value, parent_name, ...)
or as
@stochastic(observed=True)
def A(value = ., parent_name = ., ...):
return foo(value, parent_name, ...)
:SeeAlso:
stochastic, Stochastic, dtrm, Deterministic, potential, Potential, Model,
distributions | [
"Decorator",
"function",
"to",
"instantiate",
"data",
"objects",
".",
"If",
"given",
"a",
"Stochastic",
"sets",
"a",
"the",
"observed",
"flag",
"to",
"True",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/InstantiationDecorators.py#L259-L295 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.