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
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
225,200
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): """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
[ "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
225,201
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): """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
[ "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
225,202
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): """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
[ "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
225,203
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): """Generator for rows of the stop_times file""" 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
225,204
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): """Return a tuple of Stop objects, in the order visited""" 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
225,205
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): """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)
[ "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
225,206
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): """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)
[ "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
225,207
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): """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)
[ "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
225,208
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): """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)
[ "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
225,209
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): """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)
[ "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
225,210
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): """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)
[ "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
225,211
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): """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)
[ "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
225,212
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): """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
[ "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
225,213
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): """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
[ "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
225,214
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' ): """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)
[ "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
225,215
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): """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
[ "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
225,216
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): """ 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))
[ "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
225,217
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): """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)
[ "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
225,218
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): """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)
[ "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
225,219
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'): """ 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
[ "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
225,220
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): """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
[ "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
225,221
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): """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
[ "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
225,222
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): """ 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)
[ "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
225,223
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'): """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)
[ "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
225,224
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): """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
[ "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
225,225
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): """ 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
[ "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
225,226
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): """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))
[ "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
225,227
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): """ An eager version of Trace Returns ------- raw : RawTrace """ 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
225,228
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): """ 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()
[ "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
225,229
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): """ 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]
[ "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
225,230
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): """ 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
[ "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
225,231
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): """ 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
[ "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
225,232
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): """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.")
[ "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
225,233
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): """ 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
[ "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
225,234
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): """ 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
[ "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
225,235
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
225,236
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
225,237
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): """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
[ "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
225,238
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): """ 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.')
[ "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
225,239
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): """ 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
[ "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
225,240
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): """ 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
[ "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
225,241
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): """ 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
[ "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
225,242
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): """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
[ "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
225,243
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): """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
[ "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
225,244
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)): """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)
[ "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
225,245
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): """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
[ "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
225,246
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): """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
[ "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
225,247
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): """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 = []
[ "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
225,248
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
225,249
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
225,250
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): """ 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
[ "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
225,251
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): """ 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
[ "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
225,252
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): """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))
[ "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
225,253
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): """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)
[ "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
225,254
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): """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
[ "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
225,255
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): """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
[ "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
225,256
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): """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)
[ "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
225,257
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): """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
[ "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
225,258
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): """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)
[ "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
225,259
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): """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)
[ "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
225,260
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): """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
[ "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
225,261
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): """ 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
[ "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
225,262
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): """ Returns loglike of 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
225,263
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): """ 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
[ "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
225,264
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): """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
[ "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
225,265
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): """ 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]
[ "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
225,266
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): """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]
[ "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
225,267
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'): """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
[ "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
225,268
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): """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
[ "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
225,269
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): """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
[ "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
225,270
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): """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=',')
[ "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
225,271
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): """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)
[ "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
225,272
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): """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)
[ "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
225,273
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): """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
[ "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
225,274
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): """ 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
[ "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
225,275
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): """ 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
[ "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
225,276
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): """ 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)
[ "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
225,277
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): """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]
[ "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
225,278
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): """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
[ "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
225,279
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): """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()
[ "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
225,280
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): """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)
[ "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
225,281
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): """ 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
[ "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
225,282
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): """ 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)
[ "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
225,283
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): """ 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
[ "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
225,284
pymc-devs/pymc
pymc/InstantiationDecorators.py
robust_init
def robust_init(stochclass, tries, *args, **kwds): """Robust initialization of a Stochastic. If the evaluation of the log-probability returns a ZeroProbability error, due for example to a parent being outside of the support for this Stochastic, the values of parents are randomly sampled until a valid log-probability is obtained. If the log-probability is still not valid after `tries` attempts, the original ZeroProbability error is raised. :Parameters: stochclass : Stochastic, eg. Normal, Uniform, ... The Stochastic distribution to instantiate. tries : int Maximum number of times parents will be sampled. *args, **kwds Positional and keyword arguments to declare the Stochastic variable. :Example: >>> lower = pymc.Uniform('lower', 0., 2., value=1.5, rseed=True) >>> pymc.robust_init(pymc.Uniform, 100, 'data', lower=lower, upper=5, value=[1,2,3,4], observed=True) """ # Find the direct parents stochs = [arg for arg in (list(args) + list(kwds.values())) if isinstance(arg.__class__, StochasticMeta)] # Find the extended parents parents = stochs for s in stochs: parents.extend(s.extended_parents) extended_parents = set(parents) # Select the parents with a random method. random_parents = [ p for p in extended_parents if p.rseed is True and hasattr( p, 'random')] for i in range(tries): try: return stochclass(*args, **kwds) except ZeroProbability: exc = sys.exc_info() for parent in random_parents: try: parent.random() except: six.reraise(*exc) six.reraise(*exc)
python
def robust_init(stochclass, tries, *args, **kwds): """Robust initialization of a Stochastic. If the evaluation of the log-probability returns a ZeroProbability error, due for example to a parent being outside of the support for this Stochastic, the values of parents are randomly sampled until a valid log-probability is obtained. If the log-probability is still not valid after `tries` attempts, the original ZeroProbability error is raised. :Parameters: stochclass : Stochastic, eg. Normal, Uniform, ... The Stochastic distribution to instantiate. tries : int Maximum number of times parents will be sampled. *args, **kwds Positional and keyword arguments to declare the Stochastic variable. :Example: >>> lower = pymc.Uniform('lower', 0., 2., value=1.5, rseed=True) >>> pymc.robust_init(pymc.Uniform, 100, 'data', lower=lower, upper=5, value=[1,2,3,4], observed=True) """ # Find the direct parents stochs = [arg for arg in (list(args) + list(kwds.values())) if isinstance(arg.__class__, StochasticMeta)] # Find the extended parents parents = stochs for s in stochs: parents.extend(s.extended_parents) extended_parents = set(parents) # Select the parents with a random method. random_parents = [ p for p in extended_parents if p.rseed is True and hasattr( p, 'random')] for i in range(tries): try: return stochclass(*args, **kwds) except ZeroProbability: exc = sys.exc_info() for parent in random_parents: try: parent.random() except: six.reraise(*exc) six.reraise(*exc)
[ "def", "robust_init", "(", "stochclass", ",", "tries", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "# Find the direct parents", "stochs", "=", "[", "arg", "for", "arg", "in", "(", "list", "(", "args", ")", "+", "list", "(", "kwds", ".", "value...
Robust initialization of a Stochastic. If the evaluation of the log-probability returns a ZeroProbability error, due for example to a parent being outside of the support for this Stochastic, the values of parents are randomly sampled until a valid log-probability is obtained. If the log-probability is still not valid after `tries` attempts, the original ZeroProbability error is raised. :Parameters: stochclass : Stochastic, eg. Normal, Uniform, ... The Stochastic distribution to instantiate. tries : int Maximum number of times parents will be sampled. *args, **kwds Positional and keyword arguments to declare the Stochastic variable. :Example: >>> lower = pymc.Uniform('lower', 0., 2., value=1.5, rseed=True) >>> pymc.robust_init(pymc.Uniform, 100, 'data', lower=lower, upper=5, value=[1,2,3,4], observed=True)
[ "Robust", "initialization", "of", "a", "Stochastic", "." ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/InstantiationDecorators.py#L300-L351
225,285
pymc-devs/pymc
pymc/examples/gp/more_examples/MKMsalmon/salmon.py
salmon.plot
def plot(self): """ Plot posterior from simple nonstochetric regression. """ figure() plot_envelope(self.M, self.C, self.xplot) for i in range(3): f = Realization(self.M, self.C) plot(self.xplot,f(self.xplot)) plot(self.abundance, self.frye, 'k.', markersize=4) xlabel('Female abundance') ylabel('Frye density') title(self.name) axis('tight')
python
def plot(self): """ Plot posterior from simple nonstochetric regression. """ figure() plot_envelope(self.M, self.C, self.xplot) for i in range(3): f = Realization(self.M, self.C) plot(self.xplot,f(self.xplot)) plot(self.abundance, self.frye, 'k.', markersize=4) xlabel('Female abundance') ylabel('Frye density') title(self.name) axis('tight')
[ "def", "plot", "(", "self", ")", ":", "figure", "(", ")", "plot_envelope", "(", "self", ".", "M", ",", "self", ".", "C", ",", "self", ".", "xplot", ")", "for", "i", "in", "range", "(", "3", ")", ":", "f", "=", "Realization", "(", "self", ".", ...
Plot posterior from simple nonstochetric regression.
[ "Plot", "posterior", "from", "simple", "nonstochetric", "regression", "." ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/examples/gp/more_examples/MKMsalmon/salmon.py#L54-L68
225,286
pymc-devs/pymc
pymc/examples/melanoma.py
survival
def survival(value=t, lam=lam, f=failure): """Exponential survival likelihood, accounting for censoring""" return sum(f * log(lam) - lam * value)
python
def survival(value=t, lam=lam, f=failure): """Exponential survival likelihood, accounting for censoring""" return sum(f * log(lam) - lam * value)
[ "def", "survival", "(", "value", "=", "t", ",", "lam", "=", "lam", ",", "f", "=", "failure", ")", ":", "return", "sum", "(", "f", "*", "log", "(", "lam", ")", "-", "lam", "*", "value", ")" ]
Exponential survival likelihood, accounting for censoring
[ "Exponential", "survival", "likelihood", "accounting", "for", "censoring" ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/examples/melanoma.py#L43-L45
225,287
pymc-devs/pymc
pymc/examples/disaster_model_gof.py
disasters_sim
def disasters_sim(early_mean=early_mean, late_mean=late_mean, switchpoint=switchpoint): """Coal mining disasters sampled from the posterior predictive distribution""" return concatenate((pm.rpoisson(early_mean, size=switchpoint), pm.rpoisson( late_mean, size=n - switchpoint)))
python
def disasters_sim(early_mean=early_mean, late_mean=late_mean, switchpoint=switchpoint): """Coal mining disasters sampled from the posterior predictive distribution""" return concatenate((pm.rpoisson(early_mean, size=switchpoint), pm.rpoisson( late_mean, size=n - switchpoint)))
[ "def", "disasters_sim", "(", "early_mean", "=", "early_mean", ",", "late_mean", "=", "late_mean", ",", "switchpoint", "=", "switchpoint", ")", ":", "return", "concatenate", "(", "(", "pm", ".", "rpoisson", "(", "early_mean", ",", "size", "=", "switchpoint", ...
Coal mining disasters sampled from the posterior predictive distribution
[ "Coal", "mining", "disasters", "sampled", "from", "the", "posterior", "predictive", "distribution" ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/examples/disaster_model_gof.py#L50-L55
225,288
pymc-devs/pymc
pymc/examples/disaster_model_gof.py
expected_values
def expected_values(early_mean=early_mean, late_mean=late_mean, switchpoint=switchpoint): """Discrepancy measure for GOF using the Freeman-Tukey statistic""" # Sample size n = len(disasters_array) # Expected values return concatenate( (ones(switchpoint) * early_mean, ones(n - switchpoint) * late_mean))
python
def expected_values(early_mean=early_mean, late_mean=late_mean, switchpoint=switchpoint): """Discrepancy measure for GOF using the Freeman-Tukey statistic""" # Sample size n = len(disasters_array) # Expected values return concatenate( (ones(switchpoint) * early_mean, ones(n - switchpoint) * late_mean))
[ "def", "expected_values", "(", "early_mean", "=", "early_mean", ",", "late_mean", "=", "late_mean", ",", "switchpoint", "=", "switchpoint", ")", ":", "# Sample size", "n", "=", "len", "(", "disasters_array", ")", "# Expected values", "return", "concatenate", "(", ...
Discrepancy measure for GOF using the Freeman-Tukey statistic
[ "Discrepancy", "measure", "for", "GOF", "using", "the", "Freeman", "-", "Tukey", "statistic" ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/examples/disaster_model_gof.py#L59-L68
225,289
pymc-devs/pymc
pymc/database/pickle.py
load
def load(filename): """Load a pickled database. Return a Database instance. """ file = open(filename, 'rb') container = std_pickle.load(file) file.close() db = Database(file.name) chains = 0 funs = set() for k, v in six.iteritems(container): if k == '_state_': db._state_ = v else: db._traces[k] = Trace(name=k, value=v, db=db) setattr(db, k, db._traces[k]) chains = max(chains, len(v)) funs.add(k) db.chains = chains db.trace_names = chains * [list(funs)] return db
python
def load(filename): """Load a pickled database. Return a Database instance. """ file = open(filename, 'rb') container = std_pickle.load(file) file.close() db = Database(file.name) chains = 0 funs = set() for k, v in six.iteritems(container): if k == '_state_': db._state_ = v else: db._traces[k] = Trace(name=k, value=v, db=db) setattr(db, k, db._traces[k]) chains = max(chains, len(v)) funs.add(k) db.chains = chains db.trace_names = chains * [list(funs)] return db
[ "def", "load", "(", "filename", ")", ":", "file", "=", "open", "(", "filename", ",", "'rb'", ")", "container", "=", "std_pickle", ".", "load", "(", "file", ")", "file", ".", "close", "(", ")", "db", "=", "Database", "(", "file", ".", "name", ")", ...
Load a pickled database. Return a Database instance.
[ "Load", "a", "pickled", "database", "." ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/pickle.py#L77-L100
225,290
pymc-devs/pymc
pymc/database/pickle.py
Database._finalize
def _finalize(self): """Dump traces using cPickle.""" container = {} try: for name in self._traces: container[name] = self._traces[name]._trace container['_state_'] = self._state_ file = open(self.filename, 'w+b') std_pickle.dump(container, file) file.close() except AttributeError: pass
python
def _finalize(self): """Dump traces using cPickle.""" container = {} try: for name in self._traces: container[name] = self._traces[name]._trace container['_state_'] = self._state_ file = open(self.filename, 'w+b') std_pickle.dump(container, file) file.close() except AttributeError: pass
[ "def", "_finalize", "(", "self", ")", ":", "container", "=", "{", "}", "try", ":", "for", "name", "in", "self", ".", "_traces", ":", "container", "[", "name", "]", "=", "self", ".", "_traces", "[", "name", "]", ".", "_trace", "container", "[", "'_s...
Dump traces using cPickle.
[ "Dump", "traces", "using", "cPickle", "." ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/pickle.py#L62-L74
225,291
pymc-devs/pymc
pymc/diagnostics.py
geweke
def geweke(x, first=.1, last=.5, intervals=20, maxlag=20): """Return z-scores for convergence diagnostics. Compare the mean of the first % of series with the mean of the last % of series. x is divided into a number of segments for which this difference is computed. If the series is converged, this score should oscillate between -1 and 1. Parameters ---------- x : array-like The trace of some stochastic parameter. first : float The fraction of series at the beginning of the trace. last : float The fraction of series at the end to be compared with the section at the beginning. intervals : int The number of segments. maxlag : int Maximum autocorrelation lag for estimation of spectral variance Returns ------- scores : list [[]] Return a list of [i, score], where i is the starting index for each interval and score the Geweke score on the interval. Notes ----- The Geweke score on some series x is computed by: .. math:: \frac{E[x_s] - E[x_e]}{\sqrt{V[x_s] + V[x_e]}} where :math:`E` stands for the mean, :math:`V` the variance, :math:`x_s` a section at the start of the series and :math:`x_e` a section at the end of the series. References ---------- Geweke (1992) """ if not has_sm: print("statsmodels not available. Geweke diagnostic cannot be calculated.") return if np.ndim(x) > 1: return [geweke(y, first, last, intervals) for y in np.transpose(x)] # Filter out invalid intervals if first + last >= 1: raise ValueError( "Invalid intervals for Geweke convergence analysis", (first, last)) # Initialize list of z-scores zscores = [None] * intervals # Starting points for calculations starts = np.linspace(0, int(len(x)*(1.-last)), intervals).astype(int) # Loop over start indices for i,s in enumerate(starts): # Size of remaining array x_trunc = x[s:] n = len(x_trunc) # Calculate slices first_slice = x_trunc[:int(first * n)] last_slice = x_trunc[int(last * n):] z = (first_slice.mean() - last_slice.mean()) z /= np.sqrt(spec(first_slice)/len(first_slice) + spec(last_slice)/len(last_slice)) zscores[i] = len(x) - n, z return zscores
python
def geweke(x, first=.1, last=.5, intervals=20, maxlag=20): """Return z-scores for convergence diagnostics. Compare the mean of the first % of series with the mean of the last % of series. x is divided into a number of segments for which this difference is computed. If the series is converged, this score should oscillate between -1 and 1. Parameters ---------- x : array-like The trace of some stochastic parameter. first : float The fraction of series at the beginning of the trace. last : float The fraction of series at the end to be compared with the section at the beginning. intervals : int The number of segments. maxlag : int Maximum autocorrelation lag for estimation of spectral variance Returns ------- scores : list [[]] Return a list of [i, score], where i is the starting index for each interval and score the Geweke score on the interval. Notes ----- The Geweke score on some series x is computed by: .. math:: \frac{E[x_s] - E[x_e]}{\sqrt{V[x_s] + V[x_e]}} where :math:`E` stands for the mean, :math:`V` the variance, :math:`x_s` a section at the start of the series and :math:`x_e` a section at the end of the series. References ---------- Geweke (1992) """ if not has_sm: print("statsmodels not available. Geweke diagnostic cannot be calculated.") return if np.ndim(x) > 1: return [geweke(y, first, last, intervals) for y in np.transpose(x)] # Filter out invalid intervals if first + last >= 1: raise ValueError( "Invalid intervals for Geweke convergence analysis", (first, last)) # Initialize list of z-scores zscores = [None] * intervals # Starting points for calculations starts = np.linspace(0, int(len(x)*(1.-last)), intervals).astype(int) # Loop over start indices for i,s in enumerate(starts): # Size of remaining array x_trunc = x[s:] n = len(x_trunc) # Calculate slices first_slice = x_trunc[:int(first * n)] last_slice = x_trunc[int(last * n):] z = (first_slice.mean() - last_slice.mean()) z /= np.sqrt(spec(first_slice)/len(first_slice) + spec(last_slice)/len(last_slice)) zscores[i] = len(x) - n, z return zscores
[ "def", "geweke", "(", "x", ",", "first", "=", ".1", ",", "last", "=", ".5", ",", "intervals", "=", "20", ",", "maxlag", "=", "20", ")", ":", "if", "not", "has_sm", ":", "print", "(", "\"statsmodels not available. Geweke diagnostic cannot be calculated.\"", "...
Return z-scores for convergence diagnostics. Compare the mean of the first % of series with the mean of the last % of series. x is divided into a number of segments for which this difference is computed. If the series is converged, this score should oscillate between -1 and 1. Parameters ---------- x : array-like The trace of some stochastic parameter. first : float The fraction of series at the beginning of the trace. last : float The fraction of series at the end to be compared with the section at the beginning. intervals : int The number of segments. maxlag : int Maximum autocorrelation lag for estimation of spectral variance Returns ------- scores : list [[]] Return a list of [i, score], where i is the starting index for each interval and score the Geweke score on the interval. Notes ----- The Geweke score on some series x is computed by: .. math:: \frac{E[x_s] - E[x_e]}{\sqrt{V[x_s] + V[x_e]}} where :math:`E` stands for the mean, :math:`V` the variance, :math:`x_s` a section at the start of the series and :math:`x_e` a section at the end of the series. References ---------- Geweke (1992)
[ "Return", "z", "-", "scores", "for", "convergence", "diagnostics", "." ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/diagnostics.py#L236-L315
225,292
pymc-devs/pymc
pymc/diagnostics.py
raftery_lewis
def raftery_lewis(x, q, r, s=.95, epsilon=.001, verbose=1): """ Return the number of iterations needed to achieve a given precision. :Parameters: x : sequence Sampled series. q : float Quantile. r : float Accuracy requested for quantile. s (optional) : float Probability of attaining the requested accuracy (defaults to 0.95). epsilon (optional) : float Half width of the tolerance interval required for the q-quantile (defaults to 0.001). verbose (optional) : int Verbosity level for output (defaults to 1). :Return: nmin : int Minimum number of independent iterates required to achieve the specified accuracy for the q-quantile. kthin : int Skip parameter sufficient to produce a first-order Markov chain. nburn : int Number of iterations to be discarded at the beginning of the simulation, i.e. the number of burn-in iterations. nprec : int Number of iterations not including the burn-in iterations which need to be obtained in order to attain the precision specified by the values of the q, r and s input parameters. kmind : int Minimum skip parameter sufficient to produce an independence chain. :Example: >>> raftery_lewis(x, q=.025, r=.005) :Reference: Raftery, A.E. and Lewis, S.M. (1995). The number of iterations, convergence diagnostics and generic Metropolis algorithms. In Practical Markov Chain Monte Carlo (W.R. Gilks, D.J. Spiegelhalter and S. Richardson, eds.). London, U.K.: Chapman and Hall. See the fortran source file `gibbsit.f` for more details and references. """ if np.ndim(x) > 1: return [raftery_lewis(y, q, r, s, epsilon, verbose) for y in np.transpose(x)] output = nmin, kthin, nburn, nprec, kmind = flib.gibbmain( x, q, r, s, epsilon) if verbose: print_("\n========================") print_("Raftery-Lewis Diagnostic") print_("========================") print_() print_( "%s iterations required (assuming independence) to achieve %s accuracy with %i percent probability." % (nmin, r, 100 * s)) print_() print_( "Thinning factor of %i required to produce a first-order Markov chain." % kthin) print_() print_( "%i iterations to be discarded at the beginning of the simulation (burn-in)." % nburn) print_() print_("%s subsequent iterations required." % nprec) print_() print_( "Thinning factor of %i required to produce an independence chain." % kmind) return output
python
def raftery_lewis(x, q, r, s=.95, epsilon=.001, verbose=1): """ Return the number of iterations needed to achieve a given precision. :Parameters: x : sequence Sampled series. q : float Quantile. r : float Accuracy requested for quantile. s (optional) : float Probability of attaining the requested accuracy (defaults to 0.95). epsilon (optional) : float Half width of the tolerance interval required for the q-quantile (defaults to 0.001). verbose (optional) : int Verbosity level for output (defaults to 1). :Return: nmin : int Minimum number of independent iterates required to achieve the specified accuracy for the q-quantile. kthin : int Skip parameter sufficient to produce a first-order Markov chain. nburn : int Number of iterations to be discarded at the beginning of the simulation, i.e. the number of burn-in iterations. nprec : int Number of iterations not including the burn-in iterations which need to be obtained in order to attain the precision specified by the values of the q, r and s input parameters. kmind : int Minimum skip parameter sufficient to produce an independence chain. :Example: >>> raftery_lewis(x, q=.025, r=.005) :Reference: Raftery, A.E. and Lewis, S.M. (1995). The number of iterations, convergence diagnostics and generic Metropolis algorithms. In Practical Markov Chain Monte Carlo (W.R. Gilks, D.J. Spiegelhalter and S. Richardson, eds.). London, U.K.: Chapman and Hall. See the fortran source file `gibbsit.f` for more details and references. """ if np.ndim(x) > 1: return [raftery_lewis(y, q, r, s, epsilon, verbose) for y in np.transpose(x)] output = nmin, kthin, nburn, nprec, kmind = flib.gibbmain( x, q, r, s, epsilon) if verbose: print_("\n========================") print_("Raftery-Lewis Diagnostic") print_("========================") print_() print_( "%s iterations required (assuming independence) to achieve %s accuracy with %i percent probability." % (nmin, r, 100 * s)) print_() print_( "Thinning factor of %i required to produce a first-order Markov chain." % kthin) print_() print_( "%i iterations to be discarded at the beginning of the simulation (burn-in)." % nburn) print_() print_("%s subsequent iterations required." % nprec) print_() print_( "Thinning factor of %i required to produce an independence chain." % kmind) return output
[ "def", "raftery_lewis", "(", "x", ",", "q", ",", "r", ",", "s", "=", ".95", ",", "epsilon", "=", ".001", ",", "verbose", "=", "1", ")", ":", "if", "np", ".", "ndim", "(", "x", ")", ">", "1", ":", "return", "[", "raftery_lewis", "(", "y", ",",...
Return the number of iterations needed to achieve a given precision. :Parameters: x : sequence Sampled series. q : float Quantile. r : float Accuracy requested for quantile. s (optional) : float Probability of attaining the requested accuracy (defaults to 0.95). epsilon (optional) : float Half width of the tolerance interval required for the q-quantile (defaults to 0.001). verbose (optional) : int Verbosity level for output (defaults to 1). :Return: nmin : int Minimum number of independent iterates required to achieve the specified accuracy for the q-quantile. kthin : int Skip parameter sufficient to produce a first-order Markov chain. nburn : int Number of iterations to be discarded at the beginning of the simulation, i.e. the number of burn-in iterations. nprec : int Number of iterations not including the burn-in iterations which need to be obtained in order to attain the precision specified by the values of the q, r and s input parameters. kmind : int Minimum skip parameter sufficient to produce an independence chain. :Example: >>> raftery_lewis(x, q=.025, r=.005) :Reference: Raftery, A.E. and Lewis, S.M. (1995). The number of iterations, convergence diagnostics and generic Metropolis algorithms. In Practical Markov Chain Monte Carlo (W.R. Gilks, D.J. Spiegelhalter and S. Richardson, eds.). London, U.K.: Chapman and Hall. See the fortran source file `gibbsit.f` for more details and references.
[ "Return", "the", "number", "of", "iterations", "needed", "to", "achieve", "a", "given", "precision", "." ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/diagnostics.py#L321-L400
225,293
pymc-devs/pymc
pymc/diagnostics.py
effective_n
def effective_n(x): """ Returns estimate of the effective sample size of a set of traces. Parameters ---------- x : array-like An array containing the 2 or more traces of a stochastic parameter. That is, an array of dimension m x n x k, where m is the number of traces, n the number of samples, and k the dimension of the stochastic. Returns ------- n_eff : float Return the effective sample size, :math:`\hat{n}_{eff}` Notes ----- The diagnostic is computed by: .. math:: \hat{n}_{eff} = \frac{mn}}{1 + 2 \sum_{t=1}^T \hat{\rho}_t} where :math:`\hat{\rho}_t` is the estimated autocorrelation at lag t, and T is the first odd positive integer for which the sum :math:`\hat{\rho}_{T+1} + \hat{\rho}_{T+1}` is negative. References ---------- Gelman et al. (2014)""" if np.shape(x) < (2,): raise ValueError( 'Calculation of effective sample size requires multiple chains of the same length.') try: m, n = np.shape(x) except ValueError: return [effective_n(np.transpose(y)) for y in np.transpose(x)] s2 = gelman_rubin(x, return_var=True) negative_autocorr = False t = 1 variogram = lambda t: (sum(sum((x[j][i] - x[j][i-t])**2 for i in range(t,n)) for j in range(m)) / (m*(n - t))) rho = np.ones(n) # Iterate until the sum of consecutive estimates of autocorrelation is negative while not negative_autocorr and (t < n): rho[t] = 1. - variogram(t)/(2.*s2) if not t % 2: negative_autocorr = sum(rho[t-1:t+1]) < 0 t += 1 return int(m*n / (1 + 2*rho[1:t].sum()))
python
def effective_n(x): """ Returns estimate of the effective sample size of a set of traces. Parameters ---------- x : array-like An array containing the 2 or more traces of a stochastic parameter. That is, an array of dimension m x n x k, where m is the number of traces, n the number of samples, and k the dimension of the stochastic. Returns ------- n_eff : float Return the effective sample size, :math:`\hat{n}_{eff}` Notes ----- The diagnostic is computed by: .. math:: \hat{n}_{eff} = \frac{mn}}{1 + 2 \sum_{t=1}^T \hat{\rho}_t} where :math:`\hat{\rho}_t` is the estimated autocorrelation at lag t, and T is the first odd positive integer for which the sum :math:`\hat{\rho}_{T+1} + \hat{\rho}_{T+1}` is negative. References ---------- Gelman et al. (2014)""" if np.shape(x) < (2,): raise ValueError( 'Calculation of effective sample size requires multiple chains of the same length.') try: m, n = np.shape(x) except ValueError: return [effective_n(np.transpose(y)) for y in np.transpose(x)] s2 = gelman_rubin(x, return_var=True) negative_autocorr = False t = 1 variogram = lambda t: (sum(sum((x[j][i] - x[j][i-t])**2 for i in range(t,n)) for j in range(m)) / (m*(n - t))) rho = np.ones(n) # Iterate until the sum of consecutive estimates of autocorrelation is negative while not negative_autocorr and (t < n): rho[t] = 1. - variogram(t)/(2.*s2) if not t % 2: negative_autocorr = sum(rho[t-1:t+1]) < 0 t += 1 return int(m*n / (1 + 2*rho[1:t].sum()))
[ "def", "effective_n", "(", "x", ")", ":", "if", "np", ".", "shape", "(", "x", ")", "<", "(", "2", ",", ")", ":", "raise", "ValueError", "(", "'Calculation of effective sample size requires multiple chains of the same length.'", ")", "try", ":", "m", ",", "n", ...
Returns estimate of the effective sample size of a set of traces. Parameters ---------- x : array-like An array containing the 2 or more traces of a stochastic parameter. That is, an array of dimension m x n x k, where m is the number of traces, n the number of samples, and k the dimension of the stochastic. Returns ------- n_eff : float Return the effective sample size, :math:`\hat{n}_{eff}` Notes ----- The diagnostic is computed by: .. math:: \hat{n}_{eff} = \frac{mn}}{1 + 2 \sum_{t=1}^T \hat{\rho}_t} where :math:`\hat{\rho}_t` is the estimated autocorrelation at lag t, and T is the first odd positive integer for which the sum :math:`\hat{\rho}_{T+1} + \hat{\rho}_{T+1}` is negative. References ---------- Gelman et al. (2014)
[ "Returns", "estimate", "of", "the", "effective", "sample", "size", "of", "a", "set", "of", "traces", "." ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/diagnostics.py#L497-L552
225,294
pymc-devs/pymc
pymc/diagnostics.py
gelman_rubin
def gelman_rubin(x, return_var=False): """ Returns estimate of R for a set of traces. The Gelman-Rubin diagnostic tests for lack of convergence by comparing the variance between multiple chains to the variance within each chain. If convergence has been achieved, the between-chain and within-chain variances should be identical. To be most effective in detecting evidence for nonconvergence, each chain should have been initialized to starting values that are dispersed relative to the target distribution. Parameters ---------- x : array-like An array containing the 2 or more traces of a stochastic parameter. That is, an array of dimension m x n x k, where m is the number of traces, n the number of samples, and k the dimension of the stochastic. return_var : bool Flag for returning the marginal posterior variance instead of R-hat (defaults of False). Returns ------- Rhat : float Return the potential scale reduction factor, :math:`\hat{R}` Notes ----- The diagnostic is computed by: .. math:: \hat{R} = \sqrt{\frac{\hat{V}}{W}} where :math:`W` is the within-chain variance and :math:`\hat{V}` is the posterior variance estimate for the pooled traces. This is the potential scale reduction factor, which converges to unity when each of the traces is a sample from the target posterior. Values greater than one indicate that one or more chains have not yet converged. References ---------- Brooks and Gelman (1998) Gelman and Rubin (1992)""" if np.shape(x) < (2,): raise ValueError( 'Gelman-Rubin diagnostic requires multiple chains of the same length.') try: m, n = np.shape(x) except ValueError: return [gelman_rubin(np.transpose(y)) for y in np.transpose(x)] # Calculate between-chain variance B_over_n = np.sum((np.mean(x, 1) - np.mean(x)) ** 2) / (m - 1) # Calculate within-chain variances W = np.sum( [(x[i] - xbar) ** 2 for i, xbar in enumerate(np.mean(x, 1))]) / (m * (n - 1)) # (over) estimate of variance s2 = W * (n - 1) / n + B_over_n if return_var: return s2 # Pooled posterior variance estimate V = s2 + B_over_n / m # Calculate PSRF R = V / W return np.sqrt(R)
python
def gelman_rubin(x, return_var=False): """ Returns estimate of R for a set of traces. The Gelman-Rubin diagnostic tests for lack of convergence by comparing the variance between multiple chains to the variance within each chain. If convergence has been achieved, the between-chain and within-chain variances should be identical. To be most effective in detecting evidence for nonconvergence, each chain should have been initialized to starting values that are dispersed relative to the target distribution. Parameters ---------- x : array-like An array containing the 2 or more traces of a stochastic parameter. That is, an array of dimension m x n x k, where m is the number of traces, n the number of samples, and k the dimension of the stochastic. return_var : bool Flag for returning the marginal posterior variance instead of R-hat (defaults of False). Returns ------- Rhat : float Return the potential scale reduction factor, :math:`\hat{R}` Notes ----- The diagnostic is computed by: .. math:: \hat{R} = \sqrt{\frac{\hat{V}}{W}} where :math:`W` is the within-chain variance and :math:`\hat{V}` is the posterior variance estimate for the pooled traces. This is the potential scale reduction factor, which converges to unity when each of the traces is a sample from the target posterior. Values greater than one indicate that one or more chains have not yet converged. References ---------- Brooks and Gelman (1998) Gelman and Rubin (1992)""" if np.shape(x) < (2,): raise ValueError( 'Gelman-Rubin diagnostic requires multiple chains of the same length.') try: m, n = np.shape(x) except ValueError: return [gelman_rubin(np.transpose(y)) for y in np.transpose(x)] # Calculate between-chain variance B_over_n = np.sum((np.mean(x, 1) - np.mean(x)) ** 2) / (m - 1) # Calculate within-chain variances W = np.sum( [(x[i] - xbar) ** 2 for i, xbar in enumerate(np.mean(x, 1))]) / (m * (n - 1)) # (over) estimate of variance s2 = W * (n - 1) / n + B_over_n if return_var: return s2 # Pooled posterior variance estimate V = s2 + B_over_n / m # Calculate PSRF R = V / W return np.sqrt(R)
[ "def", "gelman_rubin", "(", "x", ",", "return_var", "=", "False", ")", ":", "if", "np", ".", "shape", "(", "x", ")", "<", "(", "2", ",", ")", ":", "raise", "ValueError", "(", "'Gelman-Rubin diagnostic requires multiple chains of the same length.'", ")", "try",...
Returns estimate of R for a set of traces. The Gelman-Rubin diagnostic tests for lack of convergence by comparing the variance between multiple chains to the variance within each chain. If convergence has been achieved, the between-chain and within-chain variances should be identical. To be most effective in detecting evidence for nonconvergence, each chain should have been initialized to starting values that are dispersed relative to the target distribution. Parameters ---------- x : array-like An array containing the 2 or more traces of a stochastic parameter. That is, an array of dimension m x n x k, where m is the number of traces, n the number of samples, and k the dimension of the stochastic. return_var : bool Flag for returning the marginal posterior variance instead of R-hat (defaults of False). Returns ------- Rhat : float Return the potential scale reduction factor, :math:`\hat{R}` Notes ----- The diagnostic is computed by: .. math:: \hat{R} = \sqrt{\frac{\hat{V}}{W}} where :math:`W` is the within-chain variance and :math:`\hat{V}` is the posterior variance estimate for the pooled traces. This is the potential scale reduction factor, which converges to unity when each of the traces is a sample from the target posterior. Values greater than one indicate that one or more chains have not yet converged. References ---------- Brooks and Gelman (1998) Gelman and Rubin (1992)
[ "Returns", "estimate", "of", "R", "for", "a", "set", "of", "traces", "." ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/diagnostics.py#L556-L627
225,295
pymc-devs/pymc
pymc/diagnostics.py
_find_max_lag
def _find_max_lag(x, rho_limit=0.05, maxmaxlag=20000, verbose=0): """Automatically find an appropriate maximum lag to calculate IAT""" # Fetch autocovariance matrix acv = autocov(x) # Calculate rho rho = acv[0, 1] / acv[0, 0] lam = -1. / np.log(abs(rho)) # Initial guess at 1.5 times lambda (i.e. 3 times mean life) maxlag = int(np.floor(3. * lam)) + 1 # Jump forward 1% of lambda to look for rholimit threshold jump = int(np.ceil(0.01 * lam)) + 1 T = len(x) while ((abs(rho) > rho_limit) & (maxlag < min(T / 2, maxmaxlag))): acv = autocov(x, maxlag) rho = acv[0, 1] / acv[0, 0] maxlag += jump # Add 30% for good measure maxlag = int(np.floor(1.3 * maxlag)) if maxlag >= min(T / 2, maxmaxlag): maxlag = min(min(T / 2, maxlag), maxmaxlag) "maxlag fixed to %d" % maxlag return maxlag if maxlag <= 1: print_("maxlag = %d, fixing value to 10" % maxlag) return 10 if verbose: print_("maxlag = %d" % maxlag) return maxlag
python
def _find_max_lag(x, rho_limit=0.05, maxmaxlag=20000, verbose=0): """Automatically find an appropriate maximum lag to calculate IAT""" # Fetch autocovariance matrix acv = autocov(x) # Calculate rho rho = acv[0, 1] / acv[0, 0] lam = -1. / np.log(abs(rho)) # Initial guess at 1.5 times lambda (i.e. 3 times mean life) maxlag = int(np.floor(3. * lam)) + 1 # Jump forward 1% of lambda to look for rholimit threshold jump = int(np.ceil(0.01 * lam)) + 1 T = len(x) while ((abs(rho) > rho_limit) & (maxlag < min(T / 2, maxmaxlag))): acv = autocov(x, maxlag) rho = acv[0, 1] / acv[0, 0] maxlag += jump # Add 30% for good measure maxlag = int(np.floor(1.3 * maxlag)) if maxlag >= min(T / 2, maxmaxlag): maxlag = min(min(T / 2, maxlag), maxmaxlag) "maxlag fixed to %d" % maxlag return maxlag if maxlag <= 1: print_("maxlag = %d, fixing value to 10" % maxlag) return 10 if verbose: print_("maxlag = %d" % maxlag) return maxlag
[ "def", "_find_max_lag", "(", "x", ",", "rho_limit", "=", "0.05", ",", "maxmaxlag", "=", "20000", ",", "verbose", "=", "0", ")", ":", "# Fetch autocovariance matrix", "acv", "=", "autocov", "(", "x", ")", "# Calculate rho", "rho", "=", "acv", "[", "0", ",...
Automatically find an appropriate maximum lag to calculate IAT
[ "Automatically", "find", "an", "appropriate", "maximum", "lag", "to", "calculate", "IAT" ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/diagnostics.py#L630-L668
225,296
pymc-devs/pymc
pymc/diagnostics.py
ppp_value
def ppp_value(simdata, trueval, round=3): """ Calculates posterior predictive p-values on data simulated from the posterior predictive distribution, returning the quantile of the observed data relative to simulated. The posterior predictive p-value is computed by: .. math:: Pr(T(y^{\text{sim}} > T(y) | y) where T is a test statistic of interest and :math:`y^{\text{sim}}` is the simulated data. :Arguments: simdata: array or PyMC object Trace of simulated data or the PyMC stochastic object containing trace. trueval: numeric True (observed) value of the data round: int Rounding of returned quantile (defaults to 3) """ if ndim(trueval) == 1 and ndim(simdata == 2): # Iterate over more than one set of data return [post_pred_checks(simdata[:, i], trueval[i]) for i in range(len(trueval))] return (simdata > trueval).mean()
python
def ppp_value(simdata, trueval, round=3): """ Calculates posterior predictive p-values on data simulated from the posterior predictive distribution, returning the quantile of the observed data relative to simulated. The posterior predictive p-value is computed by: .. math:: Pr(T(y^{\text{sim}} > T(y) | y) where T is a test statistic of interest and :math:`y^{\text{sim}}` is the simulated data. :Arguments: simdata: array or PyMC object Trace of simulated data or the PyMC stochastic object containing trace. trueval: numeric True (observed) value of the data round: int Rounding of returned quantile (defaults to 3) """ if ndim(trueval) == 1 and ndim(simdata == 2): # Iterate over more than one set of data return [post_pred_checks(simdata[:, i], trueval[i]) for i in range(len(trueval))] return (simdata > trueval).mean()
[ "def", "ppp_value", "(", "simdata", ",", "trueval", ",", "round", "=", "3", ")", ":", "if", "ndim", "(", "trueval", ")", "==", "1", "and", "ndim", "(", "simdata", "==", "2", ")", ":", "# Iterate over more than one set of data", "return", "[", "post_pred_ch...
Calculates posterior predictive p-values on data simulated from the posterior predictive distribution, returning the quantile of the observed data relative to simulated. The posterior predictive p-value is computed by: .. math:: Pr(T(y^{\text{sim}} > T(y) | y) where T is a test statistic of interest and :math:`y^{\text{sim}}` is the simulated data. :Arguments: simdata: array or PyMC object Trace of simulated data or the PyMC stochastic object containing trace. trueval: numeric True (observed) value of the data round: int Rounding of returned quantile (defaults to 3)
[ "Calculates", "posterior", "predictive", "p", "-", "values", "on", "data", "simulated", "from", "the", "posterior", "predictive", "distribution", "returning", "the", "quantile", "of", "the", "observed", "data", "relative", "to", "simulated", "." ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/diagnostics.py#L705-L735
225,297
pymc-devs/pymc
pymc/Model.py
check_valid_object_name
def check_valid_object_name(sequence): """Check that the names of the objects are all different.""" names = [] for o in sequence: if o.__name__ in names: raise ValueError( 'A tallyable PyMC object called %s already exists. This will cause problems for some database backends.' % o.__name__) else: names.append(o.__name__)
python
def check_valid_object_name(sequence): """Check that the names of the objects are all different.""" names = [] for o in sequence: if o.__name__ in names: raise ValueError( 'A tallyable PyMC object called %s already exists. This will cause problems for some database backends.' % o.__name__) else: names.append(o.__name__)
[ "def", "check_valid_object_name", "(", "sequence", ")", ":", "names", "=", "[", "]", "for", "o", "in", "sequence", ":", "if", "o", ".", "__name__", "in", "names", ":", "raise", "ValueError", "(", "'A tallyable PyMC object called %s already exists. This will cause pr...
Check that the names of the objects are all different.
[ "Check", "that", "the", "names", "of", "the", "objects", "are", "all", "different", "." ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Model.py#L847-L856
225,298
pymc-devs/pymc
pymc/Model.py
Model.seed
def seed(self): """ Seed new initial values for the stochastics. """ for generation in self.generations: for s in generation: try: if s.rseed is not None: value = s.random(**s.parents.value) except: pass
python
def seed(self): """ Seed new initial values for the stochastics. """ for generation in self.generations: for s in generation: try: if s.rseed is not None: value = s.random(**s.parents.value) except: pass
[ "def", "seed", "(", "self", ")", ":", "for", "generation", "in", "self", ".", "generations", ":", "for", "s", "in", "generation", ":", "try", ":", "if", "s", ".", "rseed", "is", "not", "None", ":", "value", "=", "s", ".", "random", "(", "*", "*",...
Seed new initial values for the stochastics.
[ "Seed", "new", "initial", "values", "for", "the", "stochastics", "." ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Model.py#L114-L125
225,299
pymc-devs/pymc
pymc/Model.py
Model.get_node
def get_node(self, node_name): """Retrieve node with passed name""" for node in self.nodes: if node.__name__ == node_name: return node
python
def get_node(self, node_name): """Retrieve node with passed name""" for node in self.nodes: if node.__name__ == node_name: return node
[ "def", "get_node", "(", "self", ",", "node_name", ")", ":", "for", "node", "in", "self", ".", "nodes", ":", "if", "node", ".", "__name__", "==", "node_name", ":", "return", "node" ]
Retrieve node with passed name
[ "Retrieve", "node", "with", "passed", "name" ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Model.py#L127-L131